Version 1.9.0-dev.9.0
svn merge -r 43712:44015 https://dart.googlecode.com/svn/branches/bleeding_edge trunk
git-svn-id: http://dart.googlecode.com/svn/trunk@44017 260f80e4-7a28-3924-810f-c04153c831b5
diff --git a/create_sdk.gyp b/create_sdk.gyp
index 17b3ce2..721066a 100644
--- a/create_sdk.gyp
+++ b/create_sdk.gyp
@@ -24,9 +24,9 @@
# the pub directory instead of in tests/pub. Xcode can only handle
# a certain amount of files in one list (also depending on the
# length of the path from where you run). This regexp excludes
- # pub/test and pub_generated/test
+ # pub/test
'<!@(["python", "tools/list_files.py",'
- '"^(?!.*pub/test)(?!.*pub_generated/test).*dart$",'
+ '"^(?!.*pub/test).*dart$",'
'"sdk/lib"])',
'<!@(["python", "tools/list_files.py", "", '
'"sdk/lib/_internal/compiler/js_lib/preambles"])',
diff --git a/pkg/analysis_server/doc/api.html b/pkg/analysis_server/doc/api.html
index dc915b3..9656d5c 100644
--- a/pkg/analysis_server/doc/api.html
+++ b/pkg/analysis_server/doc/api.html
@@ -205,6 +205,16 @@
</ul>
</dd>
</dl>
+ <dl>
+ <dt>--no-index</dt>
+ <dd>
+ Disable the server from generating an index. If this flag is passed and an
+ API is used that requires an index, then an error, <tt>NO_INDEX_GENERATED</tt>,
+ will be thrown. The set of API calls that require an index include:
+ refactoring calls, code completions and searching.
+
+ </dd>
+ </dl>
</blockquote>
<h2 class="domain"><a name="domain_server">Domain: server</a></h2>
<p>
@@ -2523,7 +2533,7 @@
An enumeration of the kinds of elements.
</p>
- <dl><dt class="value">CLASS</dt><dt class="value">CLASS_TYPE_ALIAS</dt><dt class="value">COMPILATION_UNIT</dt><dt class="value">CONSTRUCTOR</dt><dt class="value">FIELD</dt><dt class="value">FUNCTION</dt><dt class="value">FUNCTION_TYPE_ALIAS</dt><dt class="value">GETTER</dt><dt class="value">LABEL</dt><dt class="value">LIBRARY</dt><dt class="value">LOCAL_VARIABLE</dt><dt class="value">METHOD</dt><dt class="value">PARAMETER</dt><dt class="value">PREFIX</dt><dt class="value">SETTER</dt><dt class="value">TOP_LEVEL_VARIABLE</dt><dt class="value">TYPE_PARAMETER</dt><dt class="value">UNIT_TEST_GROUP</dt><dt class="value">UNIT_TEST_TEST</dt><dt class="value">UNKNOWN</dt></dl></dd><dt class="typeDefinition"><a name="type_ExecutableFile">ExecutableFile: object</a></dt><dd>
+ <dl><dt class="value">CLASS</dt><dt class="value">CLASS_TYPE_ALIAS</dt><dt class="value">COMPILATION_UNIT</dt><dt class="value">CONSTRUCTOR</dt><dt class="value">ENUM</dt><dt class="value">ENUM_CONSTANT</dt><dt class="value">FIELD</dt><dt class="value">FUNCTION</dt><dt class="value">FUNCTION_TYPE_ALIAS</dt><dt class="value">GETTER</dt><dt class="value">LABEL</dt><dt class="value">LIBRARY</dt><dt class="value">LOCAL_VARIABLE</dt><dt class="value">METHOD</dt><dt class="value">PARAMETER</dt><dt class="value">PREFIX</dt><dt class="value">SETTER</dt><dt class="value">TOP_LEVEL_VARIABLE</dt><dt class="value">TYPE_PARAMETER</dt><dt class="value">UNIT_TEST_GROUP</dt><dt class="value">UNIT_TEST_TEST</dt><dt class="value">UNKNOWN</dt></dl></dd><dt class="typeDefinition"><a name="type_ExecutableFile">ExecutableFile: object</a></dt><dd>
<p>
A description of an executable file.
</p>
@@ -3115,7 +3125,7 @@
</dd><dt class="value">INVALID_OVERLAY_CHANGE</dt><dd>
<p>
- An analysis.updateContent request contained a
+ An "analysis.updateContent" request contained a
ChangeContentOverlay object which can't be applied, due
to an edit having an offset or length that is out of
range.
@@ -3130,6 +3140,12 @@
<p>
A malformed request was received.
</p>
+ </dd><dt class="value">NO_INDEX_GENERATED</dt><dd>
+
+ <p>
+ The "--no-index" flag was passed when the analysis server created,
+ but this API call requires an index to have been generated.
+ </p>
</dd><dt class="value">REFACTORING_REQUEST_CANCELLED</dt><dd>
<p>
diff --git a/pkg/analysis_server/lib/src/analysis_server.dart b/pkg/analysis_server/lib/src/analysis_server.dart
index ab012fe..0154d14 100644
--- a/pkg/analysis_server/lib/src/analysis_server.dart
+++ b/pkg/analysis_server/lib/src/analysis_server.dart
@@ -28,6 +28,7 @@
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart';
+import 'package:analyzer/src/generated/utilities_general.dart';
typedef void OptionUpdater(AnalysisOptionsImpl options);
@@ -88,14 +89,14 @@
final ResourceProvider resourceProvider;
/**
- * The [Index] for this server.
+ * The [Index] for this server, may be `null` if indexing is disabled.
*/
final Index index;
/**
- * The [SearchEngine] for this server.
+ * The [SearchEngine] for this server, may be `null` if indexing is disabled.
*/
- SearchEngine searchEngine;
+ final SearchEngine searchEngine;
/**
* [ContextManager] which handles the mapping from analysis roots
@@ -229,7 +230,7 @@
* The current state of overlays from the client. This is used as the
* content cache for all contexts.
*/
- ContentCache _overlayState = new ContentCache();
+ final ContentCache overlayState = new ContentCache();
/**
* Initialize a newly created server to receive requests from and send
@@ -241,11 +242,12 @@
* running a full analysis server.
*/
AnalysisServer(this.channel, this.resourceProvider,
- PackageMapProvider packageMapProvider, this.index,
+ PackageMapProvider packageMapProvider, Index _index,
AnalysisServerOptions analysisServerOptions, this.defaultSdk,
- this.instrumentationService, {this.rethrowExceptions: true}) {
+ this.instrumentationService, {this.rethrowExceptions: true})
+ : index = _index,
+ searchEngine = _index != null ? createSearchEngine(_index) : null {
_performance = performanceDuringStartup;
- searchEngine = createSearchEngine(index);
operationQueue = new ServerOperationQueue();
contextDirectoryManager =
new ServerContextManager(this, resourceProvider, packageMapProvider);
@@ -372,7 +374,7 @@
return null;
}
// check if there is a context that analyzed this source
- return getAnalysisContextForSource(getSource(path));
+ return getAnalysisContextForSource(_getSourceWithoutContext(path));
}
/**
@@ -495,32 +497,6 @@
// }
/**
- * Returns resolved [CompilationUnit]s of the Dart file with the given [path].
- *
- * May be empty, but not `null`.
- */
- List<CompilationUnit> getResolvedCompilationUnits(String path) {
- List<CompilationUnit> units = <CompilationUnit>[];
- // prepare AnalysisContext
- AnalysisContext context = getAnalysisContext(path);
- if (context == null) {
- return units;
- }
- // add a unit for each unit/library combination
- Source unitSource = getSource(path);
- List<Source> librarySources = context.getLibrariesContaining(unitSource);
- for (Source librarySource in librarySources) {
- CompilationUnit unit =
- context.resolveCompilationUnit2(unitSource, librarySource);
- if (unit != null) {
- units.add(unit);
- }
- }
- // done
- return units;
- }
-
- /**
* Returns the [CompilationUnit] of the Dart file with the given [path] that
* should be used to resend notifications for already resolved unit.
* Returns `null` if the file is not a part of any context, library has not
@@ -548,6 +524,32 @@
}
/**
+ * Returns resolved [CompilationUnit]s of the Dart file with the given [path].
+ *
+ * May be empty, but not `null`.
+ */
+ List<CompilationUnit> getResolvedCompilationUnits(String path) {
+ List<CompilationUnit> units = <CompilationUnit>[];
+ // prepare AnalysisContext
+ AnalysisContext context = getAnalysisContext(path);
+ if (context == null) {
+ return units;
+ }
+ // add a unit for each unit/library combination
+ Source unitSource = getSource(path);
+ List<Source> librarySources = context.getLibrariesContaining(unitSource);
+ for (Source librarySource in librarySources) {
+ CompilationUnit unit =
+ context.resolveCompilationUnit2(unitSource, librarySource);
+ if (unit != null) {
+ units.add(unit);
+ }
+ }
+ // done
+ return units;
+ }
+
+ /**
* Return the [Source] of the Dart file with the given [path].
*/
Source getSource(String path) {
@@ -561,7 +563,7 @@
}
// file-based source
File file = resourceProvider.getResource(path);
- return file.createSource();
+ return ContextManager.createSourceInContext(getAnalysisContext(path), file);
}
/**
@@ -570,32 +572,34 @@
void handleRequest(Request request) {
_performance.logRequest(request);
runZoned(() {
- int count = handlers.length;
- for (int i = 0; i < count; i++) {
- try {
- Response response = handlers[i].handleRequest(request);
- if (response == Response.DELAYED_RESPONSE) {
+ ServerPerformanceStatistics.serverRequests.makeCurrentWhile(() {
+ int count = handlers.length;
+ for (int i = 0; i < count; i++) {
+ try {
+ Response response = handlers[i].handleRequest(request);
+ if (response == Response.DELAYED_RESPONSE) {
+ return;
+ }
+ if (response != null) {
+ channel.sendResponse(response);
+ return;
+ }
+ } on RequestFailure catch (exception) {
+ channel.sendResponse(exception.response);
return;
- }
- if (response != null) {
+ } catch (exception, stackTrace) {
+ RequestError error =
+ new RequestError(RequestErrorCode.SERVER_ERROR, exception.toString());
+ if (stackTrace != null) {
+ error.stackTrace = stackTrace.toString();
+ }
+ Response response = new Response(request.id, error: error);
channel.sendResponse(response);
return;
}
- } on RequestFailure catch (exception) {
- channel.sendResponse(exception.response);
- return;
- } catch (exception, stackTrace) {
- RequestError error =
- new RequestError(RequestErrorCode.SERVER_ERROR, exception.toString());
- if (stackTrace != null) {
- error.stackTrace = stackTrace.toString();
- }
- Response response = new Response(request.id, error: error);
- channel.sendResponse(response);
- return;
}
- }
- channel.sendResponse(new Response.unknownRequest(request));
+ channel.sendResponse(new Response.unknownRequest(request));
+ });
}, onError: (exception, stackTrace) {
sendServerErrorNotification(exception, stackTrace, fatal: true);
});
@@ -655,6 +659,7 @@
*/
void performOperation() {
assert(performOperationPending);
+ PerformanceTag.UNKNOWN.makeCurrent();
performOperationPending = false;
if (!running) {
// An error has occurred, or the connection to the client has been
@@ -669,6 +674,7 @@
// This can happen if the operation queue is cleared while the operation
// loop is in progress. No problem; we just need to exit the operation
// loop and wait for the next operation to be added.
+ ServerPerformanceStatistics.idle.makeCurrent();
return;
}
sendStatusNotification(operation);
@@ -686,6 +692,7 @@
shutdown();
} finally {
if (!operationQueue.isEmpty) {
+ ServerPerformanceStatistics.intertask.makeCurrent();
_schedulePerformOperation();
} else {
sendStatusNotification(null);
@@ -693,6 +700,7 @@
_onAnalysisCompleteCompleter.complete();
_onAnalysisCompleteCompleter = null;
}
+ ServerPerformanceStatistics.idle.makeCurrent();
}
}
}
@@ -973,7 +981,7 @@
Source source = getSource(file);
operationQueue.sourceAboutToChange(source);
// Prepare the new contents.
- String oldContents = _overlayState.getContents(source);
+ String oldContents = overlayState.getContents(source);
String newContents;
if (change is AddContentOverlay) {
newContents = change.content;
@@ -1004,7 +1012,7 @@
// Protocol parsing should have ensured that we never get here.
throw new AnalysisException('Illegal change type');
}
- _overlayState.setContents(source, newContents);
+ overlayState.setContents(source, newContents);
// Update all contexts.
for (InternalAnalysisContext context in folderMap.values) {
if (context.handleContentsChanged(
@@ -1066,6 +1074,24 @@
}
/**
+ * Return the [Source] of the Dart file with the given [path], assuming that
+ * we do not know the context in which the path should be interpreted.
+ */
+ Source _getSourceWithoutContext(String path) {
+ // try SDK
+ {
+ Uri uri = resourceProvider.pathContext.toUri(path);
+ Source sdkSource = defaultSdk.fromFileUri(uri);
+ if (sdkSource != null) {
+ return sdkSource;
+ }
+ }
+ // file-based source
+ File file = resourceProvider.getResource(path);
+ return file.createSource();
+ }
+
+ /**
* Schedules [performOperation] exection.
*/
void _schedulePerformOperation() {
@@ -1099,6 +1125,7 @@
bool enableIncrementalResolutionApi = false;
bool enableIncrementalResolutionValidation = false;
bool noErrorNotification = false;
+ bool noIndex = false;
String fileReadMode = 'as-is';
}
@@ -1169,7 +1196,7 @@
AnalysisContext addContext(Folder folder, UriResolver packageUriResolver) {
InternalAnalysisContext context =
AnalysisEngine.instance.createAnalysisContext();
- context.contentCache = analysisServer._overlayState;
+ context.contentCache = analysisServer.overlayState;
analysisServer.folderMap[folder] = context;
context.sourceFactory = _createSourceFactory(packageUriResolver);
context.analysisOptions = new AnalysisOptionsImpl.con1(defaultOptions);
@@ -1246,6 +1273,41 @@
/**
+ * Container with global [AnalysisServer] performance statistics.
+ */
+class ServerPerformanceStatistics {
+ /**
+ * The [PerformanceTag] for time spent in
+ * PerformAnalysisOperation._updateIndex.
+ */
+ static PerformanceTag index = new PerformanceTag('index');
+
+ /**
+ * The [PerformanceTag] for time spent in
+ * PerformAnalysisOperation._sendNotices.
+ */
+ static PerformanceTag notices = new PerformanceTag('notices');
+
+ /**
+ * The [PerformanceTag] for time spent performing a _DartIndexOperation.
+ */
+ static PerformanceTag indexOperation = new PerformanceTag('indexOperation');
+
+ /**
+ * The [PerformanceTag] for time spent between calls to
+ * AnalysisServer.performOperation when the server is not idle.
+ */
+ static PerformanceTag intertask = new PerformanceTag('intertask');
+
+ /**
+ * The [PerformanceTag] for time spent between calls to
+ * AnalysisServer.performOperation when the server is idle.
+ */
+ static PerformanceTag idle = new PerformanceTag('idle');
+}
+
+
+/**
* A class used by [AnalysisServer] to record performance information
* such as request latency.
*/
@@ -1301,16 +1363,10 @@
*/
class ServerPerformanceStatistics {
/**
- * The [PerformanceTag] for time spent in
- * PerformAnalysisOperation._updateIndex.
+ * The [PerformanceTag] for time spent in [ExecutionDomainHandler].
*/
- static PerformanceTag index = new PerformanceTag('index');
-
- /**
- * The [PerformanceTag] for time spent in
- * PerformAnalysisOperation._sendNotices.
- */
- static PerformanceTag notices = new PerformanceTag('notices');
+ static PerformanceTag executionNotifications =
+ new PerformanceTag('executionNotifications');
/**
* The [PerformanceTag] for time spent performing a _DartIndexOperation.
@@ -1328,4 +1384,25 @@
* AnalysisServer.performOperation when the server is idle.
*/
static PerformanceTag idle = new PerformanceTag('idle');
+
+ /**
+ * The [PerformanceTag] for time spent in
+ * PerformAnalysisOperation._sendNotices.
+ */
+ static PerformanceTag notices = new PerformanceTag('notices');
+
+ /**
+ * The [PerformanceTag] for time spent in server comminication channels.
+ */
+ static PerformanceTag serverChannel = new PerformanceTag('serverChannel');
+
+ /**
+ * The [PerformanceTag] for time spent in server request handlers.
+ */
+ static PerformanceTag serverRequests = new PerformanceTag('serverRequests');
+
+ /**
+ * The [PerformanceTag] for time spent in split store microtasks.
+ */
+ static PerformanceTag splitStore = new PerformanceTag('splitStore');
}
diff --git a/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart b/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart
index 884dcd2..14d7268 100644
--- a/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart
+++ b/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart
@@ -8,6 +8,7 @@
import 'dart:convert';
import 'dart:io';
+import 'package:analysis_server/src/analysis_server.dart';
import 'package:analysis_server/src/channel/channel.dart';
import 'package:analysis_server/src/protocol.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
@@ -120,11 +121,11 @@
if (_closeRequested) {
return;
}
- ServerCommunicationChannel.ToJson.start();
- String jsonEncoding = JSON.encode(notification.toJson());
- ServerCommunicationChannel.ToJson.stop();
- _outputLine(jsonEncoding);
- _instrumentationService.logNotification(jsonEncoding);
+ ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() {
+ String jsonEncoding = JSON.encode(notification.toJson());
+ _outputLine(jsonEncoding);
+ _instrumentationService.logNotification(jsonEncoding);
+ });
}
@override
@@ -134,11 +135,11 @@
if (_closeRequested) {
return;
}
- ServerCommunicationChannel.ToJson.start();
- String jsonEncoding = JSON.encode(response.toJson());
- ServerCommunicationChannel.ToJson.stop();
- _outputLine(jsonEncoding);
- _instrumentationService.logResponse(jsonEncoding);
+ ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() {
+ String jsonEncoding = JSON.encode(response.toJson());
+ _outputLine(jsonEncoding);
+ _instrumentationService.logResponse(jsonEncoding);
+ });
}
/**
@@ -157,16 +158,16 @@
if (_closed.isCompleted) {
return;
}
- _instrumentationService.logRequest(data);
- // Parse the string as a JSON descriptor and process the resulting
- // structure as a request.
- ServerCommunicationChannel.FromJson.start();
- Request request = new Request.fromString(data);
- ServerCommunicationChannel.FromJson.stop();
- if (request == null) {
- sendResponse(new Response.invalidRequestFormat());
- return;
- }
- onRequest(request);
+ ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() {
+ _instrumentationService.logRequest(data);
+ // Parse the string as a JSON descriptor and process the resulting
+ // structure as a request.
+ Request request = new Request.fromString(data);
+ if (request == null) {
+ sendResponse(new Response.invalidRequestFormat());
+ return;
+ }
+ onRequest(request);
+ });
}
}
diff --git a/pkg/analysis_server/lib/src/channel/channel.dart b/pkg/analysis_server/lib/src/channel/channel.dart
index 71ee75e..b90b282 100644
--- a/pkg/analysis_server/lib/src/channel/channel.dart
+++ b/pkg/analysis_server/lib/src/channel/channel.dart
@@ -8,7 +8,6 @@
import 'dart:convert';
import 'package:analysis_server/src/protocol.dart';
-import 'package:analyzer/src/util/utilities_timing.dart';
/**
* Instances of the class [ChannelChunkSink] uses a [Converter] to translate
@@ -127,18 +126,6 @@
*/
abstract class ServerCommunicationChannel {
/**
- * A stopwatch used to accumulate the amount of time spent converting
- * incomming requests from Json to objects.
- */
- static final CountedStopwatch FromJson = new CountedStopwatch();
-
- /**
- * A stopwatch used to accumulate the amount of time spent converting outgoing
- * responses and notifications from objects to Json.
- */
- static final CountedStopwatch ToJson = new CountedStopwatch();
-
- /**
* Close the communication channel.
*/
void close();
diff --git a/pkg/analysis_server/lib/src/channel/web_socket_channel.dart b/pkg/analysis_server/lib/src/channel/web_socket_channel.dart
index b8ddf6d..47af214 100644
--- a/pkg/analysis_server/lib/src/channel/web_socket_channel.dart
+++ b/pkg/analysis_server/lib/src/channel/web_socket_channel.dart
@@ -8,6 +8,7 @@
import 'dart:convert';
import 'dart:io';
+import 'package:analysis_server/src/analysis_server.dart';
import 'package:analysis_server/src/channel/channel.dart';
import 'package:analysis_server/src/protocol.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
@@ -105,14 +106,14 @@
instrumentationService.logRequest(data);
// Parse the string as a JSON descriptor and process the resulting
// structure as a request.
- ServerCommunicationChannel.FromJson.start();
- Request request = new Request.fromString(data);
- ServerCommunicationChannel.FromJson.stop();
- if (request == null) {
- sendResponse(new Response.invalidRequestFormat());
- return;
- }
- onRequest(request);
+ ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() {
+ Request request = new Request.fromString(data);
+ if (request == null) {
+ sendResponse(new Response.invalidRequestFormat());
+ return;
+ }
+ onRequest(request);
+ });
} else if (data is List<int>) {
// TODO(brianwilkerson) Implement a more efficient protocol.
sendResponse(new Response.invalidRequestFormat());
@@ -123,19 +124,19 @@
@override
void sendNotification(Notification notification) {
- ServerCommunicationChannel.ToJson.start();
- String jsonEncoding = JSON.encode(notification.toJson());
- ServerCommunicationChannel.ToJson.stop();
- socket.add(jsonEncoding);
- instrumentationService.logNotification(jsonEncoding);
+ ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() {
+ String jsonEncoding = JSON.encode(notification.toJson());
+ socket.add(jsonEncoding);
+ instrumentationService.logNotification(jsonEncoding);
+ });
}
@override
void sendResponse(Response response) {
- ServerCommunicationChannel.ToJson.start();
- String jsonEncoding = JSON.encode(response.toJson());
- ServerCommunicationChannel.ToJson.stop();
- socket.add(jsonEncoding);
- instrumentationService.logResponse(jsonEncoding);
+ ServerPerformanceStatistics.serverChannel.makeCurrentWhile(() {
+ String jsonEncoding = JSON.encode(response.toJson());
+ socket.add(jsonEncoding);
+ instrumentationService.logResponse(jsonEncoding);
+ });
}
}
diff --git a/pkg/analysis_server/lib/src/computer/computer_navigation.dart b/pkg/analysis_server/lib/src/computer/computer_navigation.dart
index c3081ba..10e0bd0 100644
--- a/pkg/analysis_server/lib/src/computer/computer_navigation.dart
+++ b/pkg/analysis_server/lib/src/computer/computer_navigation.dart
@@ -150,6 +150,18 @@
}
@override
+ visitConstructorName(ConstructorName node) {
+ AstNode parent = node.parent;
+ if (parent is InstanceCreationExpression &&
+ parent.constructorName == node) {
+ _addConstructorName(parent, node);
+ } else if (parent is ConstructorDeclaration &&
+ parent.redirectedConstructor == node) {
+ _addConstructorName(node, node);
+ }
+ }
+
+ @override
visitExportDirective(ExportDirective node) {
ExportElement exportElement = node.element;
if (exportElement != null) {
@@ -176,37 +188,6 @@
}
@override
- visitInstanceCreationExpression(InstanceCreationExpression node) {
- Element element = node.staticElement;
- ConstructorName constructorName = node.constructorName;
- if (element != null && constructorName != null) {
- // if a synthetic constructor, navigate to the class
- if (element.isSynthetic) {
- ClassElement classElement = element.enclosingElement;
- element = classElement;
- }
- // add regions
- TypeName typeName = constructorName.type;
- TypeArgumentList typeArguments = typeName.typeArguments;
- if (typeArguments == null) {
- computer._addRegion_nodeStart_nodeEnd(node, constructorName, element);
- } else {
- computer._addRegion_nodeStart_nodeEnd(node, typeName.name, element);
- // <TypeA, TypeB>
- typeArguments.accept(this);
- // optional ".name"
- if (constructorName.period != null) {
- computer._addRegion_tokenStart_nodeEnd(
- constructorName.period,
- constructorName,
- element);
- }
- }
- }
- _safelyVisit(node.argumentList);
- }
-
- @override
visitPartDirective(PartDirective node) {
computer._addRegion_tokenStart_nodeEnd(
node.keyword,
@@ -262,6 +243,31 @@
_safelyVisit(node.argumentList);
}
+ void _addConstructorName(AstNode parent, ConstructorName node) {
+ Element element = node.staticElement;
+ if (element == null) {
+ return;
+ }
+ // if a synthetic constructor, navigate to the class
+ if (element.isSynthetic) {
+ element = element.enclosingElement;
+ }
+ // add regions
+ TypeName typeName = node.type;
+ TypeArgumentList typeArguments = typeName.typeArguments;
+ if (typeArguments == null) {
+ computer._addRegion_nodeStart_nodeEnd(parent, node, element);
+ } else {
+ computer._addRegion_nodeStart_nodeEnd(parent, typeName.name, element);
+ // <TypeA, TypeB>
+ typeArguments.accept(this);
+ // optional ".name"
+ if (node.period != null) {
+ computer._addRegion_tokenStart_nodeEnd(node.period, node, element);
+ }
+ }
+ }
+
void _safelyVisit(AstNode node) {
if (node != null) {
node.accept(this);
diff --git a/pkg/analysis_server/lib/src/computer/computer_outline.dart b/pkg/analysis_server/lib/src/computer/computer_outline.dart
index be1c3ac..8efd18e 100644
--- a/pkg/analysis_server/lib/src/computer/computer_outline.dart
+++ b/pkg/analysis_server/lib/src/computer/computer_outline.dart
@@ -59,6 +59,14 @@
}
unitContents.add(_newClassOutline(classDeclaration, classContents));
}
+ if (unitMember is EnumDeclaration) {
+ EnumDeclaration enumDeclaration = unitMember;
+ List<Outline> constantOutlines = <Outline>[];
+ for (EnumConstantDeclaration constant in enumDeclaration.constants) {
+ constantOutlines.add(_newEnumConstant(constant));
+ }
+ unitContents.add(_newEnumOutline(enumDeclaration, constantOutlines));
+ }
if (unitMember is TopLevelVariableDeclaration) {
TopLevelVariableDeclaration fieldDeclaration = unitMember;
VariableDeclarationList fields = fieldDeclaration.variables;
@@ -227,6 +235,38 @@
return outline;
}
+ Outline _newEnumConstant(EnumConstantDeclaration node) {
+ SimpleIdentifier nameNode = node.name;
+ String name = nameNode.name;
+ _SourceRegion sourceRegion = _getSourceRegion(node);
+ Element element = new Element(
+ ElementKind.ENUM_CONSTANT,
+ name,
+ Element.makeFlags(
+ isPrivate: Identifier.isPrivateName(name),
+ isDeprecated: _isDeprecated(node)),
+ location: _getLocationNode(nameNode));
+ return new Outline(element, sourceRegion.offset, sourceRegion.length);
+ }
+
+ Outline _newEnumOutline(EnumDeclaration node, List<Outline> children) {
+ SimpleIdentifier nameNode = node.name;
+ String name = nameNode.name;
+ _SourceRegion sourceRegion = _getSourceRegion(node);
+ Element element = new Element(
+ ElementKind.ENUM,
+ name,
+ Element.makeFlags(
+ isPrivate: Identifier.isPrivateName(name),
+ isDeprecated: _isDeprecated(node)),
+ location: _getLocationNode(nameNode));
+ return new Outline(
+ element,
+ sourceRegion.offset,
+ sourceRegion.length,
+ children: nullIfEmpty(children));
+ }
+
Outline _newFunctionOutline(FunctionDeclaration function, bool isStatic) {
TypeName returnType = function.returnType;
SimpleIdentifier nameNode = function.name;
diff --git a/pkg/analysis_server/lib/src/context_manager.dart b/pkg/analysis_server/lib/src/context_manager.dart
index 999c975..e0ad10d 100644
--- a/pkg/analysis_server/lib/src/context_manager.dart
+++ b/pkg/analysis_server/lib/src/context_manager.dart
@@ -272,7 +272,7 @@
continue;
}
// do add the file
- Source source = child.createSource();
+ Source source = createSourceInContext(info.context, child);
changeSet.addedSource(source);
info.sources[path] = source;
} else if (child is Folder) {
@@ -287,8 +287,7 @@
/**
* Resursively adds all Dart and HTML files to the [changeSet].
*/
- void _addSourceFiles(ChangeSet changeSet, Folder folder, _ContextInfo info,
- bool pubspecExists, bool createPackageUri) {
+ void _addSourceFiles(ChangeSet changeSet, Folder folder, _ContextInfo info) {
if (info.excludesResource(folder) || folder.shortName.startsWith('.')) {
return;
}
@@ -302,27 +301,7 @@
// add files, recurse into folders
if (child is File) {
if (_shouldFileBeAnalyzed(child)) {
- Source source = child.createSource();
- if (createPackageUri) {
- //
- // It should be possible to generate the uri by executing:
- //
- // Uri uri = info.context.sourceFactory.restoreUri(source);
- //
- // but for some reason this doesn't produce the same result as the
- // code below. This needs to be investigated.
- // (See https://code.google.com/p/dart/issues/detail?id=22463).
- //
- String packagePath = info.folder.path;
- String packageName =
- resourceProvider.pathContext.basename(packagePath);
- String libPath =
- resourceProvider.pathContext.join(packagePath, LIB_DIR_NAME);
- String relPath = source.fullName.substring(libPath.length);
- Uri uri =
- Uri.parse('${PackageMapUriResolver.PACKAGE_SCHEME}:$packageName$relPath');
- source = child.createSource(uri);
- }
+ Source source = createSourceInContext(info.context, child);
changeSet.addedSource(source);
info.sources[path] = source;
}
@@ -331,19 +310,7 @@
if (shortName == PACKAGES_NAME) {
continue;
}
- if (pubspecExists &&
- !createPackageUri &&
- shortName == LIB_DIR_NAME &&
- child.parent == info.folder) {
- _addSourceFiles(changeSet, child, info, pubspecExists, true);
- } else {
- _addSourceFiles(
- changeSet,
- child,
- info,
- pubspecExists,
- createPackageUri);
- }
+ _addSourceFiles(changeSet, child, info);
}
}
}
@@ -394,6 +361,20 @@
}
/**
+ * Create a new context associated with the given [folder]. The [pubspecFile]
+ * is the `pubspec.yaml` file contained in the folder. Add any sources that
+ * are not included in one of the [children] to the context.
+ */
+ _ContextInfo _createContextWithSources(Folder folder, File pubspecFile,
+ List<_ContextInfo> children) {
+ _ContextInfo info = _createContext(folder, pubspecFile, children);
+ ChangeSet changeSet = new ChangeSet();
+ _addSourceFiles(changeSet, folder, info);
+ applyChangesToContext(folder, changeSet);
+ return info;
+ }
+
+ /**
* Creates a new context associated with [folder].
*
* If there are subfolders with 'pubspec.yaml' files, separate contexts
@@ -410,13 +391,9 @@
List<_ContextInfo> _createContexts(Folder folder, bool withPubspecOnly) {
// check whether there is a pubspec in the folder
File pubspecFile = folder.getChild(PUBSPEC_NAME);
- bool pubspecExists = pubspecFile.exists;
- if (pubspecExists) {
- _ContextInfo info = _createContextWithSources(
- folder,
- pubspecFile,
- pubspecExists,
- <_ContextInfo>[]);
+ if (pubspecFile.exists) {
+ _ContextInfo info =
+ _createContextWithSources(folder, pubspecFile, <_ContextInfo>[]);
return [info];
}
// try to find subfolders with pubspec files
@@ -432,26 +409,11 @@
return children;
}
// OK, create a context without a pubspec
- _createContextWithSources(folder, pubspecFile, pubspecExists, children);
+ _createContextWithSources(folder, pubspecFile, children);
return children;
}
/**
- * Create a new context associated with the given [folder]. The [pubspecFile]
- * is the `pubspec.yaml` file contained in the folder, and [pubspecExists] is
- * `true` if the file exists. Add any sources that are not included in one of
- * the [children] to the context.
- */
- _ContextInfo _createContextWithSources(Folder folder, File pubspecFile,
- bool pubspecExists, List<_ContextInfo> children) {
- _ContextInfo info = _createContext(folder, pubspecFile, children);
- ChangeSet changeSet = new ChangeSet();
- _addSourceFiles(changeSet, folder, info, pubspecExists, false);
- applyChangesToContext(folder, changeSet);
- return info;
- }
-
- /**
* Clean up and destroy the context associated with the given folder.
*/
void _destroyContext(Folder folder) {
@@ -523,7 +485,7 @@
File file = resource;
if (_shouldFileBeAnalyzed(file)) {
ChangeSet changeSet = new ChangeSet();
- Source source = file.createSource();
+ Source source = createSourceInContext(info.context, file);
changeSet.addedSource(source);
applyChangesToContext(folder, changeSet);
info.sources[path] = source;
@@ -628,6 +590,21 @@
updateContextPackageUriResolver(info.folder, packageUriResolver);
}
+ /**
+ * Create and return a source representing the given [file] within the given
+ * [context].
+ */
+ static Source createSourceInContext(AnalysisContext context, File file) {
+ // TODO(brianwilkerson) Optimize this, by allowing support for source
+ // factories to restore URI's from a file path rather than a source.
+ Source source = file.createSource();
+ if (context == null) {
+ return source;
+ }
+ Uri uri = context.sourceFactory.restoreUri(source);
+ return file.createSource(uri);
+ }
+
static bool _shouldFileBeAnalyzed(File file) {
if (!(AnalysisEngine.isDartFileName(file.path) ||
AnalysisEngine.isHtmlFileName(file.path))) {
diff --git a/pkg/analysis_server/lib/src/domain_completion.dart b/pkg/analysis_server/lib/src/domain_completion.dart
index e1ef9fc5..a69dbb1 100644
--- a/pkg/analysis_server/lib/src/domain_completion.dart
+++ b/pkg/analysis_server/lib/src/domain_completion.dart
@@ -28,6 +28,11 @@
final AnalysisServer server;
/**
+ * The [SearchEngine] for this server.
+ */
+ SearchEngine searchEngine;
+
+ /**
* The next completion response id.
*/
int _nextCompletionId = 0;
@@ -71,6 +76,7 @@
CompletionDomainHandler(this.server) {
server.onContextsChanged.listen(contextsChanged);
server.onPriorityChange.listen(priorityChanged);
+ searchEngine = server.searchEngine;
}
/**
@@ -91,7 +97,7 @@
}
_discardManager();
}
- _manager = createCompletionManager(context, source, server.searchEngine);
+ _manager = createCompletionManager(context, source, searchEngine);
if (context != null) {
_sourcesChangedSubscription =
context.onSourcesChanged.listen(sourcesChanged);
@@ -119,6 +125,9 @@
@override
Response handleRequest(Request request) {
+ if (searchEngine == null) {
+ return new Response.noIndexGenerated(request);
+ }
try {
String requestName = request.method;
if (requestName == COMPLETION_GET_SUGGESTIONS) {
diff --git a/pkg/analysis_server/lib/src/domain_execution.dart b/pkg/analysis_server/lib/src/domain_execution.dart
index e1654df..3e5d28c 100644
--- a/pkg/analysis_server/lib/src/domain_execution.dart
+++ b/pkg/analysis_server/lib/src/domain_execution.dart
@@ -158,31 +158,33 @@
}
void _fileAnalyzed(ChangeNotice notice) {
- Source source = notice.source;
- String filePath = source.fullName;
- if (!_isInAnalysisRoot(filePath)) {
- return;
- }
- AnalysisContext context = server.getAnalysisContext(filePath);
- if (AnalysisEngine.isDartFileName(filePath)) {
- ExecutableKind kind = ExecutableKind.NOT_EXECUTABLE;
- if (context.isClientLibrary(source)) {
- kind = ExecutableKind.CLIENT;
- if (context.isServerLibrary(source)) {
- kind = ExecutableKind.EITHER;
- }
- } else if (context.isServerLibrary(source)) {
- kind = ExecutableKind.SERVER;
+ ServerPerformanceStatistics.executionNotifications.makeCurrentWhile(() {
+ Source source = notice.source;
+ String filePath = source.fullName;
+ if (!_isInAnalysisRoot(filePath)) {
+ return;
}
- server.sendNotification(
- new ExecutionLaunchDataParams(filePath, kind: kind).toNotification());
- } else if (AnalysisEngine.isHtmlFileName(filePath)) {
- List<Source> libraries = context.getLibrariesReferencedFromHtml(source);
- server.sendNotification(
- new ExecutionLaunchDataParams(
- filePath,
- referencedFiles: _getFullNames(libraries)).toNotification());
- }
+ AnalysisContext context = server.getAnalysisContext(filePath);
+ if (AnalysisEngine.isDartFileName(filePath)) {
+ ExecutableKind kind = ExecutableKind.NOT_EXECUTABLE;
+ if (context.isClientLibrary(source)) {
+ kind = ExecutableKind.CLIENT;
+ if (context.isServerLibrary(source)) {
+ kind = ExecutableKind.EITHER;
+ }
+ } else if (context.isServerLibrary(source)) {
+ kind = ExecutableKind.SERVER;
+ }
+ server.sendNotification(
+ new ExecutionLaunchDataParams(filePath, kind: kind).toNotification());
+ } else if (AnalysisEngine.isHtmlFileName(filePath)) {
+ List<Source> libraries = context.getLibrariesReferencedFromHtml(source);
+ server.sendNotification(
+ new ExecutionLaunchDataParams(
+ filePath,
+ referencedFiles: _getFullNames(libraries)).toNotification());
+ }
+ });
}
/**
diff --git a/pkg/analysis_server/lib/src/edit/edit_domain.dart b/pkg/analysis_server/lib/src/edit/edit_domain.dart
index 3061df4..003525b 100644
--- a/pkg/analysis_server/lib/src/edit/edit_domain.dart
+++ b/pkg/analysis_server/lib/src/edit/edit_domain.dart
@@ -117,8 +117,7 @@
server.getResolvedCompilationUnits(params.file);
if (units.isNotEmpty) {
CompilationUnit unit = units[0];
- List<Assist> assists =
- computeAssists(searchEngine, unit, params.offset, params.length);
+ List<Assist> assists = computeAssists(unit, params.offset, params.length);
assists.forEach((Assist assist) {
changes.add(assist.change);
});
@@ -127,34 +126,6 @@
return new EditGetAssistsResult(changes).toResponse(request.id);
}
- Response getAvailableRefactorings(Request request) {
- var params = new EditGetAvailableRefactoringsParams.fromRequest(request);
- String file = params.file;
- int offset = params.offset;
- int length = params.length;
- // add refactoring kinds
- List<RefactoringKind> kinds = <RefactoringKind>[];
- // try EXTRACT_*
- if (length != 0) {
- kinds.add(RefactoringKind.EXTRACT_LOCAL_VARIABLE);
- kinds.add(RefactoringKind.EXTRACT_METHOD);
- }
- // try RENAME
- {
- List<Element> elements = server.getElementsAtOffset(file, offset);
- if (elements.isNotEmpty) {
- Element element = elements[0];
- RenameRefactoring renameRefactoring =
- new RenameRefactoring(searchEngine, element);
- if (renameRefactoring != null) {
- kinds.add(RefactoringKind.RENAME);
- }
- }
- }
- // respond
- return new EditGetAvailableRefactoringsResult(kinds).toResponse(request.id);
- }
-
Response getFixes(Request request) {
var params = new EditGetFixesParams.fromRequest(request);
String file = params.file;
@@ -170,7 +141,7 @@
for (engine.AnalysisError error in errorInfo.errors) {
int errorLine = lineInfo.getLocation(error.offset).lineNumber;
if (errorLine == requestLine) {
- List<Fix> fixes = computeFixes(searchEngine, unit, error);
+ List<Fix> fixes = computeFixes(unit, error);
if (fixes.isNotEmpty) {
AnalysisError serverError =
newAnalysisError_fromEngine(lineInfo, error);
@@ -198,7 +169,7 @@
} else if (requestName == EDIT_GET_ASSISTS) {
return getAssists(request);
} else if (requestName == EDIT_GET_AVAILABLE_REFACTORINGS) {
- return getAvailableRefactorings(request);
+ return _getAvailableRefactorings(request);
} else if (requestName == EDIT_GET_FIXES) {
return getFixes(request);
} else if (requestName == EDIT_GET_REFACTORING) {
@@ -249,7 +220,60 @@
return new EditSortMembersResult(fileEdit).toResponse(request.id);
}
+ Response _getAvailableRefactorings(Request request) {
+ if (searchEngine == null) {
+ return new Response.noIndexGenerated(request);
+ }
+ _getAvailableRefactoringsImpl(request);
+ return Response.DELAYED_RESPONSE;
+ }
+
+ Future _getAvailableRefactoringsImpl(Request request) async {
+ // prepare parameters
+ var params = new EditGetAvailableRefactoringsParams.fromRequest(request);
+ String file = params.file;
+ int offset = params.offset;
+ int length = params.length;
+ // add refactoring kinds
+ List<RefactoringKind> kinds = <RefactoringKind>[];
+ // try EXTRACT_*
+ if (length != 0) {
+ kinds.add(RefactoringKind.EXTRACT_LOCAL_VARIABLE);
+ kinds.add(RefactoringKind.EXTRACT_METHOD);
+ }
+ // check elements
+ {
+ List<Element> elements = server.getElementsAtOffset(file, offset);
+ if (elements.isNotEmpty) {
+ Element element = elements[0];
+ // try CONVERT_METHOD_TO_GETTER
+ if (element is ExecutableElement) {
+ Refactoring refactoring =
+ new ConvertMethodToGetterRefactoring(searchEngine, element);
+ RefactoringStatus status = await refactoring.checkInitialConditions();
+ if (!status.hasFatalError) {
+ kinds.add(RefactoringKind.CONVERT_METHOD_TO_GETTER);
+ }
+ }
+ // try RENAME
+ {
+ RenameRefactoring renameRefactoring =
+ new RenameRefactoring(searchEngine, element);
+ if (renameRefactoring != null) {
+ kinds.add(RefactoringKind.RENAME);
+ }
+ }
+ }
+ }
+ // respond
+ var result = new EditGetAvailableRefactoringsResult(kinds);
+ server.sendResponse(result.toResponse(request.id));
+ }
+
Response _getRefactoring(Request request) {
+ if (searchEngine == null) {
+ return new Response.noIndexGenerated(request);
+ }
if (refactoringManager.hasPendingRequest) {
refactoringManager.cancel();
_newRefactoringManager();
@@ -400,8 +424,8 @@
* Initializes this context to perform a refactoring with the specified
* parameters. The existing [Refactoring] is reused or created as needed.
*/
- Future _init(RefactoringKind kind, String file,
- int offset, int length) async {
+ Future _init(RefactoringKind kind, String file, int offset,
+ int length) async {
await server.onAnalysisComplete;
// check if we can continue with the existing Refactoring instance
if (this.kind == kind &&
@@ -488,13 +512,11 @@
if (element is FieldFormalParameterElement) {
element = (element as FieldFormalParameterElement).field;
}
- // climb from "Class" in "new Class()" to "new Class()"
- if (node.parent is TypeName &&
- node.parent.parent is ConstructorName &&
- node.parent.parent.parent is InstanceCreationExpression) {
- InstanceCreationExpression creation = node.parent.parent.parent;
- node = creation;
- element = creation.staticElement;
+ // climb from "Class" in "new Class.named()" to "Class.named"
+ if (node.parent is TypeName && node.parent.parent is ConstructorName) {
+ ConstructorName constructor = node.parent.parent;
+ node = constructor;
+ element = constructor.staticElement;
}
// do create the refactoring
refactoring = new RenameRefactoring(searchEngine, element);
diff --git a/pkg/analysis_server/lib/src/generated_protocol.dart b/pkg/analysis_server/lib/src/generated_protocol.dart
index 5674427..62b3ce8 100644
--- a/pkg/analysis_server/lib/src/generated_protocol.dart
+++ b/pkg/analysis_server/lib/src/generated_protocol.dart
@@ -6601,6 +6601,8 @@
* CLASS_TYPE_ALIAS
* COMPILATION_UNIT
* CONSTRUCTOR
+ * ENUM
+ * ENUM_CONSTANT
* FIELD
* FUNCTION
* FUNCTION_TYPE_ALIAS
@@ -6628,6 +6630,10 @@
static const CONSTRUCTOR = const ElementKind._("CONSTRUCTOR");
+ static const ENUM = const ElementKind._("ENUM");
+
+ static const ENUM_CONSTANT = const ElementKind._("ENUM_CONSTANT");
+
static const FIELD = const ElementKind._("FIELD");
static const FUNCTION = const ElementKind._("FUNCTION");
@@ -6663,7 +6669,7 @@
/**
* A list containing all of the enum values that are defined.
*/
- static const List<ElementKind> VALUES = const <ElementKind>[CLASS, CLASS_TYPE_ALIAS, COMPILATION_UNIT, CONSTRUCTOR, FIELD, FUNCTION, FUNCTION_TYPE_ALIAS, GETTER, LABEL, LIBRARY, LOCAL_VARIABLE, METHOD, PARAMETER, PREFIX, SETTER, TOP_LEVEL_VARIABLE, TYPE_PARAMETER, UNIT_TEST_GROUP, UNIT_TEST_TEST, UNKNOWN];
+ static const List<ElementKind> VALUES = const <ElementKind>[CLASS, CLASS_TYPE_ALIAS, COMPILATION_UNIT, CONSTRUCTOR, ENUM, ENUM_CONSTANT, FIELD, FUNCTION, FUNCTION_TYPE_ALIAS, GETTER, LABEL, LIBRARY, LOCAL_VARIABLE, METHOD, PARAMETER, PREFIX, SETTER, TOP_LEVEL_VARIABLE, TYPE_PARAMETER, UNIT_TEST_GROUP, UNIT_TEST_TEST, UNKNOWN];
final String name;
@@ -6679,6 +6685,10 @@
return COMPILATION_UNIT;
case "CONSTRUCTOR":
return CONSTRUCTOR;
+ case "ENUM":
+ return ENUM;
+ case "ENUM_CONSTANT":
+ return ENUM_CONSTANT;
case "FIELD":
return FIELD;
case "FUNCTION":
@@ -9299,6 +9309,7 @@
* INVALID_OVERLAY_CHANGE
* INVALID_PARAMETER
* INVALID_REQUEST
+ * NO_INDEX_GENERATED
* REFACTORING_REQUEST_CANCELLED
* SERVER_ALREADY_STARTED
* SERVER_ERROR
@@ -9335,9 +9346,9 @@
static const INVALID_EXECUTION_CONTEXT = const RequestErrorCode._("INVALID_EXECUTION_CONTEXT");
/**
- * An analysis.updateContent request contained a ChangeContentOverlay object
- * which can't be applied, due to an edit having an offset or length that is
- * out of range.
+ * An "analysis.updateContent" request contained a ChangeContentOverlay
+ * object which can't be applied, due to an edit having an offset or length
+ * that is out of range.
*/
static const INVALID_OVERLAY_CHANGE = const RequestErrorCode._("INVALID_OVERLAY_CHANGE");
@@ -9352,6 +9363,12 @@
static const INVALID_REQUEST = const RequestErrorCode._("INVALID_REQUEST");
/**
+ * The "--no-index" flag was passed when the analysis server created, but
+ * this API call requires an index to have been generated.
+ */
+ static const NO_INDEX_GENERATED = const RequestErrorCode._("NO_INDEX_GENERATED");
+
+ /**
* Another refactoring request was received during processing of this one.
*/
static const REFACTORING_REQUEST_CANCELLED = const RequestErrorCode._("REFACTORING_REQUEST_CANCELLED");
@@ -9411,7 +9428,7 @@
/**
* A list containing all of the enum values that are defined.
*/
- static const List<RequestErrorCode> VALUES = const <RequestErrorCode>[CONTENT_MODIFIED, FORMAT_INVALID_FILE, GET_ERRORS_INVALID_FILE, INVALID_EXECUTION_CONTEXT, INVALID_OVERLAY_CHANGE, INVALID_PARAMETER, INVALID_REQUEST, REFACTORING_REQUEST_CANCELLED, SERVER_ALREADY_STARTED, SERVER_ERROR, SORT_MEMBERS_INVALID_FILE, SORT_MEMBERS_PARSE_ERRORS, UNANALYZED_PRIORITY_FILES, UNKNOWN_REQUEST, UNSUPPORTED_FEATURE];
+ static const List<RequestErrorCode> VALUES = const <RequestErrorCode>[CONTENT_MODIFIED, FORMAT_INVALID_FILE, GET_ERRORS_INVALID_FILE, INVALID_EXECUTION_CONTEXT, INVALID_OVERLAY_CHANGE, INVALID_PARAMETER, INVALID_REQUEST, NO_INDEX_GENERATED, REFACTORING_REQUEST_CANCELLED, SERVER_ALREADY_STARTED, SERVER_ERROR, SORT_MEMBERS_INVALID_FILE, SORT_MEMBERS_PARSE_ERRORS, UNANALYZED_PRIORITY_FILES, UNKNOWN_REQUEST, UNSUPPORTED_FEATURE];
final String name;
@@ -9433,6 +9450,8 @@
return INVALID_PARAMETER;
case "INVALID_REQUEST":
return INVALID_REQUEST;
+ case "NO_INDEX_GENERATED":
+ return NO_INDEX_GENERATED;
case "REFACTORING_REQUEST_CANCELLED":
return REFACTORING_REQUEST_CANCELLED;
case "SERVER_ALREADY_STARTED":
diff --git a/pkg/analysis_server/lib/src/get_handler.dart b/pkg/analysis_server/lib/src/get_handler.dart
index 2dadde0..46272c3 100644
--- a/pkg/analysis_server/lib/src/get_handler.dart
+++ b/pkg/analysis_server/lib/src/get_handler.dart
@@ -119,17 +119,17 @@
static const String DESCRIPTOR_QUERY_PARAM = 'descriptor';
/**
- * Query parameter used to represent the index in the [_overlayContents].
- */
- static const String ID_PARAM = 'id';
-
- /**
* Query parameter used to represent the name of elements to search for, when
* accessing [INDEX_ELEMENT_BY_NAME].
*/
static const String INDEX_ELEMENT_NAME = 'name';
/**
+ * Query parameter used to represent the path of an overlayed file.
+ */
+ static const String PATH_PARAM = 'path';
+
+ /**
* Query parameter used to represent the source to search for, when accessing
* [CACHE_ENTRY_PATH].
*/
@@ -157,7 +157,7 @@
/**
* Contents of overlay files.
*/
- final Map<int, String> _overlayContents = <int, String>{};
+ final Map<String, String> _overlayContents = <String, String>{};
/**
* Initialize a newly created handler for GET requests.
@@ -267,26 +267,43 @@
'Analysis Server - Analysis Performance',
[],
(StringBuffer buffer) {
- void writeRow(TimeCounter counter, String label) {
- _writeRow(buffer, [counter.result, label], classes: ["right", null]);
- }
buffer.write('<h3>Analysis Performance</h3>');
- buffer.write('<p><b>Time spent in each phase of analysis</b></p>');
- buffer.write(
- '<table style="border-collapse: separate; border-spacing: 10px 5px;">');
- _writeRow(buffer, ['Time (in ms)', 'Analysis Phase'], header: true);
- writeRow(PerformanceStatistics.io, 'io');
- writeRow(PerformanceStatistics.scan, 'scan');
- writeRow(PerformanceStatistics.parse, 'parse');
- writeRow(PerformanceStatistics.resolve, 'resolve');
- writeRow(PerformanceStatistics.errors, 'errors');
- writeRow(PerformanceStatistics.hints, 'hints');
- writeRow(PerformanceStatistics.lint, 'lint');
- buffer.write('</table>');
- Map<DataDescriptor, Map<CacheState, int>> transitionMap = SourceEntry.transitionMap;
- buffer.write('<p><b>Number of times a state transitioned to VALID (grouped by descriptor)</b></p>');
+ {
+ buffer.write('<p><b>Time spent in each phase of analysis</b></p>');
+ buffer.write(
+ '<table style="border-collapse: separate; border-spacing: 10px 5px;">');
+ _writeRow(
+ buffer,
+ ['Time (in ms)', 'Percent', 'Analysis Phase'],
+ header: true);
+ // prepare sorted tags
+ List<PerformanceTag> tags = PerformanceTag.all.toList();
+ tags.remove(ServerPerformanceStatistics.idle);
+ tags.sort((a, b) => b.elapsedMs - a.elapsedMs);
+ // prepare total time
+ int totalTime = 0;
+ tags.forEach((PerformanceTag tag) {
+ totalTime += tag.elapsedMs;
+ });
+ // write rows
+ void writeRow(PerformanceTag tag) {
+ double percent = (tag.elapsedMs * 100) / totalTime;
+ String percentStr = '${percent.toStringAsFixed(2)}%';
+ _writeRow(
+ buffer,
+ [tag.elapsedMs, percentStr, tag.label],
+ classes: ["right", "right", null]);
+ }
+ tags.forEach(writeRow);
+ buffer.write('</table>');
+ }
+
+ Map<DataDescriptor, Map<CacheState, int>> transitionMap =
+ SourceEntry.transitionMap;
+ buffer.write(
+ '<p><b>Number of times a state transitioned to VALID (grouped by descriptor)</b></p>');
if (transitionMap.isEmpty) {
buffer.write('<p>none</p>');
} else {
@@ -698,7 +715,6 @@
List<String> implicitNames = <String>[];
Map<String, String> links = new HashMap<String, String>();
List<CaughtException> exceptions = <CaughtException>[];
- Map<String, int> overlayMap = new HashMap<String, int>();
AnalysisContextImpl context = analysisServer.folderMap[folder];
priorityNames =
context.prioritySources.map((Source source) => source.fullName).toList();
@@ -723,16 +739,14 @@
links[sourceName] = link;
}
});
- _overlayContents.clear();
- int count = 0;
- context.visitContentCache((Source source, int stamp, String contents) {
- count++;
- overlayMap[source.fullName] = count;
- _overlayContents[count] = contents;
- });
explicitNames.sort();
implicitNames.sort();
+ _overlayContents.clear();
+ context.visitContentCache((Source source, int stamp, String contents) {
+ _overlayContents[source.fullName] = contents;
+ });
+
void _writeFiles(StringBuffer buffer, String title, List<String> fileNames)
{
buffer.write('<h3>$title</h3>');
@@ -744,9 +758,9 @@
buffer.write('<tr><td>');
buffer.write(links[fileName]);
buffer.write('</td><td>');
- if (overlayMap.containsKey(fileName)) {
+ if (_overlayContents.containsKey(fileName)) {
buffer.write(makeLink(OVERLAY_PATH, {
- ID_PARAM: overlayMap[fileName].toString()
+ PATH_PARAM: fileName
}, 'overlay'));
}
buffer.write('</td></tr>');
@@ -873,6 +887,9 @@
return _returnFailure(request, 'Analysis server not running');
}
Index index = analysisServer.index;
+ if (index == null) {
+ return _returnFailure(request, 'Indexing is disabled');
+ }
String name = request.uri.queryParameters[INDEX_ELEMENT_NAME];
if (name == null) {
return _returnFailure(
@@ -913,12 +930,11 @@
}
void _returnOverlayContents(HttpRequest request) {
- String idString = request.requestedUri.queryParameters[ID_PARAM];
- if (idString == null) {
- return _returnFailure(request, 'Query parameter $ID_PARAM required');
+ String path = request.requestedUri.queryParameters[PATH_PARAM];
+ if (path == null) {
+ return _returnFailure(request, 'Query parameter $PATH_PARAM required');
}
- int id = int.parse(idString);
- String contents = _overlayContents[id];
+ String contents = _overlayContents[path];
_writeResponse(request, (StringBuffer buffer) {
_writePage(
@@ -947,22 +963,19 @@
[],
(StringBuffer buffer) {
buffer.write('<table border="1">');
- int count = 0;
_overlayContents.clear();
- analysisServer.folderMap.forEach((_, AnalysisContextImpl context) {
- context.visitContentCache(
- (Source source, int stamp, String contents) {
- count++;
- buffer.write('<tr>');
- String linkRef = '$OVERLAY_PATH?id=$count';
- String linkText = HTML_ESCAPE.convert(source.toString());
- buffer.write('<td><a href="$linkRef">$linkText</a></td>');
- buffer.write(
- '<td>${new DateTime.fromMillisecondsSinceEpoch(stamp)}</td>');
- buffer.write('</tr>');
- _overlayContents[count] = contents;
- });
+ ContentCache overlayState = analysisServer.overlayState;
+ overlayState.accept((Source source, int stamp, String contents) {
+ String fileName = source.fullName;
+ buffer.write('<tr>');
+ String link = makeLink(OVERLAY_PATH, {
+ PATH_PARAM: fileName
+ }, fileName);
+ DateTime time = new DateTime.fromMillisecondsSinceEpoch(stamp);
+ _writeRow(buffer, [link, time]);
+ _overlayContents[fileName] = contents;
});
+ int count = _overlayContents.length;
buffer.write('<tr><td colspan="2">Total: $count entries.</td></tr>');
buffer.write('</table>');
});
@@ -1003,6 +1016,9 @@
buffer.write('<p>');
buffer.write(makeLink(STATUS_PATH, {}, 'Server status'));
buffer.write('</p>');
+ buffer.write('<p>');
+ buffer.write(makeLink(OVERLAYS_PATH, {}, 'File overlays'));
+ buffer.write('</p>');
});
});
}
diff --git a/pkg/analysis_server/lib/src/operation/operation_analysis.dart b/pkg/analysis_server/lib/src/operation/operation_analysis.dart
index 7d77d4a..4ed7609 100644
--- a/pkg/analysis_server/lib/src/operation/operation_analysis.dart
+++ b/pkg/analysis_server/lib/src/operation/operation_analysis.dart
@@ -84,7 +84,7 @@
void sendAnalysisNotificationErrors(AnalysisServer server, String file,
LineInfo lineInfo, List<AnalysisError> errors) {
- try {
+ _sendNotification(server, () {
if (errors == null) {
errors = <AnalysisError>[];
}
@@ -92,27 +92,22 @@
protocol.doAnalysisError_listFromEngine(lineInfo, errors);
var params = new protocol.AnalysisErrorsParams(file, serverErrors);
server.sendNotification(params.toNotification());
- } catch (exception, stackTrace) {
- server.sendServerErrorNotification(exception, stackTrace);
- }
+ });
}
-
void sendAnalysisNotificationHighlights(AnalysisServer server, String file,
CompilationUnit dartUnit) {
- try {
+ _sendNotification(server, () {
var regions = new DartUnitHighlightsComputer(dartUnit).compute();
var params = new protocol.AnalysisHighlightsParams(file, regions);
server.sendNotification(params.toNotification());
- } catch (exception, stackTrace) {
- server.sendServerErrorNotification(exception, stackTrace);
- }
+ });
}
void sendAnalysisNotificationNavigation(AnalysisServer server, String file,
CompilationUnit dartUnit) {
- try {
+ _sendNotification(server, () {
var computer = new DartUnitNavigationComputer(dartUnit);
computer.compute();
var params = new protocol.AnalysisNavigationParams(
@@ -121,46 +116,52 @@
computer.targets,
computer.files);
server.sendNotification(params.toNotification());
- } catch (exception, stackTrace) {
- server.sendServerErrorNotification(exception, stackTrace);
- }
+ });
}
void sendAnalysisNotificationOccurrences(AnalysisServer server, String file,
CompilationUnit dartUnit) {
- try {
+ _sendNotification(server, () {
var occurrences = new DartUnitOccurrencesComputer(dartUnit).compute();
var params = new protocol.AnalysisOccurrencesParams(file, occurrences);
server.sendNotification(params.toNotification());
- } catch (exception, stackTrace) {
- server.sendServerErrorNotification(exception, stackTrace);
- }
+ });
}
void sendAnalysisNotificationOutline(AnalysisServer server, String file,
LineInfo lineInfo, CompilationUnit dartUnit) {
- try {
+ _sendNotification(server, () {
var computer = new DartUnitOutlineComputer(file, lineInfo, dartUnit);
var outline = computer.compute();
var params = new protocol.AnalysisOutlineParams(file, outline);
server.sendNotification(params.toNotification());
- } catch (exception, stackTrace) {
- server.sendServerErrorNotification(exception, stackTrace);
- }
+ });
}
void sendAnalysisNotificationOverrides(AnalysisServer server, String file,
CompilationUnit dartUnit) {
- try {
+ _sendNotification(server, () {
var overrides = new DartUnitOverridesComputer(dartUnit).compute();
var params = new protocol.AnalysisOverridesParams(file, overrides);
server.sendNotification(params.toNotification());
- } catch (exception, stackTrace) {
- server.sendServerErrorNotification(exception, stackTrace);
- }
+ });
+}
+
+
+/**
+ * Runs the given notification producing function [f], catching exceptions.
+ */
+void _sendNotification(AnalysisServer server, f()) {
+ ServerPerformanceStatistics.notices.makeCurrentWhile(() {
+ try {
+ f();
+ } catch (exception, stackTrace) {
+ server.sendServerErrorNotification(exception, stackTrace);
+ }
+ });
}
@@ -221,8 +222,10 @@
return;
}
// process results
- _sendNotices(server, notices);
- _updateIndex(server, notices);
+ ServerPerformanceStatistics.notices.makeCurrentWhile(() {
+ _sendNotices(server, notices);
+ _updateIndex(server, notices);
+ });
// continue analysis
server.addOperation(new PerformAnalysisOperation(context, true));
}
@@ -312,8 +315,10 @@
@override
void perform(AnalysisServer server) {
- Index index = server.index;
- index.indexUnit(context, unit);
+ ServerPerformanceStatistics.indexOperation.makeCurrentWhile(() {
+ Index index = server.index;
+ index.indexUnit(context, unit);
+ });
}
}
diff --git a/pkg/analysis_server/lib/src/protocol.dart b/pkg/analysis_server/lib/src/protocol.dart
index 10aea74..e534943 100644
--- a/pkg/analysis_server/lib/src/protocol.dart
+++ b/pkg/analysis_server/lib/src/protocol.dart
@@ -797,6 +797,17 @@
error: new RequestError(RequestErrorCode.INVALID_REQUEST, 'Invalid request'));
/**
+ * Initialize a newly created instance to represent an error condition caused
+ * by a request that requires an index, but indexing is disabled.
+ */
+ Response.noIndexGenerated(Request request)
+ : this(
+ request.id,
+ error: new RequestError(
+ RequestErrorCode.NO_INDEX_GENERATED,
+ 'Indexing is disabled'));
+
+ /**
* Initialize a newly created instance to represent the
* REFACTORING_REQUEST_CANCELLED error condition.
*/
diff --git a/pkg/analysis_server/lib/src/search/search_domain.dart b/pkg/analysis_server/lib/src/search/search_domain.dart
index 01fd53e..c663d18 100644
--- a/pkg/analysis_server/lib/src/search/search_domain.dart
+++ b/pkg/analysis_server/lib/src/search/search_domain.dart
@@ -14,6 +14,7 @@
import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/src/generated/element.dart';
+
/**
* Instances of the class [SearchDomainHandler] implement a [RequestHandler]
* that handles requests in the search domain.
@@ -151,6 +152,9 @@
@override
protocol.Response handleRequest(protocol.Request request) {
+ if (searchEngine == null) {
+ return new protocol.Response.noIndexGenerated(request);
+ }
try {
String requestName = request.method;
if (requestName == SEARCH_FIND_ELEMENT_REFERENCES) {
diff --git a/pkg/analysis_server/lib/src/server/driver.dart b/pkg/analysis_server/lib/src/server/driver.dart
index f161c54..6811300 100644
--- a/pkg/analysis_server/lib/src/server/driver.dart
+++ b/pkg/analysis_server/lib/src/server/driver.dart
@@ -17,12 +17,14 @@
import 'package:analysis_server/src/socket_server.dart';
import 'package:analysis_server/starter.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
+import 'package:analyzer/instrumentation/file_instrumentation.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/incremental_logger.dart';
import 'package:analyzer/src/generated/java_io.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/sdk_io.dart';
+import 'package:analyzer/options.dart';
import 'package:args/args.dart';
/**
@@ -92,6 +94,12 @@
"incremental-resolution-validation";
/**
+ * The name of the option used to cause instrumentation to also be written to
+ * a local file.
+ */
+ static const String INSTRUMENTATION_LOG_FILE = "instrumentation-log-file";
+
+ /**
* The name of the option used to enable instrumentation.
*/
static const String ENABLE_INSTRUMENTATION_OPTION = "enable-instrumentation";
@@ -132,6 +140,11 @@
static const String NO_ERROR_NOTIFICATION = "no-error-notification";
/**
+ * The name of the flag used to disable the index.
+ */
+ static const String NO_INDEX = "no-index";
+
+ /**
* The name of the option used to set the file read mode.
*/
static const String FILE_READ_MODE = "file-read-mode";
@@ -165,10 +178,10 @@
* Use the given command-line [arguments] to start this server.
*/
void start(List<String> arguments) {
- ArgParser parser = _createArgParser();
- ArgResults results = parser.parse(arguments);
+ CommandLineParser parser = _createArgParser();
+ ArgResults results = parser.parse(arguments, <String, String>{});
if (results[HELP_OPTION]) {
- _printUsage(parser);
+ _printUsage(parser.parser);
return;
}
@@ -206,7 +219,7 @@
} on FormatException {
print('Invalid port number: ${results[PORT_OPTION]}');
print('');
- _printUsage(parser);
+ _printUsage(parser.parser);
exitCode = 1;
return;
}
@@ -218,6 +231,7 @@
analysisServerOptions.enableIncrementalResolutionValidation =
results[INCREMENTAL_RESOLUTION_VALIDATION];
analysisServerOptions.noErrorNotification = results[NO_ERROR_NOTIFICATION];
+ analysisServerOptions.noIndex = results[NO_INDEX];
analysisServerOptions.fileReadMode = results[FILE_READ_MODE];
_initIncrementalLogger(results[INCREMENTAL_RESOLUTION_LOG]);
@@ -231,6 +245,13 @@
defaultSdk = DirectoryBasedDartSdk.defaultSdk;
}
+ if (instrumentationServer != null) {
+ String filePath = results[INSTRUMENTATION_LOG_FILE];
+ if (filePath != null) {
+ instrumentationServer = new MulticastInstrumentationServer(
+ [instrumentationServer, new FileInstrumentationServer(filePath)]);
+ }
+ }
InstrumentationService service =
new InstrumentationService(instrumentationServer);
service.logVersion(
@@ -303,8 +324,9 @@
/**
* Create and return the parser used to parse the command-line arguments.
*/
- ArgParser _createArgParser() {
- ArgParser parser = new ArgParser();
+ CommandLineParser _createArgParser() {
+ CommandLineParser parser =
+ new CommandLineParser(alwaysIgnoreUnrecognized: true);
parser.addOption(
CLIENT_ID,
help: "an identifier used to identify the client");
@@ -332,6 +354,9 @@
help: "enable validation of incremental resolution results (slow)",
defaultsTo: false,
negatable: false);
+ parser.addOption(
+ INSTRUMENTATION_LOG_FILE,
+ help: "the path of the file to which instrumentation data will be written");
parser.addFlag(
INTERNAL_PRINT_TO_CONSOLE,
help: "enable sending `print` output to the console",
@@ -347,6 +372,11 @@
help: "disable sending all analysis error notifications to the server",
defaultsTo: false,
negatable: false);
+ parser.addFlag(
+ NO_INDEX,
+ help: "disable indexing sources",
+ defaultsTo: false,
+ negatable: false);
parser.addOption(
FILE_READ_MODE,
help: "an option of the ways files can be read from disk, " +
diff --git a/pkg/analysis_server/lib/src/services/completion/invocation_computer.dart b/pkg/analysis_server/lib/src/services/completion/invocation_computer.dart
index 0dc7319..f6e68d5 100644
--- a/pkg/analysis_server/lib/src/services/completion/invocation_computer.dart
+++ b/pkg/analysis_server/lib/src/services/completion/invocation_computer.dart
@@ -149,15 +149,15 @@
if (node is PrefixedIdentifier) {
SimpleIdentifier prefix = node.prefix;
if (prefix != null) {
- if (prefix.propagatedType != null) {
+ Element element = prefix.bestElement;
+ DartType type = prefix.bestType;
+ if (element is! ClassElement && type != null && !type.isDynamic) {
InterfaceTypeSuggestionBuilder.suggestionsFor(
request,
- prefix.propagatedType);
- } else {
- Element element = prefix.bestElement;
- if (element != null) {
- return element.accept(this);
- }
+ type);
+ return new Future.value(true);
+ } else if (element != null) {
+ return element.accept(this);
}
}
}
diff --git a/pkg/analysis_server/lib/src/services/completion/keyword_computer.dart b/pkg/analysis_server/lib/src/services/completion/keyword_computer.dart
index b9588be..baaef7b 100644
--- a/pkg/analysis_server/lib/src/services/completion/keyword_computer.dart
+++ b/pkg/analysis_server/lib/src/services/completion/keyword_computer.dart
@@ -44,27 +44,47 @@
@override
visitBlock(Block node) {
- _addSuggestions(
- [
- Keyword.ASSERT,
- Keyword.CASE,
- Keyword.CONTINUE,
- Keyword.DO,
- Keyword.FACTORY,
- Keyword.FINAL,
- Keyword.FOR,
- Keyword.IF,
- Keyword.NEW,
- Keyword.RETHROW,
- Keyword.RETURN,
- Keyword.SUPER,
- Keyword.SWITCH,
- Keyword.THIS,
- Keyword.THROW,
- Keyword.TRY,
- Keyword.VAR,
- Keyword.VOID,
- Keyword.WHILE]);
+ if (_isInClassMemberBody(node)) {
+ _addSuggestions(
+ [
+ Keyword.ASSERT,
+ Keyword.CASE,
+ Keyword.CONTINUE,
+ Keyword.DO,
+ Keyword.FINAL,
+ Keyword.FOR,
+ Keyword.IF,
+ Keyword.NEW,
+ Keyword.RETHROW,
+ Keyword.RETURN,
+ Keyword.SUPER,
+ Keyword.SWITCH,
+ Keyword.THIS,
+ Keyword.THROW,
+ Keyword.TRY,
+ Keyword.VAR,
+ Keyword.VOID,
+ Keyword.WHILE]);
+ } else {
+ _addSuggestions(
+ [
+ Keyword.ASSERT,
+ Keyword.CASE,
+ Keyword.CONTINUE,
+ Keyword.DO,
+ Keyword.FINAL,
+ Keyword.FOR,
+ Keyword.IF,
+ Keyword.NEW,
+ Keyword.RETHROW,
+ Keyword.RETURN,
+ Keyword.SWITCH,
+ Keyword.THROW,
+ Keyword.TRY,
+ Keyword.VAR,
+ Keyword.VOID,
+ Keyword.WHILE]);
+ }
}
@override
@@ -231,4 +251,18 @@
}
return false;
}
+
+ static bool _isInClassMemberBody(AstNode node) {
+ while (true) {
+ AstNode body = node.getAncestor((n) => n is FunctionBody);
+ if (body == null) {
+ return false;
+ }
+ AstNode parent = body.parent;
+ if (parent is ConstructorDeclaration || parent is MethodDeclaration) {
+ return true;
+ }
+ node = parent;
+ }
+ }
}
diff --git a/pkg/analysis_server/lib/src/services/correction/assist.dart b/pkg/analysis_server/lib/src/services/correction/assist.dart
index a63a472..e9a688e 100644
--- a/pkg/analysis_server/lib/src/services/correction/assist.dart
+++ b/pkg/analysis_server/lib/src/services/correction/assist.dart
@@ -6,7 +6,6 @@
import 'package:analysis_server/src/protocol.dart';
import 'package:analysis_server/src/services/correction/assist_internal.dart';
-import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/source.dart';
@@ -16,12 +15,11 @@
*
* Returns the computed [Assist]s, not `null`.
*/
-List<Assist> computeAssists(SearchEngine searchEngine, CompilationUnit unit,
- int offset, int length) {
+List<Assist> computeAssists(CompilationUnit unit, int offset, int length) {
Source source = unit.element.source;
String file = source.fullName;
AssistProcessor processor =
- new AssistProcessor(searchEngine, source, file, unit, offset, length);
+ new AssistProcessor(source, file, unit, offset, length);
return processor.compute();
}
diff --git a/pkg/analysis_server/lib/src/services/correction/assist_internal.dart b/pkg/analysis_server/lib/src/services/correction/assist_internal.dart
index 31b0587..bb6726d 100644
--- a/pkg/analysis_server/lib/src/services/correction/assist_internal.dart
+++ b/pkg/analysis_server/lib/src/services/correction/assist_internal.dart
@@ -14,7 +14,6 @@
import 'package:analysis_server/src/services/correction/statement_analyzer.dart';
import 'package:analysis_server/src/services/correction/util.dart';
import 'package:analysis_server/src/services/search/hierarchy.dart';
-import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/element.dart';
import 'package:analyzer/src/generated/engine.dart';
@@ -32,7 +31,6 @@
* The computer for Dart assists.
*/
class AssistProcessor {
- final SearchEngine searchEngine;
final Source source;
final String file;
int fileStamp;
@@ -56,7 +54,7 @@
SourceChange change = new SourceChange('<message>');
- AssistProcessor(this.searchEngine, this.source, this.file, this.unit,
+ AssistProcessor(this.source, this.file, this.unit,
this.selectionOffset, this.selectionLength) {
unitElement = unit.element;
context = unitElement.context;
diff --git a/pkg/analysis_server/lib/src/services/correction/fix.dart b/pkg/analysis_server/lib/src/services/correction/fix.dart
index 18094cf..329e9cf 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix.dart
@@ -6,7 +6,6 @@
import 'package:analysis_server/src/protocol.dart' show SourceChange;
import 'package:analysis_server/src/services/correction/fix_internal.dart';
-import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/error.dart';
@@ -16,9 +15,8 @@
*
* Returns the computed [Fix]s, not `null`.
*/
-List<Fix> computeFixes(SearchEngine searchEngine, CompilationUnit unit,
- AnalysisError error) {
- var processor = new FixProcessor(searchEngine, unit, error);
+List<Fix> computeFixes(CompilationUnit unit, AnalysisError error) {
+ var processor = new FixProcessor(unit, error);
List<Fix> fixes = processor.compute();
fixes.sort((Fix a, Fix b) {
return a.kind.relevance - b.kind.relevance;
diff --git a/pkg/analysis_server/lib/src/services/correction/fix_internal.dart b/pkg/analysis_server/lib/src/services/correction/fix_internal.dart
index 05e1e61..5858ae0 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix_internal.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix_internal.dart
@@ -18,7 +18,6 @@
import 'package:analysis_server/src/services/correction/strings.dart';
import 'package:analysis_server/src/services/correction/util.dart';
import 'package:analysis_server/src/services/search/hierarchy.dart';
-import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/element.dart';
import 'package:analyzer/src/generated/engine.dart';
@@ -44,7 +43,6 @@
class FixProcessor {
static const int MAX_LEVENSHTEIN_DISTANCE = 3;
- final SearchEngine searchEngine;
final CompilationUnit unit;
final AnalysisError error;
AnalysisContext context;
@@ -69,7 +67,7 @@
AstNode node;
AstNode coveredNode;
- FixProcessor(this.searchEngine, this.unit, this.error) {
+ FixProcessor(this.unit, this.error) {
unitElement = unit.element;
context = unitElement.context;
unitSource = unitElement.source;
@@ -1520,13 +1518,13 @@
Set<LibraryElement> librariesToImport = new Set<LibraryElement>();
// TODO(scheglov) use librariesToImport
String typeSource = utils.getTypeSource(type, librariesToImport);
- {
+ if (typeSource != 'dynamic') {
sb.startPosition('TYPE$i');
sb.append(typeSource);
_addSuperTypeProposals(sb, new Set(), type);
sb.endPosition();
+ sb.append(' ');
}
- sb.append(' ');
// append parameter name
{
List<String> suggestions =
diff --git a/pkg/analysis_server/lib/src/services/correction/util.dart b/pkg/analysis_server/lib/src/services/correction/util.dart
index 837afd8..c89a42d 100644
--- a/pkg/analysis_server/lib/src/services/correction/util.dart
+++ b/pkg/analysis_server/lib/src/services/correction/util.dart
@@ -944,6 +944,10 @@
if (type is FunctionType && type.element is! FunctionTypeAliasElement) {
return "Function";
}
+ // BottomType
+ if (type.isBottom) {
+ return 'dynamic';
+ }
// prepare element
Element element = type.element;
if (element == null) {
diff --git a/pkg/analysis_server/lib/src/services/index/index.dart b/pkg/analysis_server/lib/src/services/index/index.dart
index e80a190..cea7395 100644
--- a/pkg/analysis_server/lib/src/services/index/index.dart
+++ b/pkg/analysis_server/lib/src/services/index/index.dart
@@ -320,6 +320,16 @@
static Map<String, Relationship> _RELATIONSHIP_MAP = {};
/**
+ * The next artificial hash code.
+ */
+ static int _NEXT_HASH_CODE = 0;
+
+ /**
+ * The artifitial hash code for this object.
+ */
+ final int _hashCode = _NEXT_HASH_CODE++;
+
+ /**
* The unique identifier for this relationship.
*/
final String identifier;
@@ -330,6 +340,9 @@
Relationship(this.identifier);
@override
+ int get hashCode => _hashCode;
+
+ @override
String toString() => identifier;
/**
diff --git a/pkg/analysis_server/lib/src/services/index/index_contributor.dart b/pkg/analysis_server/lib/src/services/index/index_contributor.dart
index 3159baf..09f87de 100644
--- a/pkg/analysis_server/lib/src/services/index/index_contributor.dart
+++ b/pkg/analysis_server/lib/src/services/index/index_contributor.dart
@@ -70,7 +70,7 @@
/**
* Visits a resolved AST and adds relationships into [IndexStore].
*/
-class _IndexContributor extends GeneralizingAstVisitor<Object> {
+class _IndexContributor extends GeneralizingAstVisitor {
final IndexStore _store;
LibraryElement _libraryElement;
@@ -78,8 +78,8 @@
Map<ImportElement, Set<Element>> _importElementsMap = {};
/**
- * A stack whose top element (the element with the largest index) is an element representing the
- * inner-most enclosing scope.
+ * A stack whose top element (the element with the largest index) is an
+ * element representing the inner-most enclosing scope.
*/
Queue<Element> _elementStack = new Queue();
@@ -115,19 +115,19 @@
}
@override
- Object visitAssignmentExpression(AssignmentExpression node) {
+ visitAssignmentExpression(AssignmentExpression node) {
_recordOperatorReference(node.operator, node.bestElement);
- return super.visitAssignmentExpression(node);
+ super.visitAssignmentExpression(node);
}
@override
- Object visitBinaryExpression(BinaryExpression node) {
+ visitBinaryExpression(BinaryExpression node) {
_recordOperatorReference(node.operator, node.bestElement);
- return super.visitBinaryExpression(node);
+ super.visitBinaryExpression(node);
}
@override
- Object visitClassDeclaration(ClassDeclaration node) {
+ visitClassDeclaration(ClassDeclaration node) {
ClassElement element = node.element;
enterScope(element);
try {
@@ -164,14 +164,14 @@
}
}
}
- return super.visitClassDeclaration(node);
+ super.visitClassDeclaration(node);
} finally {
_exitScope();
}
}
@override
- Object visitClassTypeAlias(ClassTypeAlias node) {
+ visitClassTypeAlias(ClassTypeAlias node) {
ClassElement element = node.element;
enterScope(element);
try {
@@ -198,52 +198,56 @@
}
}
}
- return super.visitClassTypeAlias(node);
+ super.visitClassTypeAlias(node);
} finally {
_exitScope();
}
}
@override
- Object visitCompilationUnit(CompilationUnit node) {
+ visitCompilationUnit(CompilationUnit node) {
CompilationUnitElement unitElement = node.element;
if (unitElement != null) {
_elementStack.add(unitElement);
_libraryElement = unitElement.enclosingElement;
if (_libraryElement != null) {
- return super.visitCompilationUnit(node);
+ super.visitCompilationUnit(node);
}
}
- return null;
}
@override
- Object visitConstructorDeclaration(ConstructorDeclaration node) {
+ visitConstructorDeclaration(ConstructorDeclaration node) {
ConstructorElement element = node.element;
- // define
- {
- Location location;
- if (node.name != null) {
- int start = node.period.offset;
- int end = node.name.end;
- location = _createLocationForOffset(start, end - start);
- } else {
- int start = node.returnType.end;
- location = _createLocationForOffset(start, 0);
- }
- recordRelationship(element, IndexConstants.NAME_IS_DEFINED_BY, location);
- }
- // visit children
enterScope(element);
try {
- return super.visitConstructorDeclaration(node);
+ super.visitConstructorDeclaration(node);
} finally {
_exitScope();
}
}
@override
- Object visitConstructorName(ConstructorName node) {
+ visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
+ SimpleIdentifier fieldName = node.fieldName;
+ Expression expression = node.expression;
+ // field reference is write here
+ if (fieldName != null) {
+ Element element = fieldName.staticElement;
+ Location location = _createLocationForNode(fieldName);
+ _store.recordRelationship(
+ element,
+ IndexConstants.IS_WRITTEN_BY,
+ location);
+ }
+ // index expression
+ if (expression != null) {
+ expression.accept(this);
+ }
+ }
+
+ @override
+ visitConstructorName(ConstructorName node) {
ConstructorElement element = node.staticElement;
// in 'class B = A;' actually A constructors are invoked
if (element != null &&
@@ -263,106 +267,106 @@
}
// record relationship
recordRelationship(element, IndexConstants.IS_REFERENCED_BY, location);
- return super.visitConstructorName(node);
+ super.visitConstructorName(node);
}
@override
- Object visitDeclaredIdentifier(DeclaredIdentifier node) {
+ visitDeclaredIdentifier(DeclaredIdentifier node) {
LocalVariableElement element = node.element;
enterScope(element);
try {
- return super.visitDeclaredIdentifier(node);
+ super.visitDeclaredIdentifier(node);
} finally {
_exitScope();
}
}
@override
- Object visitEnumDeclaration(EnumDeclaration node) {
+ visitEnumDeclaration(EnumDeclaration node) {
ClassElement element = node.element;
enterScope(element);
try {
_recordElementDefinition(element);
- return super.visitEnumDeclaration(node);
+ super.visitEnumDeclaration(node);
} finally {
_exitScope();
}
}
@override
- Object visitExportDirective(ExportDirective node) {
+ visitExportDirective(ExportDirective node) {
ExportElement element = node.element;
if (element != null) {
LibraryElement expLibrary = element.exportedLibrary;
_recordLibraryReference(node, expLibrary);
}
- return super.visitExportDirective(node);
+ super.visitExportDirective(node);
}
@override
- Object visitFormalParameter(FormalParameter node) {
+ visitFormalParameter(FormalParameter node) {
ParameterElement element = node.element;
enterScope(element);
try {
- return super.visitFormalParameter(node);
+ super.visitFormalParameter(node);
} finally {
_exitScope();
}
}
@override
- Object visitFunctionDeclaration(FunctionDeclaration node) {
+ visitFunctionDeclaration(FunctionDeclaration node) {
Element element = node.element;
_recordElementDefinition(element);
enterScope(element);
try {
- return super.visitFunctionDeclaration(node);
+ super.visitFunctionDeclaration(node);
} finally {
_exitScope();
}
}
@override
- Object visitFunctionTypeAlias(FunctionTypeAlias node) {
+ visitFunctionTypeAlias(FunctionTypeAlias node) {
Element element = node.element;
_recordElementDefinition(element);
- return super.visitFunctionTypeAlias(node);
+ super.visitFunctionTypeAlias(node);
}
@override
- Object visitImportDirective(ImportDirective node) {
+ visitImportDirective(ImportDirective node) {
ImportElement element = node.element;
if (element != null) {
LibraryElement impLibrary = element.importedLibrary;
_recordLibraryReference(node, impLibrary);
}
- return super.visitImportDirective(node);
+ super.visitImportDirective(node);
}
@override
- Object visitIndexExpression(IndexExpression node) {
+ visitIndexExpression(IndexExpression node) {
MethodElement element = node.bestElement;
if (element is MethodElement) {
Token operator = node.leftBracket;
Location location = _createLocationForToken(operator, element != null);
recordRelationship(element, IndexConstants.IS_INVOKED_BY, location);
}
- return super.visitIndexExpression(node);
+ super.visitIndexExpression(node);
}
@override
- Object visitMethodDeclaration(MethodDeclaration node) {
+ visitMethodDeclaration(MethodDeclaration node) {
ExecutableElement element = node.element;
enterScope(element);
try {
- return super.visitMethodDeclaration(node);
+ super.visitMethodDeclaration(node);
} finally {
_exitScope();
}
}
@override
- Object visitMethodInvocation(MethodInvocation node) {
+ visitMethodInvocation(MethodInvocation node) {
SimpleIdentifier name = node.methodName;
Location location = _createLocationForNode(name);
// element invocation
@@ -382,39 +386,37 @@
location);
}
_recordImportElementReferenceWithoutPrefix(name);
- return super.visitMethodInvocation(node);
+ super.visitMethodInvocation(node);
}
@override
- Object visitPartDirective(PartDirective node) {
+ visitPartDirective(PartDirective node) {
Element element = node.element;
Location location = _createLocationForNode(node.uri);
recordRelationship(element, IndexConstants.IS_REFERENCED_BY, location);
- return super.visitPartDirective(node);
+ super.visitPartDirective(node);
}
@override
- Object visitPartOfDirective(PartOfDirective node) {
+ visitPartOfDirective(PartOfDirective node) {
Location location = _createLocationForNode(node.libraryName);
recordRelationship(node.element, IndexConstants.IS_REFERENCED_BY, location);
- return null;
}
@override
- Object visitPostfixExpression(PostfixExpression node) {
+ visitPostfixExpression(PostfixExpression node) {
_recordOperatorReference(node.operator, node.bestElement);
- return super.visitPostfixExpression(node);
+ super.visitPostfixExpression(node);
}
@override
- Object visitPrefixExpression(PrefixExpression node) {
+ visitPrefixExpression(PrefixExpression node) {
_recordOperatorReference(node.operator, node.bestElement);
- return super.visitPrefixExpression(node);
+ super.visitPrefixExpression(node);
}
@override
- Object
- visitRedirectingConstructorInvocation(RedirectingConstructorInvocation node) {
+ visitRedirectingConstructorInvocation(RedirectingConstructorInvocation node) {
ConstructorElement element = node.staticElement;
Location location;
if (node.constructorName != null) {
@@ -426,11 +428,11 @@
location = _createLocationForOffset(start, 0);
}
recordRelationship(element, IndexConstants.IS_REFERENCED_BY, location);
- return super.visitRedirectingConstructorInvocation(node);
+ super.visitRedirectingConstructorInvocation(node);
}
@override
- Object visitSimpleIdentifier(SimpleIdentifier node) {
+ visitSimpleIdentifier(SimpleIdentifier node) {
Element nameElement = new NameElement(node.name);
Location location = _createLocationForNode(node);
// name in declaration
@@ -439,13 +441,13 @@
nameElement,
IndexConstants.NAME_IS_DEFINED_BY,
location);
- return null;
+ return;
}
// prepare information
Element element = node.bestElement;
// stop if already handled
if (_isAlreadyHandledName(node)) {
- return null;
+ return;
}
// record name read/write
if (element != null && element.enclosingElement is ClassElement ||
@@ -471,7 +473,11 @@
}
// this.field parameter
if (element is FieldFormalParameterElement) {
- element = (element as FieldFormalParameterElement).field;
+ Relationship relationship = peekElement() == element ?
+ IndexConstants.IS_WRITTEN_BY :
+ IndexConstants.IS_REFERENCED_BY;
+ _store.recordRelationship(element.field, relationship, location);
+ return;
}
// record specific relations
if (element is ClassElement ||
@@ -503,11 +509,11 @@
}
}
_recordImportElementReferenceWithoutPrefix(node);
- return super.visitSimpleIdentifier(node);
+ super.visitSimpleIdentifier(node);
}
@override
- Object visitSuperConstructorInvocation(SuperConstructorInvocation node) {
+ visitSuperConstructorInvocation(SuperConstructorInvocation node) {
ConstructorElement element = node.staticElement;
Location location;
if (node.constructorName != null) {
@@ -519,32 +525,32 @@
location = _createLocationForOffset(start, 0);
}
recordRelationship(element, IndexConstants.IS_REFERENCED_BY, location);
- return super.visitSuperConstructorInvocation(node);
+ super.visitSuperConstructorInvocation(node);
}
@override
- Object visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
+ visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
VariableDeclarationList variables = node.variables;
for (VariableDeclaration variableDeclaration in variables.variables) {
Element element = variableDeclaration.element;
_recordElementDefinition(element);
}
- return super.visitTopLevelVariableDeclaration(node);
+ super.visitTopLevelVariableDeclaration(node);
}
@override
- Object visitTypeParameter(TypeParameter node) {
+ visitTypeParameter(TypeParameter node) {
TypeParameterElement element = node.element;
enterScope(element);
try {
- return super.visitTypeParameter(node);
+ super.visitTypeParameter(node);
} finally {
_exitScope();
}
}
@override
- Object visitVariableDeclaration(VariableDeclaration node) {
+ visitVariableDeclaration(VariableDeclaration node) {
VariableElement element = node.element;
// record declaration
{
@@ -556,14 +562,14 @@
// visit
enterScope(element);
try {
- return super.visitVariableDeclaration(node);
+ super.visitVariableDeclaration(node);
} finally {
_exitScope();
}
}
@override
- Object visitVariableDeclarationList(VariableDeclarationList node) {
+ visitVariableDeclarationList(VariableDeclarationList node) {
NodeList<VariableDeclaration> variables = node.variables;
if (variables != null) {
// use first VariableDeclaration as Element for Location(s) in type
@@ -585,7 +591,6 @@
// visit variables
variables.accept(this);
}
- return null;
}
/**
diff --git a/pkg/analysis_server/lib/src/services/index/store/codec.dart b/pkg/analysis_server/lib/src/services/index/store/codec.dart
index ef36535b..d340abc 100644
--- a/pkg/analysis_server/lib/src/services/index/store/codec.dart
+++ b/pkg/analysis_server/lib/src/services/index/store/codec.dart
@@ -11,6 +11,7 @@
import 'package:analyzer/src/generated/element.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/source.dart';
+import 'package:analyzer/src/generated/utilities_general.dart';
/**
@@ -136,12 +137,19 @@
}
/**
- * Returns an integer that corresponds to an approximated location of [element].
+ * Returns an integer that corresponds to the name of [element].
*/
int encodeHash(Element element) {
- List<int> path = _getLocationPathLimited(element);
- int index = _encodePath(path);
- return index;
+ String elementName = element.displayName;
+ int elementNameId = _stringCodec.encode(elementName);
+ LibraryElement libraryElement = element.library;
+ if (libraryElement != null) {
+ String libraryPath = libraryElement.source.fullName;
+ int libraryPathId = _stringCodec.encode(libraryPath);
+ return JenkinsSmiHash.combine(libraryPathId, elementNameId);
+ } else {
+ return elementNameId;
+ }
}
/**
@@ -243,25 +251,6 @@
}
}
- /**
- * Returns an approximation of the [element]'s location.
- */
- List<int> _getLocationPathLimited(Element element) {
- String firstComponent;
- {
- LibraryElement libraryElement = element.library;
- if (libraryElement != null) {
- firstComponent = libraryElement.source.fullName;
- } else {
- firstComponent = 'null';
- }
- }
- String lastComponent = element.displayName;
- int firstId = _stringCodec.encode(firstComponent);
- int lastId = _stringCodec.encode(lastComponent);
- return <int>[firstId, lastId];
- }
-
static bool _hasLocalOffset(List<String> components) {
for (String component in components) {
if (component.indexOf('@') != -1) {
diff --git a/pkg/analysis_server/lib/src/services/index/store/collection.dart b/pkg/analysis_server/lib/src/services/index/store/collection.dart
index c2ad953..808c55d 100644
--- a/pkg/analysis_server/lib/src/services/index/store/collection.dart
+++ b/pkg/analysis_server/lib/src/services/index/store/collection.dart
@@ -5,14 +5,16 @@
library services.src.index.store.collection;
import 'dart:collection';
-import 'dart:typed_data';
+import 'dart:typed_data' show Uint32List;
+
+import 'package:analyzer/src/generated/utilities_general.dart';
/**
* A hash map with `List<int>` keys and [int] values.
*/
class IntArrayToIntMap {
- final Map<Int32List, int> map = new HashMap<Int32List, int>(
+ final Map<Uint32List, int> map = new HashMap<Uint32List, int>(
equals: _intArrayEquals,
hashCode: _intArrayHashCode);
@@ -20,7 +22,7 @@
* Returns the value for the given [key] or null if [key] is not in the map.
*/
int operator [](List<int> key) {
- Int32List typedKey = _getTypedKey(key);
+ Uint32List typedKey = _getTypedKey(key);
return map[typedKey];
}
@@ -31,18 +33,18 @@
* Otherwise the key-value pair is added to the map.
*/
void operator []=(List<int> key, int value) {
- Int32List typedKey = _getTypedKey(key);
+ Uint32List typedKey = _getTypedKey(key);
map[typedKey] = value;
}
/**
- * Returns an [Int32List] version of the given `List<int>` key.
+ * Returns an [Uint32List] version of the given `List<int>` key.
*/
- static Int32List _getTypedKey(List<int> key) {
- if (key is Int32List) {
+ static Uint32List _getTypedKey(List<int> key) {
+ if (key is Uint32List) {
return key;
}
- return new Int32List.fromList(key);
+ return new Uint32List.fromList(key);
}
static bool _intArrayEquals(List<int> a, List<int> b) {
@@ -59,9 +61,7 @@
}
static int _intArrayHashCode(List<int> key) {
- return key.fold(0, (int result, int item) {
- return 31 * result + item;
- });
+ return key.fold(0, JenkinsSmiHash.combine);
}
}
@@ -70,7 +70,7 @@
* A table mapping [int] keys to sets of [int]s.
*/
class IntToIntSetMap {
- final Map<int, Int32List> _map = new HashMap<int, Int32List>();
+ final Map<int, Uint32List> _map = new HashMap<int, Uint32List>();
/**
* The number of key-value pairs in the map.
@@ -81,15 +81,15 @@
* Adds the [value] to the set associated with the given [value].
*/
void add(int key, int value) {
- Int32List values = _map[key];
+ Uint32List values = _map[key];
if (values == null) {
- values = new Int32List(1);
+ values = new Uint32List(1);
values[0] = value;
_map[key] = values;
}
if (values.indexOf(value) == -1) {
int length = values.length;
- Int32List newSet = new Int32List(length + 1);
+ Uint32List newSet = new Uint32List(length + 1);
newSet.setRange(0, length, values);
newSet[length] = value;
_map[key] = newSet;
diff --git a/pkg/analysis_server/lib/src/services/index/store/split_store.dart b/pkg/analysis_server/lib/src/services/index/store/split_store.dart
index fc1ca31..bd3bec2 100644
--- a/pkg/analysis_server/lib/src/services/index/store/split_store.dart
+++ b/pkg/analysis_server/lib/src/services/index/store/split_store.dart
@@ -6,7 +6,6 @@
import 'dart:async';
import 'dart:collection';
-import 'dart:io';
import 'dart:typed_data';
import 'package:analysis_server/src/services/index/index.dart';
@@ -17,6 +16,8 @@
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
+import 'package:analysis_server/src/analysis_server.dart';
+import 'package:analyzer/src/generated/utilities_general.dart';
/**
@@ -116,10 +117,12 @@
}
// write the node
return new Future.microtask(() {
- _DataOutputStream stream = new _DataOutputStream();
- _writeNode(node, stream);
- var bytes = stream.getBytes();
- return _fileManager.write(name, bytes);
+ return ServerPerformanceStatistics.splitStore.makeCurrentWhile(() {
+ _DataOutputStream stream = new _DataOutputStream();
+ _writeNode(node, stream);
+ var bytes = stream.getBytes();
+ return _fileManager.write(name, bytes);
+ });
}).catchError((exception, stackTrace) {
_logger.logError(
'Exception during reading index file ${name}',
@@ -988,7 +991,7 @@
}
int readInt() {
- int result = _byteData.getInt32(_byteOffset);
+ int result = _byteData.getInt32(_byteOffset, Endianness.HOST_ENDIAN);
_byteOffset += 4;
return result;
}
@@ -996,16 +999,23 @@
class _DataOutputStream {
- BytesBuilder _buffer = new BytesBuilder();
+ static const LIST_SIZE = 1024;
+ int _size = LIST_SIZE;
+ Uint32List _buf = new Uint32List(LIST_SIZE);
+ int _pos = 0;
Uint8List getBytes() {
- return new Uint8List.fromList(_buffer.takeBytes());
+ return new Uint8List.view(_buf.buffer, 0, _size << 2);
}
void writeInt(int value) {
- _buffer.addByte((value & 0xFF000000) >> 24);
- _buffer.addByte((value & 0x00FF0000) >> 16);
- _buffer.addByte((value & 0x0000FF00) >> 8);
- _buffer.addByte(value & 0xFF);
+ if (_pos == _size) {
+ int newSize = _size << 1;
+ Uint32List newBuf = new Uint32List(newSize);
+ newBuf.setRange(0, _size, _buf);
+ _size = newSize;
+ _buf = newBuf;
+ }
+ _buf[_pos++] = value;
}
}
diff --git a/pkg/analysis_server/lib/src/services/refactoring/convert_method_to_getter.dart b/pkg/analysis_server/lib/src/services/refactoring/convert_method_to_getter.dart
index e0a94cc..b1d0d58 100644
--- a/pkg/analysis_server/lib/src/services/refactoring/convert_method_to_getter.dart
+++ b/pkg/analysis_server/lib/src/services/refactoring/convert_method_to_getter.dart
@@ -40,9 +40,29 @@
}
@override
- Future<RefactoringStatus> checkInitialConditions() {
- RefactoringStatus result = _checkInitialConditions();
- return new Future.value(result);
+ Future<RefactoringStatus> checkInitialConditions() async {
+ // check Element type
+ if (element is FunctionElement) {
+ if (element.enclosingElement is! CompilationUnitElement) {
+ return new RefactoringStatus.fatal(
+ 'Only top-level functions can be converted to getters.');
+ }
+ } else if (element is! MethodElement) {
+ return new RefactoringStatus.fatal(
+ 'Only class methods or top-level functions can be converted to getters.');
+ }
+ // returns a value
+ if (element.returnType != null && element.returnType.isVoid) {
+ return new RefactoringStatus.fatal(
+ 'Cannot convert ${element.kind.displayName} returning void.');
+ }
+ // no parameters
+ if (element.parameters.isNotEmpty) {
+ return new RefactoringStatus.fatal(
+ 'Only methods without parameters can be converted to getters.');
+ }
+ // OK
+ return new RefactoringStatus();
}
@override
@@ -70,26 +90,6 @@
@override
bool requiresPreview() => false;
- RefactoringStatus _checkInitialConditions() {
- // check Element type
- if (element is FunctionElement) {
- if (element.enclosingElement is! CompilationUnitElement) {
- return new RefactoringStatus.fatal(
- 'Only top-level functions can be converted to getters.');
- }
- } else if (element is! MethodElement) {
- return new RefactoringStatus.fatal(
- 'Only class methods or top-level functions can be converted to getters.');
- }
- // no parameters
- if (element.parameters.isNotEmpty) {
- return new RefactoringStatus.fatal(
- 'Only methods without parameters can be converted to getters.');
- }
- // OK
- return new RefactoringStatus();
- }
-
void _updateElementDeclaration(Element element) {
// prepare parameters
FormalParameterList parameters;
diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_constructor.dart b/pkg/analysis_server/lib/src/services/refactoring/rename_constructor.dart
index 544b79a..b43ad0b 100644
--- a/pkg/analysis_server/lib/src/services/refactoring/rename_constructor.dart
+++ b/pkg/analysis_server/lib/src/services/refactoring/rename_constructor.dart
@@ -7,6 +7,7 @@
import 'dart:async';
import 'package:analysis_server/src/protocol_server.dart' hide Element;
+import 'package:analysis_server/src/services/correction/source_range.dart';
import 'package:analysis_server/src/services/correction/status.dart';
import 'package:analysis_server/src/services/correction/util.dart';
import 'package:analysis_server/src/services/refactoring/naming_conventions.dart';
@@ -17,6 +18,7 @@
import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/src/generated/element.dart';
import 'package:analyzer/src/generated/java_core.dart';
+import 'package:analyzer/src/generated/source.dart';
/**
@@ -51,11 +53,14 @@
@override
Future fillChange() async {
- String replacement = newName.isEmpty ? '' : '.${newName}';
- // update references
- List<SearchMatch> matches = await searchEngine.searchReferences(element);
- List<SourceReference> references = getSourceReferences(matches);
if (!element.isSynthetic) {
+ // prepare references
+ List<SearchMatch> matches = await searchEngine.searchReferences(element);
+ List<SourceReference> references = getSourceReferences(matches);
+ // append declaration
+ references.add(_createDeclarationReference());
+ // update references
+ String replacement = newName.isEmpty ? '' : '.${newName}';
for (SourceReference reference in references) {
reference.addEdit(change, replacement);
}
@@ -74,4 +79,15 @@
result.addError(message, newLocation_fromElement(newNameMember));
}
}
+
+ SourceReference _createDeclarationReference() {
+ SourceRange sourceRange;
+ if (element.periodOffset != null) {
+ sourceRange = rangeStartEnd(element.periodOffset, element.nameEnd);
+ } else {
+ sourceRange = rangeStartLength(element.nameEnd, 0);
+ }
+ String file = element.source.fullName;
+ return new SourceReference(file, sourceRange, element, true, true);
+ }
}
diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename_local.dart b/pkg/analysis_server/lib/src/services/refactoring/rename_local.dart
index 7effb9d..9579643 100644
--- a/pkg/analysis_server/lib/src/services/refactoring/rename_local.dart
+++ b/pkg/analysis_server/lib/src/services/refactoring/rename_local.dart
@@ -17,12 +17,14 @@
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/element.dart';
import 'package:analyzer/src/generated/source.dart';
-
+import 'package:analyzer/src/generated/utilities_dart.dart';
/**
* A [Refactoring] for renaming [LocalElement]s.
*/
class RenameLocalRefactoringImpl extends RenameRefactoringImpl {
+ Set<LocalElement> elements = new Set<LocalElement>();
+
RenameLocalRefactoringImpl(SearchEngine searchEngine, LocalElement element)
: super(searchEngine, element);
@@ -41,15 +43,24 @@
}
@override
- Future<RefactoringStatus> checkFinalConditions() {
+ Future<RefactoringStatus> checkFinalConditions() async {
RefactoringStatus result = new RefactoringStatus();
+ // prepare all elements (usually one)
+ await _prepareElements();
// checks the resolved CompilationUnit(s)
- Source unitSource = element.source;
- List<Source> librarySources = context.getLibrariesContaining(unitSource);
- for (Source librarySource in librarySources) {
- _analyzePossibleConflicts_inLibrary(result, unitSource, librarySource);
+ for (LocalElement element in elements) {
+ Source unitSource = element.source;
+ List<Source> librarySources = context.getLibrariesContaining(unitSource);
+ for (Source librarySource in librarySources) {
+ _analyzePossibleConflicts_inLibrary(
+ result,
+ unitSource,
+ librarySource,
+ element);
+ }
}
- return new Future.value(result);
+ // done
+ return result;
}
@override
@@ -66,19 +77,20 @@
}
@override
- Future fillChange() {
- addDeclarationEdit(element);
- return searchEngine.searchReferences(element).then(addReferenceEdits);
+ Future fillChange() async {
+ for (Element element in elements) {
+ addDeclarationEdit(element);
+ await searchEngine.searchReferences(element).then(addReferenceEdits);
+ }
}
void _analyzePossibleConflicts_inLibrary(RefactoringStatus result,
- Source unitSource, Source librarySource) {
+ Source unitSource, Source librarySource, LocalElement element) {
// prepare resolved unit
CompilationUnit unit = null;
try {
unit = context.resolveCompilationUnit2(unitSource, librarySource);
- } catch (e) {
- }
+ } catch (e) {}
if (unit == null) {
return;
}
@@ -86,8 +98,34 @@
SourceRange elementRange = element.visibleRange;
unit.accept(new _ConflictValidatorVisitor(this, result, elementRange));
}
-}
+ /**
+ * Fills [elements] with [Element]s to rename.
+ */
+ Future _prepareElements() async {
+ Element enclosing = element.enclosingElement;
+ if (enclosing is MethodElement &&
+ element is ParameterElement &&
+ (element as ParameterElement).parameterKind == ParameterKind.NAMED) {
+ // prepare hierarchy methods
+ Set<ClassMemberElement> methods =
+ await getHierarchyMembers(searchEngine, enclosing);
+ // add named parameter from each method
+ for (ClassMemberElement method in methods) {
+ if (method is MethodElement) {
+ for (ParameterElement parameter in method.parameters) {
+ if (parameter.parameterKind == ParameterKind.NAMED &&
+ parameter.name == element.name) {
+ elements.add(parameter);
+ }
+ }
+ }
+ }
+ } else {
+ elements = new Set.from([element]);
+ }
+ }
+}
class _ConflictValidatorVisitor extends RecursiveAstVisitor {
final RenameLocalRefactoringImpl refactoring;
diff --git a/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart b/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart
index a94aa70..dec4aa3 100644
--- a/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart
+++ b/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart
@@ -129,10 +129,6 @@
_Requestor requestor = new _Requestor(_index);
requestor.add(
constructor,
- IndexConstants.NAME_IS_DEFINED_BY,
- MatchKind.DECLARATION);
- requestor.add(
- constructor,
IndexConstants.IS_REFERENCED_BY,
MatchKind.REFERENCE);
return requestor.merge();
@@ -145,6 +141,7 @@
_Requestor requestor = new _Requestor(_index);
// field itself
requestor.add(field, IndexConstants.IS_REFERENCED_BY, MatchKind.REFERENCE);
+ requestor.add(field, IndexConstants.IS_WRITTEN_BY, MatchKind.WRITE);
// getter
if (getter != null) {
requestor.add(getter, IndexConstants.IS_REFERENCED_BY, MatchKind.READ);
diff --git a/pkg/analysis_server/lib/src/socket_server.dart b/pkg/analysis_server/lib/src/socket_server.dart
index cdc873a..e665f06 100644
--- a/pkg/analysis_server/lib/src/socket_server.dart
+++ b/pkg/analysis_server/lib/src/socket_server.dart
@@ -17,16 +17,6 @@
/**
- * Creates and runs an [Index].
- */
-Index _createIndex() {
- Index index = createLocalFileIndex();
- index.run();
- return index;
-}
-
-
-/**
* Instances of the class [SocketServer] implement the common parts of
* http-based and stdio-based analysis servers. The primary responsibility of
* the SocketServer is to manage the lifetime of the AnalysisServer and to
@@ -62,6 +52,7 @@
});
return;
}
+
PhysicalResourceProvider resourceProvider;
if (analysisServerOptions.fileReadMode == 'as-is') {
resourceProvider = PhysicalResourceProvider.INSTANCE;
@@ -73,11 +64,17 @@
'File read mode was set to the unknown mode: $analysisServerOptions.fileReadMode');
}
+ Index index = null;
+ if (!analysisServerOptions.noIndex) {
+ index = createLocalFileIndex();
+ index.run();
+ }
+
analysisServer = new AnalysisServer(
serverChannel,
resourceProvider,
new PubPackageMapProvider(resourceProvider, defaultSdk),
- _createIndex(),
+ index,
analysisServerOptions,
defaultSdk,
instrumentationService,
diff --git a/pkg/analysis_server/lib/src/status/ast_writer.dart b/pkg/analysis_server/lib/src/status/ast_writer.dart
index 99229a0..4d410d6 100644
--- a/pkg/analysis_server/lib/src/status/ast_writer.dart
+++ b/pkg/analysis_server/lib/src/status/ast_writer.dart
@@ -4,43 +4,27 @@
library analysis_server.src.status.ast_writer;
-import 'dart:convert';
+import 'dart:collection';
-import 'package:analysis_server/src/get_handler.dart';
+import 'package:analysis_server/src/status/tree_writer.dart';
import 'package:analyzer/src/generated/ast.dart';
-import 'package:analyzer/src/generated/element.dart';
-import 'package:analyzer/src/generated/java_engine.dart';
-import 'package:analyzer/src/generated/source.dart';
/**
* A visitor that will produce an HTML representation of an AST structure.
*/
-class AstWriter extends UnifyingAstVisitor {
- /**
- * The buffer on which the HTML is to be written.
- */
- final StringBuffer buffer;
-
- /**
- * The current level of indentation.
- */
- int indentLevel = 0;
-
- /**
- * A list containing the exceptions that were caught while attempting to write
- * out an AST structure.
- */
- List<CaughtException> exceptions = <CaughtException>[];
-
+class AstWriter extends UnifyingAstVisitor with TreeWriter {
/**
* Initialize a newly created element writer to write the HTML representation
* of visited nodes on the given [buffer].
*/
- AstWriter(this.buffer);
+ AstWriter(StringBuffer buffer) {
+ this.buffer = buffer;
+ }
@override
void visitNode(AstNode node) {
_writeNode(node);
+ writeProperties(_computeProperties(node));
indentLevel++;
try {
node.visitChildren(this);
@@ -50,6 +34,63 @@
}
/**
+ * Write a representation of the properties of the given [node] to the buffer.
+ */
+ Map<String, Object> _computeProperties(AstNode node) {
+ Map<String, Object> properties = new HashMap<String, Object>();
+
+ properties['name'] = _getName(node);
+ if (node is BinaryExpression) {
+ properties['static element'] = node.staticElement;
+ properties['static type'] = node.staticType;
+ properties['propagated element'] = node.propagatedElement;
+ properties['propagated type'] = node.propagatedType;
+ } else if (node is CompilationUnit) {
+ properties['element'] = node.element;
+ } else if (node is ExportDirective) {
+ properties['element'] = node.element;
+ properties['source'] = node.source;
+ } else if (node is FunctionExpressionInvocation) {
+ properties['static element'] = node.staticElement;
+ properties['static type'] = node.staticType;
+ properties['propagated element'] = node.propagatedElement;
+ properties['propagated type'] = node.propagatedType;
+ } else if (node is ImportDirective) {
+ properties['element'] = node.element;
+ properties['source'] = node.source;
+ } else if (node is LibraryDirective) {
+ properties['element'] = node.element;
+ } else if (node is PartDirective) {
+ properties['element'] = node.element;
+ properties['source'] = node.source;
+ } else if (node is PartOfDirective) {
+ properties['element'] = node.element;
+ } else if (node is PostfixExpression) {
+ properties['static element'] = node.staticElement;
+ properties['static type'] = node.staticType;
+ properties['propagated element'] = node.propagatedElement;
+ properties['propagated type'] = node.propagatedType;
+ } else if (node is PrefixExpression) {
+ properties['static element'] = node.staticElement;
+ properties['static type'] = node.staticType;
+ properties['propagated element'] = node.propagatedElement;
+ properties['propagated type'] = node.propagatedType;
+ } else if (node is SimpleIdentifier) {
+ properties['static element'] = node.staticElement;
+ properties['static type'] = node.staticType;
+ properties['propagated element'] = node.propagatedElement;
+ properties['propagated type'] = node.propagatedType;
+ } else if (node is SimpleStringLiteral) {
+ properties['value'] = node.value;
+ } else if (node is Expression) {
+ properties['static type'] = node.staticType;
+ properties['propagated type'] = node.propagatedType;
+ }
+
+ return properties;
+ }
+
+ /**
* Return the name of the given [node], or `null` if the given node is not a
* declaration.
*/
@@ -109,23 +150,11 @@
return buffer.toString();
}
- void _indent([int extra = 0]) {
- for (int i = 0; i < indentLevel; i++) {
- buffer.write('┊ ');
- }
- if (extra > 0) {
- buffer.write('┊ ');
- for (int i = 1; i < extra; i++) {
- buffer.write(' ');
- }
- }
- }
-
/**
* Write a representation of the given [node] to the buffer.
*/
void _writeNode(AstNode node) {
- _indent();
+ indent();
buffer.write(node.runtimeType);
buffer.write(' <span style="color:gray">[');
buffer.write(node.offset);
@@ -133,90 +162,5 @@
buffer.write(node.offset + node.length - 1);
buffer.write(']</span>');
buffer.write('<br>');
- _writeProperty('name', _getName(node));
- if (node is BinaryExpression) {
- _writeProperty('static element', node.staticElement);
- _writeProperty('static type', node.staticType);
- _writeProperty('propagated element', node.propagatedElement);
- _writeProperty('propagated type', node.propagatedType);
- } else if (node is CompilationUnit) {
- _writeProperty("element", node.element);
- } else if (node is ExportDirective) {
- _writeProperty("element", node.element);
- _writeProperty("source", node.source);
- } else if (node is FunctionExpressionInvocation) {
- _writeProperty('static element', node.staticElement);
- _writeProperty('static type', node.staticType);
- _writeProperty('propagated element', node.propagatedElement);
- _writeProperty('propagated type', node.propagatedType);
- } else if (node is ImportDirective) {
- _writeProperty("element", node.element);
- _writeProperty("source", node.source);
- } else if (node is LibraryDirective) {
- _writeProperty("element", node.element);
- } else if (node is PartDirective) {
- _writeProperty("element", node.element);
- _writeProperty("source", node.source);
- } else if (node is PartOfDirective) {
- _writeProperty("element", node.element);
- } else if (node is PostfixExpression) {
- _writeProperty('static element', node.staticElement);
- _writeProperty('static type', node.staticType);
- _writeProperty('propagated element', node.propagatedElement);
- _writeProperty('propagated type', node.propagatedType);
- } else if (node is PrefixExpression) {
- _writeProperty('static element', node.staticElement);
- _writeProperty('static type', node.staticType);
- _writeProperty('propagated element', node.propagatedElement);
- _writeProperty('propagated type', node.propagatedType);
- } else if (node is SimpleIdentifier) {
- _writeProperty('static element', node.staticElement);
- _writeProperty('static type', node.staticType);
- _writeProperty('propagated element', node.propagatedElement);
- _writeProperty('propagated type', node.propagatedType);
- } else if (node is SimpleStringLiteral) {
- _writeProperty("value", node.value);
- } else if (node is Expression) {
- _writeProperty('static type', node.staticType);
- _writeProperty('propagated type', node.propagatedType);
- }
- }
-
- /**
- * Write the [value] of the property with the given [name].
- */
- void _writeProperty(String name, Object value) {
- if (value != null) {
- String valueString = null;
- try {
- if (value is Source) {
- valueString = 'Source (uri="${value.uri}", path="${value.fullName}")';
- } else {
- valueString = value.toString();
- }
- } catch (exception, stackTrace) {
- exceptions.add(new CaughtException(exception, stackTrace));
- }
- _indent(2);
- buffer.write('$name = ');
- if (valueString == null) {
- buffer.write('<span style="color: #FF0000">');
- buffer.write(HTML_ESCAPE.convert(value.runtimeType.toString()));
- buffer.write('</span>');
- } else {
- buffer.write(HTML_ESCAPE.convert(valueString));
- if (value is Element && value is! LibraryElement) {
- String name = value.name;
- if (name != null) {
- buffer.write(' [');
- buffer.write(GetHandler.makeLink(GetHandler.INDEX_ELEMENT_BY_NAME, {
- 'name': name
- }, 'search index'));
- buffer.write(']');
- }
- }
- }
- buffer.write('<br>');
- }
}
}
diff --git a/pkg/analysis_server/lib/src/status/element_writer.dart b/pkg/analysis_server/lib/src/status/element_writer.dart
index 6625a43..b56264b 100644
--- a/pkg/analysis_server/lib/src/status/element_writer.dart
+++ b/pkg/analysis_server/lib/src/status/element_writer.dart
@@ -4,36 +4,155 @@
library analysis_server.src.status.element_writer;
+import 'dart:collection';
import 'dart:convert';
import 'package:analysis_server/src/get_handler.dart';
+import 'package:analysis_server/src/status/tree_writer.dart';
import 'package:analyzer/src/generated/element.dart';
/**
* A visitor that will produce an HTML representation of an element structure.
*/
-class ElementWriter extends GeneralizingElementVisitor {
- /**
- * The buffer on which the HTML is to be written.
- */
- final StringBuffer buffer;
-
- /**
- * The current level of indentation.
- */
- int indentLevel = 0;
-
+class ElementWriter extends GeneralizingElementVisitor with TreeWriter {
/**
* Initialize a newly created element writer to write the HTML representation
* of visited elements on the given [buffer].
*/
- ElementWriter(this.buffer);
+ ElementWriter(StringBuffer buffer) {
+ this.buffer = buffer;
+ }
@override
void visitElement(Element element) {
- for (int i = 0; i < indentLevel; i++) {
- buffer.write('┊ ');
+ _writeElement(element);
+ writeProperties(_computeProperties(element));
+ indentLevel++;
+ try {
+ element.visitChildren(this);
+ } finally {
+ indentLevel--;
}
+ }
+
+ /**
+ * Write a representation of the properties of the given [node] to the buffer.
+ */
+ Map<String, Object> _computeProperties(Element element) {
+ Map<String, Object> properties = new HashMap<String, Object>();
+
+ properties['isDeprecated'] = element.isDeprecated;
+ properties['isOverride'] = element.isOverride;
+ properties['metadata'] = element.metadata;
+ properties['nameOffset'] = element.nameOffset;
+ if (element is ClassElement) {
+ properties['hasNonFinalField'] = element.hasNonFinalField;
+ properties['hasReferenceToSuper'] = element.hasReferenceToSuper;
+ properties['hasStaticMember'] = element.hasStaticMember;
+ properties['interfaces'] = element.interfaces;
+ properties['isAbstract'] = element.isAbstract;
+ properties['isEnum'] = element.isEnum;
+ properties['isOrInheritsProxy'] = element.isOrInheritsProxy;
+ properties['isProxy'] = element.isProxy;
+ properties['isTypedef'] = element.isTypedef;
+ properties['isValidMixin'] = element.isValidMixin;
+ properties['mixins'] = element.mixins;
+ properties['supertype'] = element.supertype;
+ properties['type'] = element.type;
+ }
+ if (element is CompilationUnitElement) {
+ properties['isEnumConstant'] = element.hasLoadLibraryFunction;
+ properties['source'] = element.source;
+ }
+ if (element is ConstFieldElementImpl) {
+ properties['evaluationResult'] = element.evaluationResult;
+ }
+ if (element is ConstLocalVariableElementImpl) {
+ properties['evaluationResult'] = element.evaluationResult;
+ }
+ if (element is ConstTopLevelVariableElementImpl) {
+ properties['evaluationResult'] = element.evaluationResult;
+ }
+ if (element is ConstructorElement) {
+ properties['isConst'] = element.isConst;
+ properties['isDefaultConstructor'] = element.isDefaultConstructor;
+ properties['isFactory'] = element.isFactory;
+ properties['redirectedConstructor'] = element.redirectedConstructor;
+ }
+ if (element is ExecutableElement) {
+ properties['isAsynchronous'] = element.isAsynchronous;
+ properties['isGenerator'] = element.isGenerator;
+ properties['isOperator'] = element.isOperator;
+ properties['isStatic'] = element.isStatic;
+ properties['isSynchronous'] = element.isSynchronous;
+ properties['returnType'] = element.returnType;
+ properties['type'] = element.type;
+ }
+ if (element is ExportElement) {
+ properties['combinators'] = element.combinators;
+ properties['library'] = element.library;
+ }
+ if (element is FieldElement) {
+ properties['isEnumConstant'] = element.isEnumConstant;
+ }
+ if (element is FieldFormalParameterElement) {
+ properties['field'] = element.field;
+ }
+ if (element is FunctionTypeAliasElement) {
+ properties['returnType'] = element.returnType;
+ properties['type'] = element.type;
+ }
+ if (element is ImportElement) {
+ properties['combinators'] = element.combinators;
+ properties['library'] = element.library;
+ }
+ if (element is LibraryElement) {
+ properties['definingCompilationUnit'] = element.definingCompilationUnit;
+ properties['entryPoint'] = element.entryPoint;
+ properties['hasExtUri'] = element.hasExtUri;
+ properties['hasLoadLibraryFunction'] = element.hasLoadLibraryFunction;
+ properties['isBrowserApplication'] = element.isBrowserApplication;
+ }
+ if (element is LocalElement) {
+ properties['visibleRange'] = element.visibleRange;
+ }
+ if (element is MethodElement) {
+ properties['isAbstract'] = element.isAbstract;
+ }
+ if (element is ParameterElement) {
+ properties['defaultValueCode'] = element.defaultValueCode;
+ properties['isInitializingFormal'] = element.isInitializingFormal;
+ properties['parameterKind'] = element.parameterKind;
+ }
+ if (element is PropertyAccessorElement) {
+ properties['isAbstract'] = element.isAbstract;
+ properties['isGetter'] = element.isGetter;
+ properties['isSetter'] = element.isSetter;
+ }
+ if (element is PropertyInducingElement) {
+ properties['isStatic'] = element.isStatic;
+ properties['propagatedType'] = element.propagatedType;
+ }
+ if (element is TypeParameterElement) {
+ properties['bound'] = element.bound;
+ }
+ if (element is UriReferencedElement) {
+ properties['uri'] = element.uri;
+ }
+ if (element is VariableElement) {
+ properties['isConst'] = element.isConst;
+ properties['isFinal'] = element.isFinal;
+ properties['type'] = element.type;
+ }
+
+ return properties;
+ }
+
+ /**
+ * Write a representation of the given [node] to the buffer.
+ */
+ void _writeElement(Element element) {
+ indent();
if (element.isSynthetic) {
buffer.write('<i>');
}
@@ -55,11 +174,5 @@
}
}
buffer.write('<br>');
- indentLevel++;
- try {
- element.visitChildren(this);
- } finally {
- indentLevel--;
- }
}
}
diff --git a/pkg/analysis_server/lib/src/status/tree_writer.dart b/pkg/analysis_server/lib/src/status/tree_writer.dart
new file mode 100644
index 0000000..ec9fb85
--- /dev/null
+++ b/pkg/analysis_server/lib/src/status/tree_writer.dart
@@ -0,0 +1,136 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library analysis_server.src.status.ast_writer;
+
+import 'dart:convert';
+
+import 'package:analysis_server/src/get_handler.dart';
+import 'package:analyzer/src/generated/constant.dart';
+import 'package:analyzer/src/generated/element.dart';
+import 'package:analyzer/src/generated/java_engine.dart';
+import 'package:analyzer/src/generated/source.dart';
+
+/**
+ * Utility methods that can be mixed in to classes that produce an HTML
+ * representation of a tree structure.
+ */
+abstract class TreeWriter {
+ /**
+ * The buffer on which the HTML is to be written.
+ */
+ StringBuffer buffer;
+
+ /**
+ * The current level of indentation.
+ */
+ int indentLevel = 0;
+
+ /**
+ * A list containing the exceptions that were caught while attempting to write
+ * out the tree structure.
+ */
+ List<CaughtException> exceptions = <CaughtException>[];
+
+ void indent([int extra = 0]) {
+ for (int i = 0; i < indentLevel; i++) {
+ buffer.write('┊ ');
+ }
+ if (extra > 0) {
+ buffer.write('┊ ');
+ for (int i = 1; i < extra; i++) {
+ buffer.write(' ');
+ }
+ }
+ }
+
+ /**
+ * Write a representation of the given [properties] to the buffer.
+ */
+ void writeProperties(Map<String, Object> properties) {
+ List<String> propertyNames = properties.keys.toList();
+ propertyNames.sort();
+ for (String propertyName in propertyNames) {
+ writeProperty(propertyName, properties[propertyName]);
+ }
+ }
+
+ /**
+ * Write the [value] of the property with the given [name].
+ */
+ void writeProperty(String name, Object value) {
+ if (value != null) {
+ indent(2);
+ buffer.write('$name = ');
+ _writePropertyValue(value, indentLevel);
+ buffer.write('<br>');
+ }
+ }
+
+ String _toString(Object value) {
+ try {
+ if (value is Source) {
+ return 'Source (uri="${value.uri}", path="${value.fullName}")';
+ } else if (value is ElementAnnotationImpl) {
+ StringBuffer buffer = new StringBuffer();
+ buffer.write(_toString(value.element));
+ EvaluationResultImpl result = value.evaluationResult;
+ if (result == null) {
+ buffer.write(': no result');
+ } else {
+ buffer.write(': value = ');
+ buffer.write(result.value);
+ buffer.write('; errors = ');
+ buffer.write(result.errors);
+ }
+ return buffer.toString();
+ } else {
+ return value.toString();
+ }
+ } catch (exception, stackTrace) {
+ exceptions.add(new CaughtException(exception, stackTrace));
+ }
+ return null;
+ }
+
+ /**
+ * Write the [value] of the property with the given [name].
+ */
+ void _writePropertyValue(Object value, int baseIndent) {
+ if (value is List) {
+ if (value.isEmpty) {
+ buffer.write('[]');
+ } else {
+ int elementIndent = baseIndent + 2;
+ buffer.write('[<br>');
+ for (Object element in value) {
+ indent(elementIndent);
+ _writePropertyValue(element, elementIndent);
+ buffer.write('<br>');
+ }
+ indent(baseIndent);
+ buffer.write(']');
+ }
+ } else {
+ String valueString = _toString(value);
+ if (valueString == null) {
+ buffer.write('<span style="color: #FF0000">');
+ buffer.write(HTML_ESCAPE.convert(value.runtimeType.toString()));
+ buffer.write('</span>');
+ } else {
+ buffer.write(HTML_ESCAPE.convert(valueString));
+ if (value is Element && value is! LibraryElement) {
+ String name = value.name;
+ if (name != null) {
+ buffer.write(' [');
+ buffer.write(GetHandler.makeLink(GetHandler.INDEX_ELEMENT_BY_NAME, {
+ 'name': name
+ }, 'search index'));
+ buffer.write(']');
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/pkg/analysis_server/test/analysis/notification_navigation_test.dart b/pkg/analysis_server/test/analysis/notification_navigation_test.dart
index b04ff9c..a68da1d 100644
--- a/pkg/analysis_server/test/analysis/notification_navigation_test.dart
+++ b/pkg/analysis_server/test/analysis/notification_navigation_test.dart
@@ -255,6 +255,129 @@
});
}
+ test_factoryRedirectingConstructor_implicit() {
+ addTestFile('''
+class A {
+ factory A() = B;
+}
+class B {
+}
+''');
+ return prepareNavigation().then((_) {
+ assertHasRegion('B;');
+ assertHasTarget('B {');
+ });
+ }
+
+ test_factoryRedirectingConstructor_implicit_withTypeArgument() {
+ addTestFile('''
+class A {}
+class B {
+ factory B() = C<A>;
+}
+class C<T> {}
+''');
+ return prepareNavigation().then((_) {
+ {
+ assertHasRegion('C<A>');
+ assertHasTarget('C<T> {');
+ }
+ {
+ assertHasRegion('A>;');
+ assertHasTarget('A {');
+ }
+ });
+ }
+
+ test_factoryRedirectingConstructor_named() {
+ addTestFile('''
+class A {
+ factory A() = B.named;
+}
+class B {
+ B.named();
+}
+''');
+ return prepareNavigation().then((_) {
+ assertHasRegionString('B.named');
+ assertHasTarget('named();');
+ });
+ }
+
+ test_factoryRedirectingConstructor_named_withTypeArgument() {
+ addTestFile('''
+class A {}
+class B {
+ factory B.named() = C<A>.named;
+}
+class C<T> {
+ C.named() {}
+}
+''');
+ return prepareNavigation().then((_) {
+ {
+ assertHasRegion('C<A>');
+ assertHasTarget('named() {}');
+ }
+ {
+ assertHasRegion('A>.named');
+ assertHasTarget('A {');
+ }
+ {
+ assertHasRegion('.named;', '.named'.length);
+ assertHasTarget('named() {}');
+ }
+ });
+ }
+
+ test_factoryRedirectingConstructor_unnamed() {
+ addTestFile('''
+class A {
+ factory A() = B;
+}
+class B {
+ B() {}
+}
+''');
+ return prepareNavigation().then((_) {
+ assertHasRegion('B;');
+ assertHasTarget('B() {}', 0);
+ });
+ }
+
+ test_factoryRedirectingConstructor_unnamed_withTypeArgument() {
+ addTestFile('''
+class A {}
+class B {
+ factory B() = C<A>;
+}
+class C<T> {
+ C() {}
+}
+''');
+ return prepareNavigation().then((_) {
+ {
+ assertHasRegion('C<A>');
+ assertHasTarget('C() {}', 0);
+ }
+ {
+ assertHasRegion('A>;');
+ assertHasTarget('A {');
+ }
+ });
+ }
+
+ test_factoryRedirectingConstructor_unresolved() {
+ addTestFile('''
+class A {
+ factory A() = B;
+}
+''');
+ return prepareNavigation().then((_) {
+ // don't check regions, but there should be no exceptions
+ });
+ }
+
test_fieldFormalParameter() {
addTestFile('''
class AAA {
@@ -370,7 +493,7 @@
addTestFile('''
class A {}
class B<T> {
- A.named() {}
+ B.named() {}
}
main() {
new B<A>.named();
diff --git a/pkg/analysis_server/test/analysis/notification_outline_test.dart b/pkg/analysis_server/test/analysis/notification_outline_test.dart
index b92ec52..8b6eccf 100644
--- a/pkg/analysis_server/test/analysis/notification_outline_test.dart
+++ b/pkg/analysis_server/test/analysis/notification_outline_test.dart
@@ -256,6 +256,39 @@
});
}
+ test_enum() {
+ addTestFile('''
+enum MyEnum {
+ A, B, C
+}
+''');
+ return prepareOutline().then((_) {
+ Outline unitOutline = outline;
+ List<Outline> topOutlines = unitOutline.children;
+ expect(topOutlines, hasLength(1));
+ // MyEnum
+ {
+ Outline outline_MyEnum = topOutlines[0];
+ Element element_MyEnum = outline_MyEnum.element;
+ expect(element_MyEnum.kind, ElementKind.ENUM);
+ expect(element_MyEnum.name, "MyEnum");
+ {
+ Location location = element_MyEnum.location;
+ expect(location.offset, testCode.indexOf("MyEnum {"));
+ expect(location.length, 'MyEnum'.length);
+ }
+ expect(element_MyEnum.parameters, null);
+ expect(element_MyEnum.returnType, null);
+ // MyEnum children
+ List<Outline> outlines_MyEnum = outline_MyEnum.children;
+ expect(outlines_MyEnum, hasLength(3));
+ _isEnumConstant(outlines_MyEnum[0], 'A');
+ _isEnumConstant(outlines_MyEnum[1], 'B');
+ _isEnumConstant(outlines_MyEnum[2], 'C');
+ }
+ });
+ }
+
/**
* Code like this caused NPE in the past.
*
@@ -760,4 +793,12 @@
}
});
}
+
+ void _isEnumConstant(Outline outline, String name) {
+ Element element = outline.element;
+ expect(element.kind, ElementKind.ENUM_CONSTANT);
+ expect(element.name, name);
+ expect(element.parameters, isNull);
+ expect(element.returnType, isNull);
+ }
}
diff --git a/pkg/analysis_server/test/context_manager_test.dart b/pkg/analysis_server/test/context_manager_test.dart
index fd4d116..0eecd28 100644
--- a/pkg/analysis_server/test/context_manager_test.dart
+++ b/pkg/analysis_server/test/context_manager_test.dart
@@ -189,15 +189,6 @@
expect(filePaths, isEmpty);
}
- void test_setRoots_addFolderWithoutPubspec() {
- packageMapProvider.packageMap = null;
- manager.setRoots(<String>[projPath], <String>[], <String, String>{});
- // verify
- expect(manager.currentContextPaths, hasLength(1));
- expect(manager.currentContextPaths, contains(projPath));
- expect(manager.currentContextFilePaths[projPath], hasLength(0));
- }
-
void test_setRoots_addFolderWithPubspec() {
String pubspecPath = posix.join(projPath, 'pubspec.yaml');
resourceProvider.newFile(pubspecPath, 'pubspec');
@@ -220,6 +211,9 @@
newFile([srcPath, 'internal.dart']);
String testFilePath = newFile([testPath, 'main_test.dart']);
+ packageMapProvider.packageMap['proj'] =
+ [resourceProvider.getResource(libPath)];
+
manager.setRoots(<String>[projPath], <String>[], <String, String>{});
Set<Source> sources = manager.currentContextSources[projPath];
@@ -274,6 +268,15 @@
equals(packageMapProvider.packageMaps[subProjectB]));
}
+ void test_setRoots_addFolderWithoutPubspec() {
+ packageMapProvider.packageMap = null;
+ manager.setRoots(<String>[projPath], <String>[], <String, String>{});
+ // verify
+ expect(manager.currentContextPaths, hasLength(1));
+ expect(manager.currentContextPaths, contains(projPath));
+ expect(manager.currentContextFilePaths[projPath], hasLength(0));
+ }
+
void test_setRoots_addPackageRoot() {
String packagePathFoo = '/package1/foo';
String packageRootPath = '/package2/foo';
@@ -468,17 +471,6 @@
_checkPackageMap(projPath, equals(packageMapProvider.packageMap));
}
- void test_setRoots_removeFolderWithoutPubspec() {
- packageMapProvider.packageMap = null;
- // add one root - there is a context
- manager.setRoots(<String>[projPath], <String>[], <String, String>{});
- expect(manager.currentContextPaths, hasLength(1));
- // set empty roots - no contexts
- manager.setRoots(<String>[], <String>[], <String, String>{});
- expect(manager.currentContextPaths, hasLength(0));
- expect(manager.currentContextFilePaths, hasLength(0));
- }
-
void test_setRoots_removeFolderWithPubspec() {
// create a pubspec
String pubspecPath = posix.join(projPath, 'pubspec.yaml');
@@ -528,6 +520,17 @@
manager.assertContextFiles(subProjectA, [subProjectA_file]);
}
+ void test_setRoots_removeFolderWithoutPubspec() {
+ packageMapProvider.packageMap = null;
+ // add one root - there is a context
+ manager.setRoots(<String>[projPath], <String>[], <String, String>{});
+ expect(manager.currentContextPaths, hasLength(1));
+ // set empty roots - no contexts
+ manager.setRoots(<String>[], <String>[], <String, String>{});
+ expect(manager.currentContextPaths, hasLength(0));
+ expect(manager.currentContextFilePaths, hasLength(0));
+ }
+
void test_setRoots_removePackageRoot() {
String packagePathFoo = '/package1/foo';
String packageRootPath = '/package2/foo';
@@ -574,6 +577,21 @@
});
}
+ test_watch_addFileInSubfolder() {
+ manager.setRoots(<String>[projPath], <String>[], <String, String>{});
+ // empty folder initially
+ Map<String, int> filePaths = manager.currentContextFilePaths[projPath];
+ expect(filePaths, hasLength(0));
+ // add file in subfolder
+ String filePath = posix.join(projPath, 'foo', 'bar.dart');
+ resourceProvider.newFile(filePath, 'contents');
+ // the file was added
+ return pumpEventQueue().then((_) {
+ expect(filePaths, hasLength(1));
+ expect(filePaths, contains(filePath));
+ });
+ }
+
test_watch_addFile_excluded() {
// prepare paths
String project = '/project';
@@ -595,21 +613,6 @@
});
}
- test_watch_addFileInSubfolder() {
- manager.setRoots(<String>[projPath], <String>[], <String, String>{});
- // empty folder initially
- Map<String, int> filePaths = manager.currentContextFilePaths[projPath];
- expect(filePaths, hasLength(0));
- // add file in subfolder
- String filePath = posix.join(projPath, 'foo', 'bar.dart');
- resourceProvider.newFile(filePath, 'contents');
- // the file was added
- return pumpEventQueue().then((_) {
- expect(filePaths, hasLength(1));
- expect(filePaths, contains(filePath));
- });
- }
-
test_watch_addPubspec_toRoot() {
// prepare paths
String root = '/root';
@@ -881,7 +884,10 @@
currentContextFilePaths[path] = <String, int>{};
currentContextSources[path] = new HashSet<Source>();
currentContextPackageUriResolvers[path] = packageUriResolver;
- return null;
+ AnalysisContextImpl context = new AnalysisContextImpl();
+ context.sourceFactory =
+ new SourceFactory(packageUriResolver == null ? [] : [packageUriResolver]);
+ return context;
}
@override
diff --git a/pkg/analysis_server/test/domain_completion_test.dart b/pkg/analysis_server/test/domain_completion_test.dart
index 21307d5..cfe1bb2 100644
--- a/pkg/analysis_server/test/domain_completion_test.dart
+++ b/pkg/analysis_server/test/domain_completion_test.dart
@@ -34,6 +34,7 @@
groupSep = ' | ';
runReflectiveTests(CompletionManagerTest);
runReflectiveTests(CompletionTest);
+ runReflectiveTests(_NoSearchEngine);
}
@reflectiveTest
@@ -55,6 +56,11 @@
InstrumentationService.NULL_SERVICE);
}
+ @override
+ Index createIndex() {
+ return createLocalMemoryIndex();
+ }
+
void sendRequest(String path) {
String id = (++requestCount).toString();
request = new CompletionGetSuggestionsParams(path, 0).toRequest(id);
@@ -565,8 +571,12 @@
* Mock [AnaysisContext] for tracking usage of onSourcesChanged.
*/
class MockContext implements AnalysisContext {
+ static final SourceFactory DEFAULT_SOURCE_FACTORY = new SourceFactory([]);
+
MockStream<SourcesChangedEvent> mockStream;
+ SourceFactory sourceFactory = DEFAULT_SOURCE_FACTORY;
+
MockContext() {
mockStream = new MockStream<SourcesChangedEvent>();
}
@@ -665,3 +675,29 @@
return new MockCompletionManager(mockContext, source, searchEngine);
}
}
+<<<<<<< .working
+
+@reflectiveTest
+class _NoSearchEngine extends AbstractAnalysisTest {
+ @override
+ void setUp() {
+ super.setUp();
+ createProject();
+ handler = new CompletionDomainHandler(server);
+ }
+
+ test_noSearchEngine() async {
+ addTestFile('''
+main() {
+ ^
+}
+ ''');
+ await waitForTasksFinished();
+ Request request =
+ new CompletionGetSuggestionsParams(testFile, 0).toRequest('0');
+ Response response = handler.handleRequest(request);
+ expect(response.error, isNotNull);
+ expect(response.error.code, RequestErrorCode.NO_INDEX_GENERATED);
+ }
+}
+>>>>>>> .merge-right.r43886
diff --git a/pkg/analysis_server/test/edit/refactoring_test.dart b/pkg/analysis_server/test/edit/refactoring_test.dart
index 51e1a4e..ad3ff90 100644
--- a/pkg/analysis_server/test/edit/refactoring_test.dart
+++ b/pkg/analysis_server/test/edit/refactoring_test.dart
@@ -28,6 +28,7 @@
runReflectiveTests(InlineMethodTest);
runReflectiveTests(MoveFileTest);
runReflectiveTests(RenameTest);
+ runReflectiveTests(_NoSearchEngine);
}
@@ -627,40 +628,61 @@
@reflectiveTest
class GetAvailableRefactoringsTest extends AbstractAnalysisTest {
+ List<RefactoringKind> kinds;
+
/**
* Tests that there is a RENAME refactoring available at the [search] offset.
*/
- Future assertHasRenameRefactoring(String code, String search) {
+ Future assertHasRenameRefactoring(String code, String search) async {
+ return assertHasKind(code, search, RefactoringKind.RENAME, true);
+ }
+
+ /**
+ * Tests that there is refactoring of the given [kind] is available at the
+ * [search] offset.
+ */
+ Future assertHasKind(String code, String search, RefactoringKind kind,
+ bool expected) async {
addTestFile(code);
- return waitForTasksFinished().then((_) {
- List<RefactoringKind> kinds = getRefactoringsAtString(search);
- expect(kinds, contains(RefactoringKind.RENAME));
- });
+ await waitForTasksFinished();
+ await getRefactoringsAtString(search);
+ // verify
+ Matcher matcher = contains(kind);
+ if (!expected) {
+ matcher = isNot(matcher);
+ }
+ expect(kinds, matcher);
+ }
+
+ @override
+ Index createIndex() {
+ return createLocalMemoryIndex();
}
/**
* Returns the list of available refactorings for the given [offset] and
* [length].
*/
- List<RefactoringKind> getRefactorings(int offset, int length) {
+ Future getRefactorings(int offset, int length) async {
Request request = new EditGetAvailableRefactoringsParams(
testFile,
offset,
length).toRequest('0');
- Response response = handleSuccessfulRequest(request);
+ serverChannel.sendRequest(request);
+ var response = await serverChannel.waitForResponse(request);
var result = new EditGetAvailableRefactoringsResult.fromResponse(response);
- return result.kinds;
+ kinds = result.kinds;
}
/**
* Returns the list of available refactorings at the offset of [search].
*/
- List<RefactoringKind> getRefactoringsAtString(String search) {
+ Future getRefactoringsAtString(String search) {
int offset = findOffset(search);
return getRefactorings(offset, 0);
}
- List<RefactoringKind> getRefactoringsForString(String search) {
+ Future getRefactoringsForString(String search) {
int offset = findOffset(search);
return getRefactorings(offset, search.length);
}
@@ -670,20 +692,25 @@
super.setUp();
createProject();
handler = new EditDomainHandler(server);
+ server.handlers = [handler];
}
- Future test_extractLocal() {
+ Future test_extractLocal() async {
addTestFile('''
main() {
var a = 1 + 2;
}
''');
- return waitForTasksFinished().then((_) {
- var search = '1 + 2';
- List<RefactoringKind> kinds = getRefactoringsForString(search);
- expect(kinds, contains(RefactoringKind.EXTRACT_LOCAL_VARIABLE));
- expect(kinds, contains(RefactoringKind.EXTRACT_METHOD));
- });
+ await waitForTasksFinished();
+ await getRefactoringsForString('1 + 2');
+ expect(kinds, contains(RefactoringKind.EXTRACT_LOCAL_VARIABLE));
+ expect(kinds, contains(RefactoringKind.EXTRACT_METHOD));
+ }
+
+ Future test_convertMethodToGetter_hasElement() {
+ return assertHasKind('''
+int getValue() => 42;
+''', 'getValue', RefactoringKind.CONVERT_METHOD_TO_GETTER, true);
}
Future test_rename_hasElement_class() {
@@ -791,17 +818,15 @@
''', 'test();');
}
- Future test_rename_noElement() {
+ Future test_rename_noElement() async {
addTestFile('''
main() {
// not an element
}
''');
- return waitForTasksFinished().then((_) {
- List<RefactoringKind> kinds =
- getRefactoringsAtString('// not an element');
- expect(kinds, isNot(contains(RefactoringKind.RENAME)));
- });
+ await waitForTasksFinished();
+ await getRefactoringsAtString('// not an element');
+ expect(kinds, isNot(contains(RefactoringKind.RENAME)));
}
}
@@ -1029,8 +1054,8 @@
@reflectiveTest
class RenameTest extends _AbstractGetRefactoring_Test {
- Future<Response> sendRenameRequest(String search, String newName,
- {String id: '0', bool validateOnly: false}) {
+ Future<Response> sendRenameRequest(String search, String newName, {String id:
+ '0', bool validateOnly: false}) {
RenameOptions options = newName != null ? new RenameOptions(newName) : null;
Request request = new EditGetRefactoringParams(
RefactoringKind.RENAME,
@@ -1057,7 +1082,9 @@
Response responseA = await futureA;
// "1" was cancelled
// "2" is successful
- expect(responseA, isResponseFailure('1', RequestErrorCode.REFACTORING_REQUEST_CANCELLED));
+ expect(
+ responseA,
+ isResponseFailure('1', RequestErrorCode.REFACTORING_REQUEST_CANCELLED));
expect(responseB, isResponseSuccess('2'));
}
@@ -1326,6 +1353,27 @@
''');
}
+ test_constructor_fromFactoryRedirectingConstructor_onClassName() {
+ addTestFile('''
+class A {
+ A() = B;
+}
+class B {
+ B() {}
+}
+''');
+ return assertSuccessfulRefactoring(() {
+ return sendRenameRequest('B;', 'newName');
+ }, '''
+class A {
+ A() = B.newName;
+}
+class B {
+ B.newName() {}
+}
+''');
+ }
+
test_constructor_fromInstanceCreation() {
addTestFile('''
class A {
@@ -1576,7 +1624,10 @@
// send the second request, with the same kind, file and offset
return waitForTasksFinished().then((_) {
return getRefactoringResult(() {
- return sendRenameRequest('otherName =', 'newName', validateOnly: true);
+ return sendRenameRequest(
+ 'otherName =',
+ 'newName',
+ validateOnly: true);
}).then((result) {
RenameFeedback feedback = result.feedback;
// the refactoring was reset, so we don't get a stale result
@@ -1718,3 +1769,46 @@
handler = new EditDomainHandler(server);
}
}
+
+
+@reflectiveTest
+class _NoSearchEngine extends _AbstractGetRefactoring_Test {
+ @override
+ Index createIndex() {
+ return null;
+ }
+
+ test_getAvailableRefactorings() async {
+ addTestFile('''
+main() {
+ print(1 + 2);
+}
+''');
+ await waitForTasksFinished();
+ Request request =
+ new EditGetAvailableRefactoringsParams(testFile, 0, 0).toRequest('0');
+ return _assertErrorResposeNoIndex(request);
+ }
+
+ test_getRefactoring_noSearchEngine() async {
+ addTestFile('''
+main() {
+ print(1 + 2);
+}
+''');
+ await waitForTasksFinished();
+ Request request = new EditGetRefactoringParams(
+ RefactoringKind.EXTRACT_LOCAL_VARIABLE,
+ testFile,
+ 0,
+ 0,
+ true).toRequest('0');
+ return _assertErrorResposeNoIndex(request);
+ }
+
+ _assertErrorResposeNoIndex(Request request) async {
+ Response response = await serverChannel.sendRequest(request);
+ expect(response.error, isNotNull);
+ expect(response.error.code, RequestErrorCode.NO_INDEX_GENERATED);
+ }
+}
diff --git a/pkg/analysis_server/test/integration/protocol_matchers.dart b/pkg/analysis_server/test/integration/protocol_matchers.dart
index 3afd352..633c380 100644
--- a/pkg/analysis_server/test/integration/protocol_matchers.dart
+++ b/pkg/analysis_server/test/integration/protocol_matchers.dart
@@ -1199,6 +1199,8 @@
* CLASS_TYPE_ALIAS
* COMPILATION_UNIT
* CONSTRUCTOR
+ * ENUM
+ * ENUM_CONSTANT
* FIELD
* FUNCTION
* FUNCTION_TYPE_ALIAS
@@ -1222,6 +1224,8 @@
"CLASS_TYPE_ALIAS",
"COMPILATION_UNIT",
"CONSTRUCTOR",
+ "ENUM",
+ "ENUM_CONSTANT",
"FIELD",
"FUNCTION",
"FUNCTION_TYPE_ALIAS",
@@ -1817,6 +1821,7 @@
* INVALID_OVERLAY_CHANGE
* INVALID_PARAMETER
* INVALID_REQUEST
+ * NO_INDEX_GENERATED
* REFACTORING_REQUEST_CANCELLED
* SERVER_ALREADY_STARTED
* SERVER_ERROR
@@ -1835,6 +1840,7 @@
"INVALID_OVERLAY_CHANGE",
"INVALID_PARAMETER",
"INVALID_REQUEST",
+ "NO_INDEX_GENERATED",
"REFACTORING_REQUEST_CANCELLED",
"SERVER_ALREADY_STARTED",
"SERVER_ERROR",
diff --git a/pkg/analysis_server/test/mocks.dart b/pkg/analysis_server/test/mocks.dart
index 9475cbb..cb314c6 100644
--- a/pkg/analysis_server/test/mocks.dart
+++ b/pkg/analysis_server/test/mocks.dart
@@ -58,7 +58,7 @@
* times. By default, this should pump the event queue enough times to allow
* any code to run, as long as it's not waiting on some external event.
*/
-Future pumpEventQueue([int times = 50]) {
+Future pumpEventQueue([int times = 500]) {
if (times == 0) return new Future.value();
// We use a delayed future to allow microtask events to finish. The
// Future.value or Future() constructors use scheduleMicrotask themselves and
diff --git a/pkg/analysis_server/test/search/element_references_test.dart b/pkg/analysis_server/test/search/element_references_test.dart
index a2b0a5c..7bcba7b 100644
--- a/pkg/analysis_server/test/search/element_references_test.dart
+++ b/pkg/analysis_server/test/search/element_references_test.dart
@@ -7,6 +7,7 @@
import 'dart:async';
import 'package:analysis_server/src/protocol.dart';
+import 'package:analysis_server/src/services/index/index.dart';
import 'package:unittest/unittest.dart';
import '../reflective_tests.dart';
@@ -16,6 +17,7 @@
main() {
groupSep = ' | ';
runReflectiveTests(ElementReferencesTest);
+ runReflectiveTests(_NoSearchEngine);
}
@@ -58,6 +60,7 @@
''');
await findElementReferences('named(p)', false);
expect(searchElement.kind, ElementKind.CONSTRUCTOR);
+ expect(results, hasLength(2));
assertHasResult(SearchResultKind.REFERENCE, '.named(1)', 6);
assertHasResult(SearchResultKind.REFERENCE, '.named(2)', 6);
}
@@ -81,9 +84,8 @@
''');
await findElementReferences('named(p); // A', true);
expect(searchElement.kind, ElementKind.CONSTRUCTOR);
- assertHasResult(SearchResultKind.DECLARATION, '.named(p)', 6);
+ expect(results, hasLength(1));
assertHasResult(SearchResultKind.REFERENCE, '.named(1)', 6);
- expect(results, hasLength(2));
}
test_constructor_unnamed() async {
@@ -98,6 +100,7 @@
''');
await findElementReferences('A(p)', false);
expect(searchElement.kind, ElementKind.CONSTRUCTOR);
+ expect(results, hasLength(2));
assertHasResult(SearchResultKind.REFERENCE, '(1)', 0);
assertHasResult(SearchResultKind.REFERENCE, '(2)', 0);
}
@@ -126,9 +129,8 @@
''');
await findElementReferences('A(p)', true);
expect(searchElement.kind, ElementKind.CONSTRUCTOR);
- assertHasResult(SearchResultKind.DECLARATION, '(p); // A', 0);
+ expect(results, hasLength(1));
assertHasResult(SearchResultKind.REFERENCE, '(1)', 0);
- expect(results, hasLength(2));
}
test_field_explicit() async {
@@ -136,6 +138,7 @@
class A {
var fff; // declaration
A(this.fff); // in constructor
+ A.named() : fff = 1;
m() {
fff = 2;
fff += 3;
@@ -152,9 +155,10 @@
''');
await findElementReferences('fff; // declaration', false);
expect(searchElement.kind, ElementKind.FIELD);
- expect(results, hasLength(10));
+ expect(results, hasLength(11));
assertHasResult(SearchResultKind.DECLARATION, 'fff; // declaration');
- assertHasResult(SearchResultKind.REFERENCE, 'fff); // in constructor');
+ assertHasResult(SearchResultKind.WRITE, 'fff); // in constructor');
+ assertHasResult(SearchResultKind.WRITE, 'fff = 1;');
// m()
assertHasResult(SearchResultKind.WRITE, 'fff = 2;');
assertHasResult(SearchResultKind.WRITE, 'fff += 3;');
@@ -216,7 +220,7 @@
expect(searchElement.kind, ElementKind.FIELD);
expect(results, hasLength(4));
assertHasResult(SearchResultKind.DECLARATION, 'fff; // declaration');
- assertHasResult(SearchResultKind.REFERENCE, 'fff); // in constructor');
+ assertHasResult(SearchResultKind.WRITE, 'fff); // in constructor');
assertHasResult(SearchResultKind.WRITE, 'fff = 2;');
assertHasResult(SearchResultKind.READ, 'fff); // in m()');
}
@@ -704,3 +708,26 @@
assertHasResult(SearchResultKind.REFERENCE, 'T m()');
}
}
+
+
+@reflectiveTest
+class _NoSearchEngine extends AbstractSearchDomainTest {
+ @override
+ Index createIndex() {
+ return null;
+ }
+
+ test_requestError_noSearchEngine() async {
+ addTestFile('''
+main() {
+ var vvv = 1;
+ print(vvv);
+}
+''');
+ Request request =
+ new SearchFindElementReferencesParams(testFile, 0, false).toRequest('0');
+ Response response = await waitResponse(request);
+ expect(response.error, isNotNull);
+ expect(response.error.code, RequestErrorCode.NO_INDEX_GENERATED);
+ }
+}
diff --git a/pkg/analysis_server/test/services/completion/completion_test_util.dart b/pkg/analysis_server/test/services/completion/completion_test_util.dart
index 573f604..0b242bd 100644
--- a/pkg/analysis_server/test/services/completion/completion_test_util.dart
+++ b/pkg/analysis_server/test/services/completion/completion_test_util.dart
@@ -2697,6 +2697,15 @@
});
}
+ test_PrefixedIdentifier_getter() {
+ // SimpleIdentifier PrefixedIdentifier ExpressionStatement
+ addTestSource('String get g => "one"; f() {g.^}');
+ computeFast();
+ return computeFull((bool result) {
+ assertSuggestInvocationGetter('length', 'int');
+ });
+ }
+
test_PrefixedIdentifier_library() {
// SimpleIdentifier PrefixedIdentifier ExpressionStatement
addSource('/testB.dart', '''
diff --git a/pkg/analysis_server/test/services/completion/keyword_computer_test.dart b/pkg/analysis_server/test/services/completion/keyword_computer_test.dart
index c51d186..d0bf83f 100644
--- a/pkg/analysis_server/test/services/completion/keyword_computer_test.dart
+++ b/pkg/analysis_server/test/services/completion/keyword_computer_test.dart
@@ -20,6 +20,45 @@
@reflectiveTest
class KeywordComputerTest extends AbstractCompletionTest {
+ static const List<Keyword> IN_BLOCK_IN_CLASS =
+ const [
+ Keyword.ASSERT,
+ Keyword.CASE,
+ Keyword.CONTINUE,
+ Keyword.DO,
+ Keyword.FINAL,
+ Keyword.FOR,
+ Keyword.IF,
+ Keyword.NEW,
+ Keyword.RETHROW,
+ Keyword.RETURN,
+ Keyword.SUPER,
+ Keyword.SWITCH,
+ Keyword.THIS,
+ Keyword.THROW,
+ Keyword.TRY,
+ Keyword.VAR,
+ Keyword.VOID,
+ Keyword.WHILE];
+
+ static const List<Keyword> IN_BLOCK_NOT_IN_CLASS =
+ const [
+ Keyword.ASSERT,
+ Keyword.CASE,
+ Keyword.CONTINUE,
+ Keyword.DO,
+ Keyword.FINAL,
+ Keyword.FOR,
+ Keyword.IF,
+ Keyword.NEW,
+ Keyword.RETHROW,
+ Keyword.RETURN,
+ Keyword.SWITCH,
+ Keyword.THROW,
+ Keyword.TRY,
+ Keyword.VAR,
+ Keyword.VOID,
+ Keyword.WHILE];
void assertSuggestKeywords(Iterable<Keyword> expectedKeywords, [int relevance
= DART_RELEVANCE_KEYWORD]) {
@@ -267,56 +306,64 @@
DART_RELEVANCE_HIGH);
}
- test_function_body() {
- addTestSource('main() {^}');
+ test_function_body_inClass_constructorInitializer() {
+ addTestSource(r'''
+foo(p) {}
+class A {
+ final f;
+ A() : f = foo(() {^});
+}
+''');
expect(computeFast(), isTrue);
- assertSuggestKeywords(
- [
- Keyword.ASSERT,
- Keyword.CASE,
- Keyword.CONTINUE,
- Keyword.DO,
- Keyword.FACTORY,
- Keyword.FINAL,
- Keyword.FOR,
- Keyword.IF,
- Keyword.NEW,
- Keyword.RETHROW,
- Keyword.RETURN,
- Keyword.SUPER,
- Keyword.SWITCH,
- Keyword.THIS,
- Keyword.THROW,
- Keyword.TRY,
- Keyword.VAR,
- Keyword.VOID,
- Keyword.WHILE]);
+ assertSuggestKeywords(IN_BLOCK_NOT_IN_CLASS);
}
- test_function_body2() {
+ test_function_body_inClass_field() {
+ addTestSource(r'''
+class A {
+ var f = () {^};
+}
+''');
+ expect(computeFast(), isTrue);
+ assertSuggestKeywords(IN_BLOCK_NOT_IN_CLASS);
+ }
+
+ test_function_body_inClass_methodBody() {
+ addTestSource(r'''
+class A {
+ m() {
+ f() {^};
+ }
+}
+''');
+ expect(computeFast(), isTrue);
+ assertSuggestKeywords(IN_BLOCK_IN_CLASS);
+ }
+
+ test_function_body_inClass_methodBody_inFunction() {
+ addTestSource(r'''
+class A {
+ m() {
+ f() {
+ f2() {^};
+ };
+ }
+}
+''');
+ expect(computeFast(), isTrue);
+ assertSuggestKeywords(IN_BLOCK_IN_CLASS);
+ }
+
+ test_function_body_inUnit() {
+ addTestSource('main() {^}');
+ expect(computeFast(), isTrue);
+ assertSuggestKeywords(IN_BLOCK_NOT_IN_CLASS);
+ }
+
+ test_function_body_inUnit_afterBlock() {
addTestSource('main() {{}^}');
expect(computeFast(), isTrue);
- assertSuggestKeywords(
- [
- Keyword.ASSERT,
- Keyword.CASE,
- Keyword.CONTINUE,
- Keyword.DO,
- Keyword.FACTORY,
- Keyword.FINAL,
- Keyword.FOR,
- Keyword.IF,
- Keyword.NEW,
- Keyword.RETHROW,
- Keyword.RETURN,
- Keyword.SUPER,
- Keyword.SWITCH,
- Keyword.THIS,
- Keyword.THROW,
- Keyword.TRY,
- Keyword.VAR,
- Keyword.VOID,
- Keyword.WHILE]);
+ assertSuggestKeywords(IN_BLOCK_NOT_IN_CLASS);
}
test_in_class() {
@@ -362,27 +409,7 @@
test_method_body() {
addTestSource('class A { foo() {^}}');
expect(computeFast(), isTrue);
- assertSuggestKeywords(
- [
- Keyword.ASSERT,
- Keyword.CASE,
- Keyword.CONTINUE,
- Keyword.DO,
- Keyword.FACTORY,
- Keyword.FINAL,
- Keyword.FOR,
- Keyword.IF,
- Keyword.NEW,
- Keyword.RETHROW,
- Keyword.RETURN,
- Keyword.SUPER,
- Keyword.SWITCH,
- Keyword.THIS,
- Keyword.THROW,
- Keyword.TRY,
- Keyword.VAR,
- Keyword.VOID,
- Keyword.WHILE]);
+ assertSuggestKeywords(IN_BLOCK_IN_CLASS);
}
test_named_constructor_invocation() {
diff --git a/pkg/analysis_server/test/services/correction/assist_test.dart b/pkg/analysis_server/test/services/correction/assist_test.dart
index 5db7631..4c48713 100644
--- a/pkg/analysis_server/test/services/correction/assist_test.dart
+++ b/pkg/analysis_server/test/services/correction/assist_test.dart
@@ -6,9 +6,6 @@
import 'package:analysis_server/src/protocol.dart';
import 'package:analysis_server/src/services/correction/assist.dart';
-import 'package:analysis_server/src/services/index/index.dart';
-import 'package:analysis_server/src/services/index/local_memory_index.dart';
-import 'package:analysis_server/src/services/search/search_engine_internal.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:unittest/unittest.dart';
@@ -24,9 +21,6 @@
@reflectiveTest
class AssistProcessorTest extends AbstractSingleUnitTest {
- Index index;
- SearchEngineImpl searchEngine;
-
int offset;
int length;
@@ -63,8 +57,7 @@
* Asserts that there is no [Assist] of the given [kind] at [offset].
*/
void assertNoAssist(AssistKind kind) {
- List<Assist> assists =
- computeAssists(searchEngine, testUnit, offset, length);
+ List<Assist> assists = computeAssists(testUnit, offset, length);
for (Assist assist in assists) {
if (assist.kind == kind) {
throw fail('Unexpected assist $kind in\n${assists.join('\n')}');
@@ -102,14 +95,12 @@
void setUp() {
super.setUp();
- index = createLocalMemoryIndex();
- searchEngine = new SearchEngineImpl(index);
offset = 0;
length = 0;
}
void test_addTypeAnnotation_classField_OK_final() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
final f = 0;
}
@@ -122,7 +113,7 @@
}
void test_addTypeAnnotation_classField_OK_int() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
var f = 0;
}
@@ -135,7 +126,7 @@
}
void test_addTypeAnnotation_declaredIdentifier_BAD_hasTypeAnnotation() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(List<String> items) {
for (String item in items) {
}
@@ -145,7 +136,7 @@
}
void test_addTypeAnnotation_declaredIdentifier_BAD_inForEachBody() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(List<String> items) {
for (var item in items) {
42;
@@ -157,7 +148,7 @@
void test_addTypeAnnotation_declaredIdentifier_BAD_unknownType() {
verifyNoTestUnitErrors = false;
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
for (var item in unknownList) {
}
@@ -167,7 +158,7 @@
}
void test_addTypeAnnotation_declaredIdentifier_generic_OK() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A<T> {
main(List<List<T>> items) {
for (var item in items) {
@@ -186,7 +177,7 @@
}
void test_addTypeAnnotation_declaredIdentifier_OK() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(List<String> items) {
for (var item in items) {
}
@@ -213,7 +204,7 @@
import 'dart:async';
List<Future<int>> getFutures() => null;
''');
- _indexTestUnit('''
+ resolveTestUnit('''
import 'my_lib.dart';
main() {
for (var future in getFutures()) {
@@ -231,7 +222,7 @@
}
void test_addTypeAnnotation_declaredIdentifier_OK_final() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(List<String> items) {
for (final item in items) {
}
@@ -246,7 +237,7 @@
}
void test_addTypeAnnotation_local_generic_OK_literal() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main(List<int> items) {
var v = items;
@@ -263,7 +254,7 @@
}
void test_addTypeAnnotation_local_generic_OK_local() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A<T> {
main(List<T> items) {
var v = items;
@@ -284,7 +275,7 @@
import 'dart:async';
Future<int> getFutureInt() => null;
''');
- _indexTestUnit('''
+ resolveTestUnit('''
import 'my_lib.dart';
main() {
var v = getFutureInt();
@@ -361,7 +352,7 @@
import '../aa/bbb/lib_a.dart';
MyClass newMyClass() => null;
''');
- _indexTestUnit('''
+ resolveTestUnit('''
import 'ccc/lib_b.dart';
main() {
var v = newMyClass();
@@ -377,7 +368,7 @@
}
void test_addTypeAnnotation_local_OK_Function() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = () => 1;
}
@@ -390,7 +381,7 @@
}
void test_addTypeAnnotation_local_OK_int() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 0;
}
@@ -403,7 +394,7 @@
}
void test_addTypeAnnotation_local_OK_List() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = <String>[];
}
@@ -416,7 +407,7 @@
}
void test_addTypeAnnotation_local_OK_localType() {
- _indexTestUnit('''
+ resolveTestUnit('''
class C {}
C f() => null;
main() {
@@ -433,7 +424,7 @@
}
void test_addTypeAnnotation_local_OK_onInitializer() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 123;
}
@@ -446,7 +437,7 @@
}
void test_addTypeAnnotation_local_OK_onName() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var abc = 0;
}
@@ -459,7 +450,7 @@
}
void test_addTypeAnnotation_local_OK_onVar() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 0;
}
@@ -472,7 +463,7 @@
}
void test_addTypeAnnotation_local_OK_onVariableDeclarationStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 123; // marker
}
@@ -485,7 +476,7 @@
}
void test_addTypeAnnotation_local_wrong_hasTypeAnnotation() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int v = 42;
}
@@ -494,7 +485,7 @@
}
void test_addTypeAnnotation_local_wrong_multiple() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var a = 1, b = '';
}
@@ -504,7 +495,7 @@
void test_addTypeAnnotation_local_wrong_noValue() {
verifyNoTestUnitErrors = false;
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
}
@@ -513,7 +504,7 @@
}
void test_addTypeAnnotation_local_wrong_null() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = null;
}
@@ -523,7 +514,7 @@
void test_addTypeAnnotation_local_wrong_unknown() {
verifyNoTestUnitErrors = false;
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = unknownVar;
}
@@ -532,7 +523,7 @@
}
void test_addTypeAnnotation_parameter_BAD_hasExplicitType() {
- _indexTestUnit('''
+ resolveTestUnit('''
foo(f(int p)) {}
main() {
foo((num test) {});
@@ -542,7 +533,7 @@
}
void test_addTypeAnnotation_parameter_BAD_noPropagatedType() {
- _indexTestUnit('''
+ resolveTestUnit('''
foo(f(p)) {}
main() {
foo((test) {});
@@ -552,7 +543,7 @@
}
void test_addTypeAnnotation_parameter_OK() {
- _indexTestUnit('''
+ resolveTestUnit('''
foo(f(int p)) {}
main() {
foo((test) {});
@@ -567,7 +558,7 @@
}
void test_addTypeAnnotation_topLevelField_OK_int() {
- _indexTestUnit('''
+ resolveTestUnit('''
var V = 0;
''');
assertHasAssistAt('var ', AssistKind.ADD_TYPE_ANNOTATION, '''
@@ -576,21 +567,21 @@
}
void test_addTypeAnnotation_topLevelField_wrong_multiple() {
- _indexTestUnit('''
+ resolveTestUnit('''
var A = 1, V = '';
''');
assertNoAssistAt('var ', AssistKind.ADD_TYPE_ANNOTATION);
}
void test_addTypeAnnotation_topLevelField_wrong_noValue() {
- _indexTestUnit('''
+ resolveTestUnit('''
var V;
''');
assertNoAssistAt('var ', AssistKind.ADD_TYPE_ANNOTATION);
}
void test_assignToLocalVariable() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
List<int> bytes;
readBytes();
@@ -613,7 +604,7 @@
}
void test_assignToLocalVariable_alreadyAssignment() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var vvv;
vvv = 42;
@@ -623,7 +614,7 @@
}
void test_assignToLocalVariable_throw() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
throw 42;
}
@@ -632,7 +623,7 @@
}
void test_assignToLocalVariable_void() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
f();
}
@@ -642,7 +633,7 @@
}
void test_convertToBlockBody_OK_closure() {
- _indexTestUnit('''
+ resolveTestUnit('''
setup(x) {}
main() {
setup(() => print('done'));
@@ -659,7 +650,7 @@
}
void test_convertToBlockBody_OK_constructor() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
factory A() => null;
}
@@ -674,7 +665,7 @@
}
void test_convertToBlockBody_OK_method() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
mmm() => 123;
}
@@ -689,7 +680,7 @@
}
void test_convertToBlockBody_OK_onName() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() => 123;
''');
assertHasAssistAt('fff()', AssistKind.CONVERT_INTO_BLOCK_BODY, '''
@@ -700,7 +691,7 @@
}
void test_convertToBlockBody_OK_onValue() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() => 123;
''');
assertHasAssistAt('23;', AssistKind.CONVERT_INTO_BLOCK_BODY, '''
@@ -711,14 +702,14 @@
}
void test_convertToBlockBody_wrong_noEnclosingFunction() {
- _indexTestUnit('''
+ resolveTestUnit('''
var v = 123;
''');
assertNoAssistAt('v =', AssistKind.CONVERT_INTO_BLOCK_BODY);
}
void test_convertToBlockBody_wrong_notExpressionBlock() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() {
return 123;
}
@@ -727,7 +718,7 @@
}
void test_convertToExpressionBody_OK_closure() {
- _indexTestUnit('''
+ resolveTestUnit('''
setup(x) {}
main() {
setup(() {
@@ -744,7 +735,7 @@
}
void test_convertToExpressionBody_OK_constructor() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
factory A() {
return null;
@@ -759,7 +750,7 @@
}
void test_convertToExpressionBody_OK_function_onBlock() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() {
return 42;
}
@@ -770,7 +761,7 @@
}
void test_convertToExpressionBody_OK_function_onName() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() {
return 42;
}
@@ -781,7 +772,7 @@
}
void test_convertToExpressionBody_OK_method_onBlock() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
m() { // marker
return 42;
@@ -799,7 +790,7 @@
}
void test_convertToExpressionBody_OK_topFunction_onReturnStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() {
return 42;
}
@@ -810,14 +801,14 @@
}
void test_convertToExpressionBody_wrong_already() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() => 42;
''');
assertNoAssistAt('fff()', AssistKind.CONVERT_INTO_EXPRESSION_BODY);
}
void test_convertToExpressionBody_wrong_moreThanOneStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() {
var v = 42;
return v;
@@ -827,14 +818,14 @@
}
void test_convertToExpressionBody_wrong_noEnclosingFunction() {
- _indexTestUnit('''
+ resolveTestUnit('''
var V = 42;
''');
assertNoAssistAt('V = ', AssistKind.CONVERT_INTO_EXPRESSION_BODY);
}
void test_convertToExpressionBody_wrong_noReturn() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() {
var v = 42;
}
@@ -843,7 +834,7 @@
}
void test_convertToExpressionBody_wrong_noReturnValue() {
- _indexTestUnit('''
+ resolveTestUnit('''
fff() {
return;
}
@@ -852,7 +843,7 @@
}
void test_convertToIsNot_OK_childOfIs_left() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!(p is String);
}
@@ -865,7 +856,7 @@
}
void test_convertToIsNot_OK_childOfIs_right() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!(p is String);
}
@@ -878,7 +869,7 @@
}
void test_convertToIsNot_OK_is() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!(p is String);
}
@@ -891,7 +882,7 @@
}
void test_convertToIsNot_OK_is_higherPrecedencePrefix() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!!(p is String);
}
@@ -904,7 +895,7 @@
}
void test_convertToIsNot_OK_is_not_higherPrecedencePrefix() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!!(p is String);
}
@@ -917,7 +908,7 @@
}
void test_convertToIsNot_OK_not() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!(p is String);
}
@@ -930,7 +921,7 @@
}
void test_convertToIsNot_OK_parentheses() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!(p is String);
}
@@ -943,7 +934,7 @@
}
void test_convertToIsNot_wrong_is_alreadyIsNot() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
p is! String;
}
@@ -952,7 +943,7 @@
}
void test_convertToIsNot_wrong_is_noEnclosingParenthesis() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
p is String;
}
@@ -961,7 +952,7 @@
}
void test_convertToIsNot_wrong_is_noPrefix() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
(p is String);
}
@@ -970,7 +961,7 @@
}
void test_convertToIsNot_wrong_is_notIsExpression() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
123 + 456;
}
@@ -980,7 +971,7 @@
void test_convertToIsNot_wrong_is_notTheNotOperator() {
verifyNoTestUnitErrors = false;
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
++(p is String);
}
@@ -989,7 +980,7 @@
}
void test_convertToIsNot_wrong_not_alreadyIsNot() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!(p is! String);
}
@@ -998,7 +989,7 @@
}
void test_convertToIsNot_wrong_not_noEnclosingParenthesis() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!p;
}
@@ -1007,7 +998,7 @@
}
void test_convertToIsNot_wrong_not_notIsExpression() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
!(p == null);
}
@@ -1017,7 +1008,7 @@
void test_convertToIsNot_wrong_not_notTheNotOperator() {
verifyNoTestUnitErrors = false;
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
++(p is String);
}
@@ -1026,7 +1017,7 @@
}
void test_convertToIsNotEmpty_OK_on_isEmpty() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(String str) {
!str.isEmpty;
}
@@ -1039,7 +1030,7 @@
}
void test_convertToIsNotEmpty_OK_on_str() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(String str) {
!str.isEmpty;
}
@@ -1052,7 +1043,7 @@
}
void test_convertToIsNotEmpty_OK_propertyAccess() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(String str) {
!'text'.isEmpty;
}
@@ -1065,7 +1056,7 @@
}
void test_convertToIsNotEmpty_wrong_notInPrefixExpression() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(String str) {
str.isEmpty;
}
@@ -1074,7 +1065,7 @@
}
void test_convertToIsNotEmpty_wrong_notIsEmpty() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(int p) {
!p.isEven;
}
@@ -1083,7 +1074,7 @@
}
void test_convertToIsNotEmpty_wrote_noIsNotEmpty() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
bool get isEmpty => false;
}
@@ -1102,7 +1093,7 @@
'>=': '<='
};
operatorMap.forEach((initialOperator, resultOperator) {
- _indexTestUnit('''
+ resolveTestUnit('''
bool main(int a, int b) {
return a $initialOperator b;
}
@@ -1116,7 +1107,7 @@
}
void test_exchangeBinaryExpressionArguments_OK_extended_mixOperator_1() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 * 2 * 3 + 4;
}
@@ -1129,7 +1120,7 @@
}
void test_exchangeBinaryExpressionArguments_OK_extended_mixOperator_2() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 + 2 - 3 + 4;
}
@@ -1143,7 +1134,7 @@
void
test_exchangeBinaryExpressionArguments_OK_extended_sameOperator_afterFirst() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 + 2 + 3;
}
@@ -1157,7 +1148,7 @@
void
test_exchangeBinaryExpressionArguments_OK_extended_sameOperator_afterSecond() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 + 2 + 3;
}
@@ -1170,7 +1161,7 @@
}
void test_exchangeBinaryExpressionArguments_OK_simple_afterOperator() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 + 2;
}
@@ -1183,7 +1174,7 @@
}
void test_exchangeBinaryExpressionArguments_OK_simple_beforeOperator() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 + 2;
}
@@ -1196,7 +1187,7 @@
}
void test_exchangeBinaryExpressionArguments_OK_simple_fullSelection() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 + 2;
}
@@ -1210,7 +1201,7 @@
}
void test_exchangeBinaryExpressionArguments_OK_simple_withLength() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 + 2;
}
@@ -1224,7 +1215,7 @@
}
void test_exchangeBinaryExpressionArguments_wrong_extraLength() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
111 + 222;
}
@@ -1234,7 +1225,7 @@
}
void test_exchangeBinaryExpressionArguments_wrong_onOperand() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
111 + 222;
}
@@ -1244,7 +1235,7 @@
}
void test_exchangeBinaryExpressionArguments_wrong_selectionWithBinary() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
1 + 2 + 3;
}
@@ -1254,7 +1245,7 @@
}
void test_importAddShow_BAD_hasShow() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:math' show PI;
main() {
PI;
@@ -1264,21 +1255,21 @@
}
void test_importAddShow_BAD_unresolvedUri() {
- _indexTestUnit('''
+ resolveTestUnit('''
import '/no/such/lib.dart';
''');
assertNoAssistAt('import ', AssistKind.IMPORT_ADD_SHOW);
}
void test_importAddShow_BAD_unused() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:math';
''');
assertNoAssistAt('import ', AssistKind.IMPORT_ADD_SHOW);
}
void test_importAddShow_OK_hasUnresolvedIdentifier() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:math';
main(x) {
PI;
@@ -1295,7 +1286,7 @@
}
void test_importAddShow_OK_onDirective() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:math';
main() {
PI;
@@ -1314,7 +1305,7 @@
}
void test_importAddShow_OK_onUri() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:math';
main() {
PI;
@@ -1333,7 +1324,7 @@
}
void test_introduceLocalTestedType_BAD_notBlock() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
if (p is String)
print('not a block');
@@ -1343,7 +1334,7 @@
}
void test_introduceLocalTestedType_BAD_notIsExpression() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
if (p == null) {
}
@@ -1353,7 +1344,7 @@
}
void test_introduceLocalTestedType_OK_if() {
- _indexTestUnit('''
+ resolveTestUnit('''
class MyTypeName {}
main(p) {
if (p is MyTypeName) {
@@ -1385,7 +1376,7 @@
}
void test_introduceLocalTestedType_OK_while() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
while (p is String) {
}
@@ -1411,13 +1402,13 @@
}
void test_invalidSelection() {
- _indexTestUnit('');
- List<Assist> assists = computeAssists(searchEngine, testUnit, -1, 0);
+ resolveTestUnit('');
+ List<Assist> assists = computeAssists(testUnit, -1, 0);
expect(assists, isEmpty);
}
void test_invertIfStatement_blocks() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (true) {
0;
@@ -1438,7 +1429,7 @@
}
void test_invertIfStatement_statements() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (true)
0;
@@ -1457,7 +1448,7 @@
}
void test_joinIfStatementInner_OK_conditionAndOr() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2 || 3 == 3) {
@@ -1476,7 +1467,7 @@
}
void test_joinIfStatementInner_OK_conditionInvocation() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (isCheck()) {
if (2 == 2) {
@@ -1497,7 +1488,7 @@
}
void test_joinIfStatementInner_OK_conditionOrAnd() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1 || 2 == 2) {
if (3 == 3) {
@@ -1516,7 +1507,7 @@
}
void test_joinIfStatementInner_OK_onCondition() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1535,7 +1526,7 @@
}
void test_joinIfStatementInner_OK_simpleConditions_block_block() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1554,7 +1545,7 @@
}
void test_joinIfStatementInner_OK_simpleConditions_block_single() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2)
@@ -1572,7 +1563,7 @@
}
void test_joinIfStatementInner_OK_simpleConditions_single_blockMulti() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1595,7 +1586,7 @@
}
void test_joinIfStatementInner_OK_simpleConditions_single_blockOne() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1)
if (2 == 2) {
@@ -1613,7 +1604,7 @@
}
void test_joinIfStatementInner_wrong_innerNotIf() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
print(0);
@@ -1624,7 +1615,7 @@
}
void test_joinIfStatementInner_wrong_innerWithElse() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1639,7 +1630,7 @@
}
void test_joinIfStatementInner_wrong_targetNotIf() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
print(0);
}
@@ -1648,7 +1639,7 @@
}
void test_joinIfStatementInner_wrong_targetWithElse() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1663,7 +1654,7 @@
}
void test_joinIfStatementOuter_OK_conditionAndOr() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2 || 3 == 3) {
@@ -1682,7 +1673,7 @@
}
void test_joinIfStatementOuter_OK_conditionInvocation() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (isCheck()) {
@@ -1703,7 +1694,7 @@
}
void test_joinIfStatementOuter_OK_conditionOrAnd() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1 || 2 == 2) {
if (3 == 3) {
@@ -1722,7 +1713,7 @@
}
void test_joinIfStatementOuter_OK_onCondition() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1741,7 +1732,7 @@
}
void test_joinIfStatementOuter_OK_simpleConditions_block_block() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1760,7 +1751,7 @@
}
void test_joinIfStatementOuter_OK_simpleConditions_block_single() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2)
@@ -1778,7 +1769,7 @@
}
void test_joinIfStatementOuter_OK_simpleConditions_single_blockMulti() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1801,7 +1792,7 @@
}
void test_joinIfStatementOuter_OK_simpleConditions_single_blockOne() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1)
if (2 == 2) {
@@ -1819,7 +1810,7 @@
}
void test_joinIfStatementOuter_wrong_outerNotIf() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
print(0);
@@ -1830,7 +1821,7 @@
}
void test_joinIfStatementOuter_wrong_outerWithElse() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1845,7 +1836,7 @@
}
void test_joinIfStatementOuter_wrong_targetNotIf() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
print(0);
}
@@ -1854,7 +1845,7 @@
}
void test_joinIfStatementOuter_wrong_targetWithElse() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1) {
if (2 == 2) {
@@ -1869,7 +1860,7 @@
}
void test_joinVariableDeclaration_onAssignment_OK() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
v = 1;
@@ -1883,7 +1874,7 @@
}
void test_joinVariableDeclaration_onAssignment_wrong_hasInitializer() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 1;
v = 2;
@@ -1893,7 +1884,7 @@
}
void test_joinVariableDeclaration_onAssignment_wrong_notAdjacent() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
var bar;
@@ -1904,7 +1895,7 @@
}
void test_joinVariableDeclaration_onAssignment_wrong_notAssignment() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
v += 1;
@@ -1914,7 +1905,7 @@
}
void test_joinVariableDeclaration_onAssignment_wrong_notDeclaration() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(var v) {
v = 1;
}
@@ -1923,7 +1914,7 @@
}
void test_joinVariableDeclaration_onAssignment_wrong_notLeftArgument() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
1 + v; // marker
@@ -1933,7 +1924,7 @@
}
void test_joinVariableDeclaration_onAssignment_wrong_notOneVariable() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v, v2;
v = 1;
@@ -1944,7 +1935,7 @@
void test_joinVariableDeclaration_onAssignment_wrong_notResolved() {
verifyNoTestUnitErrors = false;
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
x = 1;
@@ -1954,7 +1945,7 @@
}
void test_joinVariableDeclaration_onAssignment_wrong_notSameBlock() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
{
@@ -1966,7 +1957,7 @@
}
void test_joinVariableDeclaration_onDeclaration_OK_onName() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
v = 1;
@@ -1980,7 +1971,7 @@
}
void test_joinVariableDeclaration_onDeclaration_OK_onType() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int v;
v = 1;
@@ -1994,7 +1985,7 @@
}
void test_joinVariableDeclaration_onDeclaration_OK_onVar() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
v = 1;
@@ -2008,7 +1999,7 @@
}
void test_joinVariableDeclaration_onDeclaration_wrong_hasInitializer() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 1;
v = 2;
@@ -2018,7 +2009,7 @@
}
void test_joinVariableDeclaration_onDeclaration_wrong_lastStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (true)
var v;
@@ -2029,7 +2020,7 @@
void
test_joinVariableDeclaration_onDeclaration_wrong_nextNotAssignmentExpression() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
42;
@@ -2040,7 +2031,7 @@
void
test_joinVariableDeclaration_onDeclaration_wrong_nextNotExpressionStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
if (true) return;
@@ -2051,7 +2042,7 @@
void
test_joinVariableDeclaration_onDeclaration_wrong_nextNotPureAssignment() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
v += 1;
@@ -2061,7 +2052,7 @@
}
void test_joinVariableDeclaration_onDeclaration_wrong_notOneVariable() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v, v2;
v = 1;
@@ -2071,7 +2062,7 @@
}
void test_removeTypeAnnotation_classField_OK() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
int v = 1;
}
@@ -2084,7 +2075,7 @@
}
void test_removeTypeAnnotation_localVariable_OK() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int a = 1, b = 2;
}
@@ -2097,7 +2088,7 @@
}
void test_removeTypeAnnotation_topLevelVariable_OK() {
- _indexTestUnit('''
+ resolveTestUnit('''
int V = 1;
''');
assertHasAssistAt('int ', AssistKind.REMOVE_TYPE_ANNOTATION, '''
@@ -2106,7 +2097,7 @@
}
void test_replaceConditionalWithIfElse_OK_assignment() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v;
v = true ? 111 : 222;
@@ -2137,7 +2128,7 @@
}
void test_replaceConditionalWithIfElse_OK_return() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
return true ? 111 : 222;
}
@@ -2157,7 +2148,7 @@
}
void test_replaceConditionalWithIfElse_OK_variableDeclaration() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int a = 1, vvv = true ? 111 : 222, b = 2;
}
@@ -2175,14 +2166,14 @@
}
void test_replaceConditionalWithIfElse_wrong_noEnclosingStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
var v = true ? 111 : 222;
''');
assertNoAssistAt('? 111', AssistKind.REPLACE_CONDITIONAL_WITH_IF_ELSE);
}
void test_replaceConditionalWithIfElse_wrong_notConditional() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 42;
}
@@ -2191,7 +2182,7 @@
}
void test_replaceIfElseWithConditional_OK_assignment() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int vvv;
if (true) {
@@ -2213,7 +2204,7 @@
}
void test_replaceIfElseWithConditional_OK_return() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (true) {
return 111;
@@ -2233,7 +2224,7 @@
}
void test_replaceIfElseWithConditional_wrong_expressionVsReturn() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (true) {
print(42);
@@ -2246,7 +2237,7 @@
}
void test_replaceIfElseWithConditional_wrong_notIfStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
print(0);
}
@@ -2255,7 +2246,7 @@
}
void test_replaceIfElseWithConditional_wrong_notSingleStatememt() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int vvv;
if (true) {
@@ -2271,7 +2262,7 @@
}
void test_splitAndCondition_OK_innerAndExpression() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1 && 2 == 2 && 3 == 3) {
print(0);
@@ -2290,7 +2281,7 @@
}
void test_splitAndCondition_OK_thenBlock() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (true && false) {
print(0);
@@ -2315,7 +2306,7 @@
}
void test_splitAndCondition_OK_thenStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (true && false)
print(0);
@@ -2331,7 +2322,7 @@
}
void test_splitAndCondition_wrong() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1 && 2 == 2) {
print(0);
@@ -2349,7 +2340,7 @@
}
void test_splitAndCondition_wrong_hasElse() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1 && 2 == 2) {
print(1);
@@ -2362,7 +2353,7 @@
}
void test_splitAndCondition_wrong_notAnd() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (1 == 1 || 2 == 2) {
print(0);
@@ -2373,7 +2364,7 @@
}
void test_splitAndCondition_wrong_notPartOfIf() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
print(1 == 1 && 2 == 2);
}
@@ -2382,7 +2373,7 @@
}
void test_splitAndCondition_wrong_notTopLevelAnd() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (true || (1 == 1 && 2 == 2)) {
print(0);
@@ -2397,7 +2388,7 @@
}
void test_splitVariableDeclaration_OK_onName() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 1;
}
@@ -2411,7 +2402,7 @@
}
void test_splitVariableDeclaration_OK_onType() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int v = 1;
}
@@ -2425,7 +2416,7 @@
}
void test_splitVariableDeclaration_OK_onVar() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 1;
}
@@ -2439,7 +2430,7 @@
}
void test_splitVariableDeclaration_wrong_notOneVariable() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var v = 1, v2;
}
@@ -2448,7 +2439,7 @@
}
void test_surroundWith_block() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
// start
print(0);
@@ -2470,7 +2461,7 @@
}
void test_surroundWith_doWhile() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
// start
print(0);
@@ -2492,7 +2483,7 @@
}
void test_surroundWith_for() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
// start
print(0);
@@ -2514,7 +2505,7 @@
}
void test_surroundWith_forIn() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
// start
print(0);
@@ -2536,7 +2527,7 @@
}
void test_surroundWith_if() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
// start
print(0);
@@ -2558,7 +2549,7 @@
}
void test_surroundWith_tryCatch() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
// start
print(0);
@@ -2582,7 +2573,7 @@
}
void test_surroundWith_tryFinally() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
// start
print(0);
@@ -2606,7 +2597,7 @@
}
void test_surroundWith_while() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
// start
print(0);
@@ -2631,8 +2622,7 @@
* Computes assists and verifies that there is an assist of the given kind.
*/
Assist _assertHasAssist(AssistKind kind) {
- List<Assist> assists =
- computeAssists(searchEngine, testUnit, offset, length);
+ List<Assist> assists = computeAssists(testUnit, offset, length);
for (Assist assist in assists) {
if (assist.kind == kind) {
return assist;
@@ -2659,11 +2649,6 @@
return positions;
}
- void _indexTestUnit(String code) {
- resolveTestUnit(code);
- index.indexUnit(context, testUnit);
- }
-
void _setStartEndSelection() {
offset = findOffset('// start\n') + '// start\n'.length;
length = findOffset('// end') - offset;
diff --git a/pkg/analysis_server/test/services/correction/fix_test.dart b/pkg/analysis_server/test/services/correction/fix_test.dart
index 9e33386..feb88df 100644
--- a/pkg/analysis_server/test/services/correction/fix_test.dart
+++ b/pkg/analysis_server/test/services/correction/fix_test.dart
@@ -6,9 +6,6 @@
import 'package:analysis_server/src/protocol.dart' hide AnalysisError;
import 'package:analysis_server/src/services/correction/fix.dart';
-import 'package:analysis_server/src/services/index/index.dart';
-import 'package:analysis_server/src/services/index/local_memory_index.dart';
-import 'package:analysis_server/src/services/search/search_engine_internal.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/source/package_map_resolver.dart';
import 'package:analyzer/src/generated/error.dart';
@@ -32,9 +29,6 @@
@reflectiveTest
class FixProcessorTest extends AbstractSingleUnitTest {
- Index index;
- SearchEngineImpl searchEngine;
-
AnalysisErrorFilter errorFilter = null;
Fix fix;
@@ -42,7 +36,7 @@
String resultCode;
void assert_undefinedFunction_create_returnType_bool(String lineWithTest) {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
bool b = true;
$lineWithTest
@@ -73,7 +67,7 @@
void assertNoFix(FixKind kind) {
AnalysisError error = _findErrorToFix();
- List<Fix> fixes = computeFixes(searchEngine, testUnit, error);
+ List<Fix> fixes = computeFixes(testUnit, error);
for (Fix fix in fixes) {
if (fix.kind == kind) {
throw fail('Unexpected fix $kind in\n${fixes.join('\n')}');
@@ -103,13 +97,11 @@
void setUp() {
super.setUp();
- index = createLocalMemoryIndex();
- searchEngine = new SearchEngineImpl(index);
verifyNoTestUnitErrors = false;
}
void test_addSync_blockFunctionBody() {
- _indexTestUnit('''
+ resolveTestUnit('''
foo() {}
main() {
await foo();
@@ -121,14 +113,14 @@
{
AnalysisError error = errors[0];
expect(error.message, "Expected to find ';'");
- List<Fix> fixes = computeFixes(searchEngine, testUnit, error);
+ List<Fix> fixes = computeFixes(testUnit, error);
expect(fixes, isEmpty);
}
// Undefined name 'await'
{
AnalysisError error = errors[1];
expect(error.message, "Undefined name 'await'");
- List<Fix> fixes = computeFixes(searchEngine, testUnit, error);
+ List<Fix> fixes = computeFixes(testUnit, error);
// has exactly one fix
expect(fixes, hasLength(1));
Fix fix = fixes[0];
@@ -151,7 +143,7 @@
errorFilter = (AnalysisError error) {
return error.errorCode == StaticWarningCode.UNDEFINED_IDENTIFIER;
};
- _indexTestUnit('''
+ resolveTestUnit('''
foo() {}
main() => await foo();
''');
@@ -162,7 +154,7 @@
}
void test_boolean() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
boolean v;
}
@@ -175,7 +167,7 @@
}
void test_changeToStaticAccess_method() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
static foo() {}
}
@@ -194,7 +186,7 @@
}
void test_changeToStaticAccess_method_prefixLibrary() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:async' as pref;
main(pref.Future f) {
f.wait([]);
@@ -209,7 +201,7 @@
}
void test_changeToStaticAccess_property() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
static get foo => 42;
}
@@ -228,7 +220,7 @@
}
void test_createClass() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Test v = null;
}
@@ -245,7 +237,7 @@
}
void test_createConstructor_insteadOfSyntheticDefault() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
int field;
@@ -271,7 +263,7 @@
}
void test_createConstructor_named() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
method() {}
}
@@ -294,7 +286,7 @@
}
void test_createConstructorSuperExplicit() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
A(bool p1, int p2, double p3, String p4, {p5});
}
@@ -313,7 +305,7 @@
}
void test_createConstructorSuperExplicit_hasInitializers() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
A(int p);
}
@@ -334,7 +326,7 @@
}
void test_createConstructorSuperExplicit_named() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
A.named(int p);
}
@@ -353,7 +345,7 @@
}
void test_createConstructorSuperExplicit_named_private() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
A._named(int p);
}
@@ -365,7 +357,7 @@
}
void test_createConstructorSuperImplicit() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
A(p1, int p2, List<String> p3, [int p4]);
}
@@ -390,7 +382,7 @@
}
void test_createConstructorSuperImplicit_fieldInitializer() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
int _field;
A(this._field);
@@ -417,7 +409,7 @@
}
void test_createConstructorSuperImplicit_named() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
A.named(p1, int p2);
}
@@ -442,7 +434,7 @@
}
void test_createConstructorSuperImplicit_private() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
A._named(p);
}
@@ -453,7 +445,7 @@
}
void test_createField_BAD_inSDK() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(List p) {
p.foo = 1;
}
@@ -462,7 +454,7 @@
}
void test_createField_getter_multiLevel() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
class B {
@@ -492,7 +484,7 @@
}
void test_createField_getter_qualified_instance() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
main(A a) {
@@ -510,7 +502,7 @@
}
void test_createField_getter_qualified_instance_dynamicType() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
B b;
void f(Object p) {
@@ -534,7 +526,7 @@
}
void test_createField_getter_unqualified_instance_asInvocationArgument() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
f(test);
@@ -555,7 +547,7 @@
}
void test_createField_getter_unqualified_instance_assignmentRhs() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
int v = test;
@@ -574,7 +566,7 @@
}
void test_createField_getter_unqualified_instance_asStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
test;
@@ -593,7 +585,7 @@
}
void test_createField_setter_generic_BAD() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
class B<T> {
@@ -617,7 +609,7 @@
}
void test_createField_setter_generic_OK_local() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A<T> {
List<T> items;
@@ -640,7 +632,7 @@
}
void test_createField_setter_qualified_instance_hasField() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
int aaa;
int zzz;
@@ -667,7 +659,7 @@
}
void test_createField_setter_qualified_instance_hasMethod() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
existingMethod() {}
}
@@ -688,7 +680,7 @@
}
void test_createField_setter_qualified_static() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
main() {
@@ -706,7 +698,7 @@
}
void test_createField_setter_unqualified_instance() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
test = 5;
@@ -725,7 +717,7 @@
}
void test_createField_setter_unqualified_static() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
static main() {
test = 5;
@@ -745,7 +737,7 @@
void test_createFile_forImport() {
testFile = '/my/project/bin/test.dart';
- _indexTestUnit('''
+ resolveTestUnit('''
import 'my_file.dart';
''');
AnalysisError error = _findErrorToFix();
@@ -761,7 +753,7 @@
}
void test_createGetter_BAD_inSDK() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(List p) {
int v = p.foo;
}
@@ -770,7 +762,7 @@
}
void test_createGetter_multiLevel() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
class B {
@@ -800,7 +792,7 @@
}
void test_createGetter_qualified_instance() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
main(A a) {
@@ -818,7 +810,7 @@
}
void test_createGetter_qualified_instance_dynamicType() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
B b;
void f(Object p) {
@@ -842,7 +834,7 @@
}
void test_createGetter_setterContext() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
main(A a) {
@@ -853,7 +845,7 @@
}
void test_createGetter_unqualified_instance_asInvocationArgument() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
f(test);
@@ -874,7 +866,7 @@
}
void test_createGetter_unqualified_instance_assignmentLhs() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
test = 42;
@@ -885,7 +877,7 @@
}
void test_createGetter_unqualified_instance_assignmentRhs() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
int v = test;
@@ -904,7 +896,7 @@
}
void test_createGetter_unqualified_instance_asStatement() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
test;
@@ -923,7 +915,7 @@
}
void test_createLocalVariable_functionType_named() {
- _indexTestUnit('''
+ resolveTestUnit('''
typedef MY_FUNCTION(int p);
foo(MY_FUNCTION f) {}
main() {
@@ -941,7 +933,7 @@
}
void test_createLocalVariable_functionType_synthetic() {
- _indexTestUnit('''
+ resolveTestUnit('''
foo(f(int p)) {}
main() {
foo(bar);
@@ -951,7 +943,7 @@
}
void test_createLocalVariable_read_typeAssignment() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int a = test;
}
@@ -965,7 +957,7 @@
}
void test_createLocalVariable_read_typeCondition() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
if (!test) {
print(42);
@@ -983,7 +975,7 @@
}
void test_createLocalVariable_read_typeInvocationArgument() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
f(test);
}
@@ -999,7 +991,7 @@
}
void test_createLocalVariable_write_assignment() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
test = 42;
}
@@ -1012,7 +1004,7 @@
}
void test_createLocalVariable_write_assignment_compound() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
test += 42;
}
@@ -1026,7 +1018,7 @@
}
void test_createMissingOverrides_functionTypeAlias() {
- _indexTestUnit('''
+ resolveTestUnit('''
typedef int Binary(int left, int right);
abstract class Emulator {
@@ -1053,7 +1045,7 @@
}
void test_createMissingOverrides_functionTypedParameter() {
- _indexTestUnit('''
+ resolveTestUnit('''
abstract class A {
forEach(int f(double p1, String p2));
}
@@ -1076,7 +1068,7 @@
}
void test_createMissingOverrides_generics() {
- _indexTestUnit('''
+ resolveTestUnit('''
class Iterator<T> {
}
@@ -1104,7 +1096,7 @@
}
void test_createMissingOverrides_getter() {
- _indexTestUnit('''
+ resolveTestUnit('''
abstract class A {
get g1;
int get g2;
@@ -1132,7 +1124,7 @@
}
void test_createMissingOverrides_importPrefix() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:async' as aaa;
abstract class A {
Map<aaa.Future, List<aaa.Future>> g(aaa.Future p);
@@ -1157,7 +1149,7 @@
}
void test_createMissingOverrides_mergeToField_getterSetter() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
int ma;
void mb() {}
@@ -1188,7 +1180,7 @@
}
void test_createMissingOverrides_method() {
- _indexTestUnit('''
+ resolveTestUnit('''
abstract class A {
m1();
int m2();
@@ -1261,7 +1253,7 @@
}
void test_createMissingOverrides_operator() {
- _indexTestUnit('''
+ resolveTestUnit('''
abstract class A {
int operator [](int index);
void operator []=(int index, String value);
@@ -1291,7 +1283,7 @@
}
void test_createMissingOverrides_setter() {
- _indexTestUnit('''
+ resolveTestUnit('''
abstract class A {
set s1(x);
set s2(int x);
@@ -1328,7 +1320,7 @@
}
void test_createNoSuchMethod() {
- _indexTestUnit('''
+ resolveTestUnit('''
abstract class A {
m1();
int m2();
@@ -1353,7 +1345,7 @@
}
void test_creatGetter_location_afterLastGetter() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
int existingField;
@@ -1382,7 +1374,7 @@
}
void test_creationFunction_forFunctionType_cascadeSecond() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
B ma() => null;
}
@@ -1414,7 +1406,7 @@
}
void test_creationFunction_forFunctionType_coreFunction() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
useFunction(g: test);
}
@@ -1432,7 +1424,7 @@
}
void test_creationFunction_forFunctionType_dynamicArgument() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
useFunction(test);
}
@@ -1450,7 +1442,7 @@
}
void test_creationFunction_forFunctionType_function() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
useFunction(test);
}
@@ -1468,7 +1460,7 @@
}
void test_creationFunction_forFunctionType_function_namedArgument() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
useFunction(g: test);
}
@@ -1486,7 +1478,7 @@
}
void test_creationFunction_forFunctionType_method_enclosingClass_static() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
static foo() {
useFunction(test);
@@ -1508,7 +1500,7 @@
}
void test_creationFunction_forFunctionType_method_enclosingClass_static2() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
var f;
A() : f = useFunction(test);
@@ -1528,7 +1520,7 @@
}
void test_creationFunction_forFunctionType_method_targetClass() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(A a) {
useFunction(a.test);
}
@@ -1550,7 +1542,7 @@
void
test_creationFunction_forFunctionType_method_targetClass_hasOtherMember() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(A a) {
useFunction(a.test);
}
@@ -1574,7 +1566,7 @@
}
void test_creationFunction_forFunctionType_notFunctionType() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(A a) {
useFunction(a.test);
}
@@ -1586,7 +1578,7 @@
}
void test_creationFunction_forFunctionType_unknownTarget() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(A a) {
useFunction(a.test);
}
@@ -1598,7 +1590,7 @@
}
void test_expectedToken_semicolon() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
print(0)
}
@@ -1616,7 +1608,7 @@
class Test {}
''');
// try to find a fix
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Test test = null;
}
@@ -1632,7 +1624,7 @@
}
void test_importLibraryPrefix_withTopLevelVariable() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:math' as pref;
main() {
print(pref.E);
@@ -1649,7 +1641,7 @@
}
void test_importLibraryPrefix_withType() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:async' as pref;
main() {
pref.Stream s = null;
@@ -1670,7 +1662,7 @@
library lib;
myFunction() {}
''');
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
myFunction();
}
@@ -1690,7 +1682,7 @@
library lib;
myFunction() {}
''');
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
myFunction();
@@ -1714,7 +1706,7 @@
library lib;
int MY_VAR = 42;
''');
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
print(MY_VAR);
}
@@ -1736,7 +1728,7 @@
const Test(int p);
}
''');
- _indexTestUnit('''
+ resolveTestUnit('''
@Test(0)
main() {
}
@@ -1757,7 +1749,7 @@
library lib;
class Test {}
''');
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Test t = null;
}
@@ -1778,7 +1770,7 @@
library lib;
class Test {}
''');
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Test t = null;
}
@@ -1799,7 +1791,7 @@
library lib;
class Test {}
''');
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Test t = null;
}
@@ -1815,7 +1807,7 @@
}
void test_importLibrarySdk_withTopLevelVariable() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
print(PI);
}
@@ -1831,7 +1823,7 @@
}
void test_importLibrarySdk_withTopLevelVariable_annotation() {
- _indexTestUnit('''
+ resolveTestUnit('''
@PI
main() {
}
@@ -1847,7 +1839,7 @@
}
void test_importLibrarySdk_withType_AsExpression() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
p as Future;
}
@@ -1862,7 +1854,7 @@
}
void test_importLibrarySdk_withType_invocationTarget() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Future.wait(null);
}
@@ -1877,7 +1869,7 @@
}
void test_importLibrarySdk_withType_IsExpression() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
p is Future;
}
@@ -1892,7 +1884,7 @@
}
void test_importLibrarySdk_withType_typeAnnotation() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Future f = null;
}
@@ -1907,7 +1899,7 @@
}
void test_importLibrarySdk_withType_typeAnnotation_PrefixedIdentifier() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Future.wait;
}
@@ -1922,7 +1914,7 @@
}
void test_importLibrarySdk_withType_typeArgument() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
List<Future> futures = [];
}
@@ -1937,7 +1929,7 @@
}
void test_importLibraryShow() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:async' show Stream;
main() {
Stream s = null;
@@ -1954,7 +1946,7 @@
}
void test_isNotNull() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
p is! Null;
}
@@ -1967,7 +1959,7 @@
}
void test_isNull() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(p) {
p is Null;
}
@@ -1980,7 +1972,7 @@
}
void test_makeEnclosingClassAbstract_declaresAbstractMethod() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
m();
}
@@ -1993,7 +1985,7 @@
}
void test_makeEnclosingClassAbstract_inheritsAbstractMethod() {
- _indexTestUnit('''
+ resolveTestUnit('''
abstract class A {
m();
}
@@ -2010,7 +2002,7 @@
}
void test_removeParentheses_inGetterDeclaration() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
int get foo() => 0;
}
@@ -2023,7 +2015,7 @@
}
void test_removeParentheses_inGetterInvocation() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
int get foo => 0;
}
@@ -2042,7 +2034,7 @@
}
void test_removeUnnecessaryCast_assignment() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(Object p) {
if (p is String) {
String v = ((p as String));
@@ -2059,7 +2051,7 @@
}
void test_removeUnusedImport() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:math';
main() {
}
@@ -2071,7 +2063,7 @@
}
void test_removeUnusedImport_anotherImportOnLine() {
- _indexTestUnit('''
+ resolveTestUnit('''
import 'dart:math'; import 'dart:async';
main() {
@@ -2088,7 +2080,7 @@
}
void test_removeUnusedImport_severalLines() {
- _indexTestUnit('''
+ resolveTestUnit('''
import
'dart:math';
main() {
@@ -2103,7 +2095,7 @@
void test_replaceImportUri_inProject() {
testFile = '/project/bin/test.dart';
addSource('/project/foo/bar/lib.dart', '');
- _indexTestUnit('''
+ resolveTestUnit('''
import 'no/matter/lib.dart';
''');
performAllAnalysisTasks();
@@ -2114,7 +2106,7 @@
void test_replaceImportUri_package() {
_configureMyPkg('');
- _indexTestUnit('''
+ resolveTestUnit('''
import 'no/matter/my_lib.dart';
''');
performAllAnalysisTasks();
@@ -2127,7 +2119,7 @@
errorFilter = (AnalysisError error) {
return error.errorCode == ParserErrorCode.VAR_AS_TYPE_NAME;
};
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
Map<String, var> m;
}
@@ -2140,7 +2132,7 @@
}
void test_replaceWithConstInstanceCreation() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
const A();
}
@@ -2155,7 +2147,7 @@
}
void test_undefinedClass_useSimilar_fromImport() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
Stirng s = 'abc';
}
@@ -2168,7 +2160,7 @@
}
void test_undefinedClass_useSimilar_fromThisLibrary() {
- _indexTestUnit('''
+ resolveTestUnit('''
class MyClass {}
main() {
MyCalss v = null;
@@ -2182,8 +2174,42 @@
''');
}
+ void test_undefinedFunction_create_dynamicArgument() {
+ resolveTestUnit('''
+main() {
+ dynamic v;
+ test(v);
+}
+''');
+ assertHasFix(FixKind.CREATE_FUNCTION, '''
+main() {
+ dynamic v;
+ test(v);
+}
+
+void test(v) {
+}
+''');
+ }
+
+ void test_undefinedFunction_create_dynamicReturnType() {
+ resolveTestUnit('''
+main() {
+ dynamic v = test();
+}
+''');
+ assertHasFix(FixKind.CREATE_FUNCTION, '''
+main() {
+ dynamic v = test();
+}
+
+test() {
+}
+''');
+ }
+
void test_undefinedFunction_create_fromFunction() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int v = myUndefinedFunction(1, 2.0, '3');
}
@@ -2199,7 +2225,7 @@
}
void test_undefinedFunction_create_fromMethod() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
int v = myUndefinedFunction(1, 2.0, '3');
@@ -2219,7 +2245,7 @@
}
void test_undefinedFunction_create_generic_BAD() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A<T> {
Map<int, T> items;
main() {
@@ -2241,7 +2267,7 @@
}
void test_undefinedFunction_create_generic_OK() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
List<int> items;
main() {
@@ -2262,6 +2288,22 @@
''');
}
+ void test_undefinedFunction_create_nullArgument() {
+ resolveTestUnit('''
+main() {
+ test(null);
+}
+''');
+ assertHasFix(FixKind.CREATE_FUNCTION, '''
+main() {
+ test(null);
+}
+
+void test(arg0) {
+}
+''');
+ }
+
void test_undefinedFunction_create_returnType_bool_expressions() {
assert_undefinedFunction_create_returnType_bool("!test();");
assert_undefinedFunction_create_returnType_bool("b && test();");
@@ -2278,7 +2320,7 @@
}
void test_undefinedFunction_create_returnType_fromAssignment_eq() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int v;
v = myUndefinedFunction();
@@ -2296,7 +2338,7 @@
}
void test_undefinedFunction_create_returnType_fromAssignment_plusEq() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int v;
v += myUndefinedFunction();
@@ -2314,7 +2356,7 @@
}
void test_undefinedFunction_create_returnType_fromBinary_right() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
0 + myUndefinedFunction();
}
@@ -2330,7 +2372,7 @@
}
void test_undefinedFunction_create_returnType_fromInitializer() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
int v = myUndefinedFunction();
}
@@ -2346,7 +2388,7 @@
}
void test_undefinedFunction_create_returnType_fromInvocationArgument() {
- _indexTestUnit('''
+ resolveTestUnit('''
foo(int p) {}
main() {
foo( myUndefinedFunction() );
@@ -2364,7 +2406,7 @@
}
void test_undefinedFunction_create_returnType_fromReturn() {
- _indexTestUnit('''
+ resolveTestUnit('''
int main() {
return myUndefinedFunction();
}
@@ -2380,7 +2422,7 @@
}
void test_undefinedFunction_create_returnType_void() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
myUndefinedFunction();
}
@@ -2396,7 +2438,7 @@
}
void test_undefinedFunction_useSimilar_fromImport() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
pritn(0);
}
@@ -2409,7 +2451,7 @@
}
void test_undefinedFunction_useSimilar_thisLibrary() {
- _indexTestUnit('''
+ resolveTestUnit('''
myFunction() {}
main() {
myFuntcion();
@@ -2424,7 +2466,7 @@
}
void test_undefinedMethod_create_BAD_inSDK() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
List.foo();
}
@@ -2433,7 +2475,7 @@
}
void test_undefinedMethod_create_generic_BAD() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A<T> {
B b;
Map<int, T> items;
@@ -2462,7 +2504,7 @@
}
void test_undefinedMethod_create_generic_OK_literal() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
B b;
List<int> items;
@@ -2491,7 +2533,7 @@
}
void test_undefinedMethod_create_generic_OK_local() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A<T> {
List<T> items;
main() {
@@ -2513,7 +2555,7 @@
}
void test_undefinedMethod_createQualified_fromClass() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
main() {
@@ -2532,7 +2574,7 @@
}
void test_undefinedMethod_createQualified_fromClass_hasOtherMember() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
foo() {}
}
@@ -2554,7 +2596,7 @@
}
void test_undefinedMethod_createQualified_fromInstance() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
main(A a) {
@@ -2573,7 +2615,7 @@
}
void test_undefinedMethod_createQualified_targetIsFunctionType() {
- _indexTestUnit('''
+ resolveTestUnit('''
typedef A();
main() {
A.myUndefinedMethod();
@@ -2583,7 +2625,7 @@
}
void test_undefinedMethod_createQualified_targetIsUnresolved() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
NoSuchClass.myUndefinedMethod();
}
@@ -2592,7 +2634,7 @@
}
void test_undefinedMethod_createUnqualified_parameters() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
myUndefinedMethod(0, 1.0, '3');
@@ -2641,7 +2683,7 @@
}
void test_undefinedMethod_createUnqualified_returnType() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
main() {
int v = myUndefinedMethod();
@@ -2666,7 +2708,7 @@
}
void test_undefinedMethod_createUnqualified_staticFromField() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
static var f = myUndefinedMethod();
}
@@ -2682,7 +2724,7 @@
}
void test_undefinedMethod_createUnqualified_staticFromMethod() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
static main() {
myUndefinedMethod();
@@ -2702,7 +2744,7 @@
}
void test_undefinedMethod_hint_createQualified_fromInstance() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
}
main() {
@@ -2723,7 +2765,7 @@
}
void test_undefinedMethod_useSimilar_ignoreOperators() {
- _indexTestUnit('''
+ resolveTestUnit('''
main(Object object) {
object.then();
}
@@ -2732,7 +2774,7 @@
}
void test_undefinedMethod_useSimilar_qualified() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
myMethod() {}
}
@@ -2753,7 +2795,7 @@
}
void test_undefinedMethod_useSimilar_unqualified_superClass() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
myMethod() {}
}
@@ -2776,7 +2818,7 @@
}
void test_undefinedMethod_useSimilar_unqualified_thisClass() {
- _indexTestUnit('''
+ resolveTestUnit('''
class A {
myMethod() {}
main() {
@@ -2795,7 +2837,7 @@
}
void test_useEffectiveIntegerDivision() {
- _indexTestUnit('''
+ resolveTestUnit('''
main() {
var a = 5;
var b = 2;
@@ -2815,7 +2857,7 @@
* Computes fixes and verifies that there is a fix of the given kind.
*/
Fix _assertHasFix(FixKind kind, AnalysisError error) {
- List<Fix> fixes = computeFixes(searchEngine, testUnit, error);
+ List<Fix> fixes = computeFixes(testUnit, error);
for (Fix fix in fixes) {
if (fix.kind == kind) {
return fix;
@@ -2872,9 +2914,4 @@
}
return positions;
}
-
- void _indexTestUnit(String code) {
- resolveTestUnit(code);
- index.indexUnit(context, testUnit);
- }
}
diff --git a/pkg/analysis_server/test/services/index/dart_index_contributor_test.dart b/pkg/analysis_server/test/services/index/dart_index_contributor_test.dart
index 9d2dacc..eb56ce8 100644
--- a/pkg/analysis_server/test/services/index/dart_index_contributor_test.dart
+++ b/pkg/analysis_server/test/services/index/dart_index_contributor_test.dart
@@ -164,29 +164,6 @@
_expectedLocation(mainElement, 'v in []'));
}
- void test_isDefinedBy_ConstructorElement() {
- _indexTestUnit('''
-class A {
- A() {}
- A.foo() {}
-}''');
- // prepare elements
- ClassElement classA = findElement("A");
- ConstructorElement consA =
- findNodeElementAtString("A()", (node) => node is ConstructorDeclaration);
- ConstructorElement consA_foo =
- findNodeElementAtString("A.foo()", (node) => node is ConstructorDeclaration);
- // verify
- _assertRecordedRelation(
- consA,
- IndexConstants.NAME_IS_DEFINED_BY,
- _expectedLocation(classA, '() {}'));
- _assertRecordedRelation(
- consA_foo,
- IndexConstants.NAME_IS_DEFINED_BY,
- _expectedLocation(classA, '.foo() {}', length: 4));
- }
-
void test_isDefinedBy_NameElement_method() {
_indexTestUnit('''
class A {
@@ -815,75 +792,50 @@
_expectedLocation(constructorA, '.bar();', length: 4));
}
- void test_isReferencedBy_ConstructorFieldInitializer() {
- _indexTestUnit('''
-class A {
- int field;
- A() : field = 5;
-}
-''');
- // prepare elements
- ConstructorElement constructorElement =
- findNodeElementAtString("A()", (node) => node is ConstructorDeclaration);
- FieldElement fieldElement = findElement("field");
- // verify
- _assertRecordedRelation(
- fieldElement,
- IndexConstants.IS_REFERENCED_BY,
- _expectedLocation(constructorElement, 'field = 5'));
- }
-
void test_isReferencedBy_FieldElement() {
_indexTestUnit('''
class A {
var field;
- main() {
- this.field = 5; // q
- print(this.field); // q
- field = 5; // nq
+ A({this.field});
+ m() {
+ field = 1; // nq
print(field); // nq
}
}
+main(A a) {
+ a.field = 2; // q
+ print(a.field); // q
+ new A(field: 3);
+}
''');
// prepare elements
+ Element mElement = findElement("m");
Element mainElement = findElement("main");
FieldElement fieldElement = findElement("field");
PropertyAccessorElement getter = fieldElement.getter;
PropertyAccessorElement setter = fieldElement.setter;
- // verify
+ // m()
_assertRecordedRelation(
setter,
IndexConstants.IS_REFERENCED_BY,
- _expectedLocationQ(mainElement, 'field = 5; // q'));
+ _expectedLocation(mElement, 'field = 1; // nq'));
+ _assertRecordedRelation(
+ getter,
+ IndexConstants.IS_REFERENCED_BY,
+ _expectedLocation(mElement, 'field); // nq'));
+ // main()
+ _assertRecordedRelation(
+ setter,
+ IndexConstants.IS_REFERENCED_BY,
+ _expectedLocationQ(mainElement, 'field = 2; // q'));
_assertRecordedRelation(
getter,
IndexConstants.IS_REFERENCED_BY,
_expectedLocationQ(mainElement, 'field); // q'));
_assertRecordedRelation(
- setter,
- IndexConstants.IS_REFERENCED_BY,
- _expectedLocation(mainElement, 'field = 5; // nq'));
- _assertRecordedRelation(
- getter,
- IndexConstants.IS_REFERENCED_BY,
- _expectedLocation(mainElement, 'field); // nq'));
- }
-
- void test_isReferencedBy_FieldFormalParameterElement() {
- _indexTestUnit('''
-class A {
- int field;
- A(this.field);
-}
-''');
- // prepare elements
- FieldElement fieldElement = findElement("field");
- Element fieldParameterElement = findNodeElementAtString("field);");
- // verify
- _assertRecordedRelation(
fieldElement,
IndexConstants.IS_REFERENCED_BY,
- _expectedLocation(fieldParameterElement, 'field);'));
+ _expectedLocation(mainElement, 'field: 3'));
}
void test_isReferencedBy_FunctionElement() {
@@ -1326,6 +1278,41 @@
_expectedLocation(variableElement, 'T v'));
}
+ void test_isWrittenBy_ConstructorFieldInitializer() {
+ _indexTestUnit('''
+class A {
+ int field;
+ A() : field = 5;
+}
+''');
+ // prepare elements
+ ClassElement classElement = findElement('A');
+ ConstructorElement constructorElement = classElement.constructors[0];
+ FieldElement fieldElement = findElement("field");
+ // verify
+ _assertRecordedRelation(
+ fieldElement,
+ IndexConstants.IS_WRITTEN_BY,
+ _expectedLocation(constructorElement, 'field = 5'));
+ }
+
+ void test_isWrittenBy_FieldElement_fieldFormalParameter() {
+ _indexTestUnit('''
+class A {
+ int field;
+ A(this.field);
+}
+''');
+ // prepare elements
+ FieldElement fieldElement = findElement("field");
+ Element fieldParameterElement = findNodeElementAtString("field);");
+ // verify
+ _assertRecordedRelation(
+ fieldElement,
+ IndexConstants.IS_WRITTEN_BY,
+ _expectedLocation(fieldParameterElement, 'field);'));
+ }
+
void test_isWrittenBy_ParameterElement() {
_indexTestUnit('''
main(var p) {
diff --git a/pkg/analysis_server/test/services/refactoring/convert_method_to_getter_test.dart b/pkg/analysis_server/test/services/refactoring/convert_method_to_getter_test.dart
index 32780d8..eea5385 100644
--- a/pkg/analysis_server/test/services/refactoring/convert_method_to_getter_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/convert_method_to_getter_test.dart
@@ -148,6 +148,15 @@
'Only methods without parameters can be converted to getters.');
}
+ test_checkInitialConditions_returnTypeVoid() {
+ indexTestUnit('''
+void test() {}
+''');
+ _createRefactoring('test');
+ // check conditions
+ _assertInitialConditions_fatal('Cannot convert function returning void.');
+ }
+
test_checkInitialConditions_localFunction() {
indexTestUnit('''
main() {
diff --git a/pkg/analysis_server/test/services/refactoring/rename_local_test.dart b/pkg/analysis_server/test/services/refactoring/rename_local_test.dart
index 92c67d9..89b34f6 100644
--- a/pkg/analysis_server/test/services/refactoring/rename_local_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/rename_local_test.dart
@@ -5,19 +5,17 @@
library test.services.refactoring.rename_local;
import 'package:analysis_server/src/protocol.dart';
+import 'package:analysis_server/src/services/correction/status.dart';
import 'package:unittest/unittest.dart';
import '../../reflective_tests.dart';
import 'abstract_rename.dart';
-import 'package:analysis_server/src/services/correction/status.dart';
-
main() {
groupSep = ' | ';
runReflectiveTests(RenameLocalTest);
}
-
@reflectiveTest
class RenameLocalTest extends RenameRefactoringTest {
test_checkFinalConditions_hasLocalFunction_after() async {
@@ -147,6 +145,31 @@
expectedContextSearch: 'newName);');
}
+ test_checkFinalConditions_shadows_classMember_namedParameter() async {
+ indexTestUnit('''
+class A {
+ foo({test: 1}) {
+ }
+}
+class B extends A {
+ var newName = 1;
+ foo({test: 2}) {
+ print(newName);
+ }
+}
+''');
+ createRenameRefactoringAtString('test: 1}');
+ // check status
+ refactoring.newName = 'newName';
+ RefactoringStatus status = await refactoring.checkFinalConditions();
+ assertRefactoringStatus(
+ status,
+ RefactoringProblemSeverity.ERROR,
+ expectedMessage: 'Usage of field "B.newName" declared in "test.dart" '
+ 'will be shadowed by renamed parameter.',
+ expectedContextSearch: 'newName);');
+ }
+
test_checkFinalConditions_shadows_classMemberOK_qualifiedReference() {
indexTestUnit('''
class A {
@@ -411,7 +434,7 @@
''');
}
- test_createChange_parameter_namedInOtherFile() async {
+ test_createChange_parameter_named_inOtherFile() async {
indexTestUnit('''
class A {
A({test});
@@ -441,6 +464,66 @@
''');
}
+ test_createChange_parameter_named_updateHierarchy() async {
+ indexUnit('/test2.dart', '''
+library test2;
+class A {
+ void foo({int test: 1}) {
+ print(test);
+ }
+}
+class B extends A {
+ void foo({int test: 2}) {
+ print(test);
+ }
+}
+''');
+ indexTestUnit('''
+import 'test2.dart';
+main() {
+ new A().foo(test: 10);
+ new B().foo(test: 20);
+ new C().foo(test: 30);
+}
+class C extends A {
+ void foo({int test: 3}) {
+ print(test);
+ }
+}
+''');
+ // configure refactoring
+ createRenameRefactoringAtString('test: 20');
+ expect(refactoring.refactoringName, 'Rename Parameter');
+ refactoring.newName = 'newName';
+ // validate change
+ await assertSuccessfulRefactoring('''
+import 'test2.dart';
+main() {
+ new A().foo(newName: 10);
+ new B().foo(newName: 20);
+ new C().foo(newName: 30);
+}
+class C extends A {
+ void foo({int newName: 3}) {
+ print(newName);
+ }
+}
+''');
+ assertFileChangeResult('/test2.dart', '''
+library test2;
+class A {
+ void foo({int newName: 1}) {
+ print(newName);
+ }
+}
+class B extends A {
+ void foo({int newName: 2}) {
+ print(newName);
+ }
+}
+''');
+ }
+
test_oldName() {
indexTestUnit('''
main() {
diff --git a/pkg/analysis_server/test/services/search/search_engine_test.dart b/pkg/analysis_server/test/services/search/search_engine_test.dart
index a46e524..804a62f 100644
--- a/pkg/analysis_server/test/services/search/search_engine_test.dart
+++ b/pkg/analysis_server/test/services/search/search_engine_test.dart
@@ -211,10 +211,8 @@
}
''');
ConstructorElement element = findElement('named');
- ClassElement elementA = findElement('A');
Element mainElement = findElement('main');
var expected = [
- _expectId(elementA, MatchKind.DECLARATION, '.named() {}', length: 6),
_expectId(mainElement, MatchKind.REFERENCE, '.named();', length: 6)];
return _verifyReferences(element, expected);
}
@@ -245,7 +243,7 @@
Element main = findElement('main');
Element fieldParameter = findElement('field', ElementKind.PARAMETER);
var expected = [
- _expectId(fieldParameter, MatchKind.REFERENCE, 'field}'),
+ _expectId(fieldParameter, MatchKind.WRITE, 'field}'),
_expectId(main, MatchKind.REFERENCE, 'field: 1'),
_expectId(main, MatchKind.READ, 'field); // ref-nq'),
_expectIdQ(main, MatchKind.READ, 'field); // ref-q'),
diff --git a/pkg/analysis_server/tool/spec/spec_input.html b/pkg/analysis_server/tool/spec/spec_input.html
index 65854bb..9d5ade1 100644
--- a/pkg/analysis_server/tool/spec/spec_input.html
+++ b/pkg/analysis_server/tool/spec/spec_input.html
@@ -168,6 +168,16 @@
</ul>
</dd>
</dl>
+ <dl>
+ <dt>--no-index</dt>
+ <dd>
+ Disable the server from generating an index. If this flag is passed and an
+ API is used that requires an index, then an error, <tt>NO_INDEX_GENERATED</tt>,
+ will be thrown. The set of API calls that require an index include:
+ refactoring calls, code completions and searching.
+ <!-- TODO(jwren/scheglov): make sure that this of APIs that is complete. -->
+ </dd>
+ </dl>
</blockquote>
<domain name="server">
<p>
@@ -2302,6 +2312,8 @@
<value><code>CLASS_TYPE_ALIAS</code></value>
<value><code>COMPILATION_UNIT</code></value>
<value><code>CONSTRUCTOR</code></value>
+ <value><code>ENUM</code></value>
+ <value><code>ENUM_CONSTANT</code></value>
<value><code>FIELD</code></value>
<value><code>FUNCTION</code></value>
<value><code>FUNCTION_TYPE_ALIAS</code></value>
@@ -3109,7 +3121,7 @@
<value>
<code>INVALID_OVERLAY_CHANGE</code>
<p>
- An analysis.updateContent request contained a
+ An "analysis.updateContent" request contained a
ChangeContentOverlay object which can't be applied, due
to an edit having an offset or length that is out of
range.
@@ -3128,6 +3140,13 @@
</p>
</value>
<value>
+ <code>NO_INDEX_GENERATED</code>
+ <p>
+ The "--no-index" flag was passed when the analysis server created,
+ but this API call requires an index to have been generated.
+ </p>
+ </value>
+ <value>
<code>REFACTORING_REQUEST_CANCELLED</code>
<p>
Another refactoring request was received during processing of
diff --git a/pkg/analyzer/bin/analyzer.dart b/pkg/analyzer/bin/analyzer.dart
index c40fdf7..447b386 100644
--- a/pkg/analyzer/bin/analyzer.dart
+++ b/pkg/analyzer/bin/analyzer.dart
@@ -17,6 +17,7 @@
import 'package:analyzer/src/generated/interner.dart';
import 'package:analyzer/src/generated/java_core.dart' show JavaSystem;
import 'package:analyzer/src/generated/java_engine.dart';
+import 'package:analyzer/src/generated/utilities_general.dart';
void main(List<String> args) {
StringUtilities.INTERNER = new MappedInterner();
@@ -70,7 +71,7 @@
analyzer.analyzeSync(printMode: 0);
}
- PerformanceStatistics.reset();
+ PerformanceTag.reset();
startTime = JavaSystem.currentTimeMillis();
analyzer = new AnalyzerImpl(sourcePath, options, startTime);
return analyzer.analyzeSync();
diff --git a/pkg/analyzer/lib/file_system/file_system.dart b/pkg/analyzer/lib/file_system/file_system.dart
index ff3e5ff..a53f0e6 100644
--- a/pkg/analyzer/lib/file_system/file_system.dart
+++ b/pkg/analyzer/lib/file_system/file_system.dart
@@ -16,6 +16,12 @@
*/
abstract class File extends Resource {
/**
+ * Return the last-modified stamp of the file.
+ * Throws [FileSystemException] if the file does not exist.
+ */
+ int get modificationStamp;
+
+ /**
* Create a new [Source] instance that serves this file.
*/
Source createSource([Uri uri]);
@@ -23,6 +29,19 @@
/**
+ * Base class for all file system exceptions.
+ */
+class FileSystemException implements Exception {
+ final String path;
+ final String message;
+
+ FileSystemException(this.path, this.message);
+
+ String toString() => 'FileSystemException(path=$path; message=$message)';
+}
+
+
+/**
* [Folder]s are [Resource]s which may contain files and/or other folders.
*/
abstract class Folder extends Resource {
diff --git a/pkg/analyzer/lib/file_system/memory_file_system.dart b/pkg/analyzer/lib/file_system/memory_file_system.dart
index b038f45eb..efb779c 100644
--- a/pkg/analyzer/lib/file_system/memory_file_system.dart
+++ b/pkg/analyzer/lib/file_system/memory_file_system.dart
@@ -16,22 +16,6 @@
/**
- * Exception thrown when a memory [Resource] file operation fails.
- */
-class MemoryResourceException {
- final path;
- final message;
-
- MemoryResourceException(this.path, this.message);
-
- @override
- String toString() {
- return "MemoryResourceException(path=$path; message=$message)";
- }
-}
-
-
-/**
* An in-memory implementation of [ResourceProvider].
* Use `/` as a path separator.
*/
@@ -159,15 +143,21 @@
@override
bool get exists => false;
- String get _content {
- throw new MemoryResourceException(path, "File '$path' could not be read");
+ int get modificationStamp {
+ int stamp = _provider._pathToTimestamp[path];
+ if (stamp == null) {
+ throw new FileSystemException(path, "File does not exist");
+ }
+ return stamp;
}
- int get _timestamp => _provider._pathToTimestamp[path];
+ String get _content {
+ throw new FileSystemException(path, 'File could not be read');
+ }
@override
Source createSource([Uri uri]) {
- throw new MemoryResourceException(path, "File '$path' could not be read");
+ throw new FileSystemException(path, 'File could not be read');
}
@override
@@ -184,16 +174,22 @@
_MemoryFile(MemoryResourceProvider provider, String path)
: super(provider, path);
+ int get modificationStamp {
+ int stamp = _provider._pathToTimestamp[path];
+ if (stamp == null) {
+ throw new FileSystemException(path, 'File does not exist.');
+ }
+ return stamp;
+ }
+
String get _content {
String content = _provider._pathToContent[path];
if (content == null) {
- throw new MemoryResourceException(path, "File '$path' does not exist");
+ throw new FileSystemException(path, "File does not exist");
}
return content;
}
- int get _timestamp => _provider._pathToTimestamp[path];
-
@override
Source createSource([Uri uri]) {
if (uri == null) {
@@ -239,7 +235,13 @@
bool get isInSystemLibrary => uriKind == UriKind.DART_URI;
@override
- int get modificationStamp => _file._timestamp;
+ int get modificationStamp {
+ try {
+ return _file.modificationStamp;
+ } on FileSystemException catch (e) {
+ return -1;
+ }
+ }
@override
String get shortName => _file.shortName;
diff --git a/pkg/analyzer/lib/file_system/physical_file_system.dart b/pkg/analyzer/lib/file_system/physical_file_system.dart
index 3f3e452..398e451 100644
--- a/pkg/analyzer/lib/file_system/physical_file_system.dart
+++ b/pkg/analyzer/lib/file_system/physical_file_system.dart
@@ -78,6 +78,16 @@
_PhysicalFile(io.File file) : super(file);
@override
+ int get modificationStamp {
+ try {
+ io.File file = _entry as io.File;
+ return file.lastModifiedSync().millisecondsSinceEpoch;
+ } on io.FileSystemException catch (exception) {
+ throw new FileSystemException(path, exception.message);
+ }
+ }
+
+ @override
Source createSource([Uri uri]) {
io.File file = _entry as io.File;
JavaFile javaFile = new JavaFile(file.absolute.path);
diff --git a/pkg/analyzer/lib/options.dart b/pkg/analyzer/lib/options.dart
index 50519dc..ef7a677 100644
--- a/pkg/analyzer/lib/options.dart
+++ b/pkg/analyzer/lib/options.dart
@@ -133,7 +133,7 @@
static CommandLineOptions _parse(List<String> args) {
args = args.expand((String arg) => arg.split('=')).toList();
- var parser = new _CommandLineParser()
+ var parser = new CommandLineParser()
..addFlag(
'batch',
abbr: 'b',
@@ -208,8 +208,7 @@
..addOption(
'url-mapping',
help: '--url-mapping=libraryUri,/path/to/library.dart directs the '
- 'analyzer to use "library.dart" as the source for an import '
- 'of "libraryUri"',
+ 'analyzer to use "library.dart" as the source for an import ' 'of "libraryUri"',
allowMultiple: true)
//
// Hidden flags.
@@ -282,7 +281,9 @@
customUrlMappings[splitMapping[0]] = splitMapping[1];
}
return new CommandLineOptions._fromArgs(
- results, definedVariables, customUrlMappings);
+ results,
+ definedVariables,
+ customUrlMappings);
} on FormatException catch (e) {
print(e.message);
_showUsage(parser);
@@ -305,17 +306,21 @@
* TODO(pquitslund): when the args package supports ignoring unrecognized
* options/flags, this class can be replaced with a simple [ArgParser] instance.
*/
-class _CommandLineParser {
+class CommandLineParser {
final List<String> _knownFlags;
+ final bool _alwaysIgnoreUnrecognized;
final ArgParser _parser;
/** Creates a new command line parser */
- _CommandLineParser()
+ CommandLineParser({bool alwaysIgnoreUnrecognized: false})
: _knownFlags = <String>[],
+ _alwaysIgnoreUnrecognized = alwaysIgnoreUnrecognized,
_parser = new ArgParser(allowTrailingOptions: true);
+ ArgParser get parser => _parser;
+
/**
* Defines a flag.
*
@@ -391,35 +396,46 @@
return remainingArgs;
}
- List<String> _filterUnknowns(args) {
+ List<String> _filterUnknowns(List<String> args) {
- // Only filter args if the ignore flag is specified.
- if (!args.contains('--ignore-unrecognized-flags')) {
- return args;
- }
- //TODO(pquitslund): replace w/ the following once library skew issues are
- // sorted out
- //return args.where((arg) => !arg.startsWith('--') ||
- // _knownFlags.contains(arg.substring(2)));
+ // Only filter args if the ignore flag is specified, or if
+ // _alwaysIgnoreUnrecognized was set to true
+ if (_alwaysIgnoreUnrecognized ||
+ args.contains('--ignore-unrecognized-flags')) {
- // Filter all unrecognized flags and options.
- var filtered = <String>[];
- for (var i = 0; i < args.length; ++i) {
- var arg = args[i];
- if (arg.startsWith('--') && arg.length > 2) {
- if (!_knownFlags.contains(arg.substring(2))) {
- print('remove: $arg');
- //"eat" params by advancing to the next flag/option
- i = _getNextFlagIndex(args, i);
+ //TODO(pquitslund): replace w/ the following once library skew issues are
+ // sorted out
+ //return args.where((arg) => !arg.startsWith('--') ||
+ // _knownFlags.contains(arg.substring(2)));
+
+ // Filter all unrecognized flags and options.
+ List<String> filtered = <String>[];
+ for (int i = 0; i < args.length; ++i) {
+ String arg = args[i];
+ if (arg.startsWith('--') && arg.length > 2) {
+ String option = arg.substring(2);
+ // strip the last '=value'
+ int equalsOffset = option.lastIndexOf('=');
+ if (equalsOffset != -1) {
+ option = option.substring(0, equalsOffset);
+ }
+ // check the option
+ if (!_knownFlags.contains(option)) {
+ //print('remove: $arg');
+ //"eat" params by advancing to the next flag/option
+ i = _getNextFlagIndex(args, i);
+ } else {
+ filtered.add(arg);
+ }
} else {
filtered.add(arg);
}
- } else {
- filtered.add(arg);
}
- }
- return filtered;
+ return filtered;
+ } else {
+ return args;
+ }
}
_getNextFlagIndex(args, i) {
diff --git a/pkg/analyzer/lib/source/package_map_resolver.dart b/pkg/analyzer/lib/source/package_map_resolver.dart
index 37de62a..80ce2e6 100644
--- a/pkg/analyzer/lib/source/package_map_resolver.dart
+++ b/pkg/analyzer/lib/source/package_map_resolver.dart
@@ -79,11 +79,15 @@
String sourcePath = source.fullName;
for (String pkgName in packageMap.keys) {
List<Folder> pkgFolders = packageMap[pkgName];
- for (Folder pkgFolder in pkgFolders) {
+ for (int i = 0; i < pkgFolders.length; i++) {
+ Folder pkgFolder = pkgFolders[i];
String pkgFolderPath = pkgFolder.path;
- if (sourcePath.startsWith(pkgFolderPath)) {
- String relPath = sourcePath.substring(pkgFolderPath.length);
- return Uri.parse('$PACKAGE_SCHEME:$pkgName$relPath');
+ // TODO(paulberry): figure out the right thing to do for Windows.
+ if (sourcePath.startsWith(pkgFolderPath + '/')) {
+ String relPath = sourcePath.substring(pkgFolderPath.length + 1);
+ if (_isReversibleTranslation(pkgFolders, i, relPath)) {
+ return Uri.parse('$PACKAGE_SCHEME:$pkgName/$relPath');
+ }
}
}
}
@@ -91,6 +95,29 @@
}
/**
+ * A translation from file path to package URI has just been found for
+ * using the [packageDirIndex]th element of [packageDirs], and appending the
+ * relative path [relPath]. Determine whether the translation is reversible;
+ * that is, whether translating the package URI pack to a file path will
+ * produce the file path we started with.
+ */
+ bool _isReversibleTranslation(List<Folder> packageDirs, int packageDirIndex,
+ String relPath) {
+ // The translation is reversible provided there is no prior element of
+ // [packageDirs] containing a file matching [relPath].
+ for (int i = 0; i < packageDirIndex; i++) {
+ Folder packageDir = packageDirs[i];
+ if (packageDir.exists) {
+ Resource result = packageDir.getChild(relPath);
+ if (result is File && result.exists) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
* Returns `true` if [uri] is a `package` URI.
*/
static bool isPackageUri(Uri uri) {
diff --git a/pkg/analyzer/lib/src/analyzer_impl.dart b/pkg/analyzer/lib/src/analyzer_impl.dart
index 09de9d7..f0cf30c 100644
--- a/pkg/analyzer/lib/src/analyzer_impl.dart
+++ b/pkg/analyzer/lib/src/analyzer_impl.dart
@@ -25,6 +25,7 @@
import 'generated/java_io.dart';
import 'generated/sdk_io.dart';
import 'generated/source_io.dart';
+import 'package:analyzer/src/generated/utilities_general.dart';
DirectoryBasedDartSdk sdk;
@@ -300,20 +301,15 @@
_printColdPerf() {
// print cold VM performance numbers
int totalTime = JavaSystem.currentTimeMillis() - startTime;
- int ioTime = PerformanceStatistics.io.result;
- int scanTime = PerformanceStatistics.scan.result;
- int parseTime = PerformanceStatistics.parse.result;
- int resolveTime = PerformanceStatistics.resolve.result;
- int errorsTime = PerformanceStatistics.errors.result;
- int hintsTime = PerformanceStatistics.hints.result;
- stdout.writeln("io-cold:$ioTime");
- stdout.writeln("scan-cold:$scanTime");
- stdout.writeln("parse-cold:$parseTime");
- stdout.writeln("resolve-cold:$resolveTime");
- stdout.writeln("errors-cold:$errorsTime");
- stdout.writeln("hints-cold:$hintsTime");
- stdout.writeln("other-cold:${totalTime
- - (ioTime + scanTime + parseTime + resolveTime + errorsTime + hintsTime)}");
+ int otherTime = totalTime;
+ for (PerformanceTag tag in PerformanceTag.all) {
+ if (tag != PerformanceTag.UNKNOWN) {
+ int tagTime = tag.elapsedMs;
+ stdout.writeln('${tag.label}-cold:$tagTime');
+ otherTime -= tagTime;
+ }
+ }
+ stdout.writeln('other-cold:$otherTime');
stdout.writeln("total-cold:$totalTime");
}
@@ -334,20 +330,15 @@
// print performance numbers
if (options.perf || options.warmPerf) {
int totalTime = JavaSystem.currentTimeMillis() - startTime;
- int ioTime = PerformanceStatistics.io.result;
- int scanTime = PerformanceStatistics.scan.result;
- int parseTime = PerformanceStatistics.parse.result;
- int resolveTime = PerformanceStatistics.resolve.result;
- int errorsTime = PerformanceStatistics.errors.result;
- int hintsTime = PerformanceStatistics.hints.result;
- stdout.writeln("io:$ioTime");
- stdout.writeln("scan:$scanTime");
- stdout.writeln("parse:$parseTime");
- stdout.writeln("resolve:$resolveTime");
- stdout.writeln("errors:$errorsTime");
- stdout.writeln("hints:$hintsTime");
- stdout.writeln("other:${totalTime
- - (ioTime + scanTime + parseTime + resolveTime + errorsTime + hintsTime)}");
+ int otherTime = totalTime;
+ for (PerformanceTag tag in PerformanceTag.all) {
+ if (tag != PerformanceTag.UNKNOWN) {
+ int tagTime = tag.elapsedMs;
+ stdout.writeln('${tag.label}:$tagTime');
+ otherTime -= tagTime;
+ }
+ }
+ stdout.writeln('other:$otherTime');
stdout.writeln("total:$totalTime");
}
}
diff --git a/pkg/analyzer/lib/src/generated/ast.dart b/pkg/analyzer/lib/src/generated/ast.dart
index 9f83af4..277af7f 100644
--- a/pkg/analyzer/lib/src/generated/ast.dart
+++ b/pkg/analyzer/lib/src/generated/ast.dart
@@ -21,16 +21,15 @@
import 'utilities_dart.dart';
/**
- * Instances of the class `AdjacentStrings` represents two or more string literals that are
- * implicitly concatenated because of being adjacent (separated only by whitespace).
+ * Two or more string literals that are implicitly concatenated because of being
+ * adjacent (separated only by whitespace).
*
- * While the grammar only allows adjacent strings when all of the strings are of the same kind
- * (single line or multi-line), this class doesn't enforce that restriction.
+ * While the grammar only allows adjacent strings when all of the strings are of
+ * the same kind (single line or multi-line), this class doesn't enforce that
+ * restriction.
*
- * <pre>
- * adjacentStrings ::=
- * [StringLiteral] [StringLiteral]+
- * </pre>
+ * > adjacentStrings ::=
+ * > [StringLiteral] [StringLiteral]+
*/
class AdjacentStrings extends StringLiteral {
/**
@@ -39,9 +38,8 @@
NodeList<StringLiteral> _strings;
/**
- * Initialize a newly created list of adjacent strings.
- *
- * @param strings the strings that are implicitly concatenated
+ * Initialize a newly created list of adjacent strings. To be syntactically
+ * valid, the list of [strings] must contain at least two elements.
*/
AdjacentStrings(List<StringLiteral> strings) {
_strings = new NodeList<StringLiteral>(this, strings);
@@ -58,8 +56,6 @@
/**
* Return the strings that are implicitly concatenated.
- *
- * @return the strings that are implicitly concatenated
*/
NodeList<StringLiteral> get strings => _strings;
@@ -80,13 +76,13 @@
}
/**
- * The abstract class `AnnotatedNode` defines the behavior of nodes that can be annotated with
- * both a comment and metadata.
+ * An AST node that can be annotated with both a documentation comment and a
+ * list of annotations.
*/
abstract class AnnotatedNode extends AstNode {
/**
- * The documentation comment associated with this node, or `null` if this node does not have
- * a documentation comment associated with it.
+ * The documentation comment associated with this node, or `null` if this node
+ * does not have a documentation comment associated with it.
*/
Comment _comment;
@@ -96,10 +92,9 @@
NodeList<Annotation> _metadata;
/**
- * Initialize a newly created node.
- *
- * @param comment the documentation comment associated with this node
- * @param metadata the annotations associated with this node
+ * Initialize a newly created annotated node. Either or both of the [comment]
+ * and [metadata] can be `null` if the node does not have the corresponding
+ * attribute.
*/
AnnotatedNode(Comment comment, List<Annotation> metadata) {
_comment = becomeParentOf(comment);
@@ -125,17 +120,14 @@
}
/**
- * Return the documentation comment associated with this node, or `null` if this node does
- * not have a documentation comment associated with it.
- *
- * @return the documentation comment associated with this node
+ * Return the documentation comment associated with this node, or `null` if
+ * this node does not have a documentation comment associated with it.
*/
Comment get documentationComment => _comment;
/**
- * Set the documentation comment associated with this node to the given comment.
- *
- * @param comment the documentation comment to be associated with this node
+ * Set the documentation comment associated with this node to the given
+ * [comment].
*/
void set documentationComment(Comment comment) {
_comment = becomeParentOf(comment);
@@ -143,22 +135,16 @@
/**
* Return the first token following the comment and metadata.
- *
- * @return the first token following the comment and metadata
*/
Token get firstTokenAfterCommentAndMetadata;
/**
* Return the annotations associated with this node.
- *
- * @return the annotations associated with this node
*/
NodeList<Annotation> get metadata => _metadata;
/**
- * Set the metadata associated with this node to the given metadata.
- *
- * @param metadata the metadata to be associated with this node
+ * Set the metadata associated with this node to the given [metadata].
*/
void set metadata(List<Annotation> metadata) {
_metadata.clear();
@@ -166,11 +152,8 @@
}
/**
- * Return an array containing the comment and annotations associated with this node, sorted in
- * lexical order.
- *
- * @return the comment and annotations associated with this node in the order in which they
- * appeared in the original source
+ * Return a list containing the comment and annotations associated with this
+ * node, sorted in lexical order.
*/
List<AstNode> get sortedCommentAndAnnotations {
return <AstNode>[]
@@ -194,7 +177,7 @@
@override
void visitChildren(AstVisitor visitor) {
if (_commentIsBeforeAnnotations()) {
- safelyVisitChild(_comment, visitor);
+ _safelyVisitChild(_comment, visitor);
_metadata.accept(visitor);
} else {
for (AstNode child in sortedCommentAndAnnotations) {
@@ -205,8 +188,6 @@
/**
* Return `true` if the comment is lexically before any annotations.
- *
- * @return `true` if the comment is lexically before any annotations
*/
bool _commentIsBeforeAnnotations() {
if (_comment == null || _metadata.isEmpty) {
@@ -218,16 +199,13 @@
}
/**
- * Instances of the class `Annotation` represent an annotation that can be associated with an
- * AST node.
+ * An annotation that can be associated with an AST node.
*
- * <pre>
- * metadata ::=
- * annotation*
- *
- * annotation ::=
- * '@' [Identifier] ('.' [SimpleIdentifier])? [ArgumentList]?
- * </pre>
+ * > metadata ::=
+ * > annotation*
+ * >
+ * > annotation ::=
+ * > '@' [Identifier] ('.' [SimpleIdentifier])? [ArgumentList]?
*/
class Annotation extends AstNode {
/**
@@ -236,32 +214,32 @@
Token atSign;
/**
- * The name of the class defining the constructor that is being invoked or the name of the field
- * that is being referenced.
+ * The name of the class defining the constructor that is being invoked or the
+ * name of the field that is being referenced.
*/
Identifier _name;
/**
- * The period before the constructor name, or `null` if this annotation is not the
- * invocation of a named constructor.
+ * The period before the constructor name, or `null` if this annotation is not
+ * the invocation of a named constructor.
*/
Token period;
/**
- * The name of the constructor being invoked, or `null` if this annotation is not the
- * invocation of a named constructor.
+ * The name of the constructor being invoked, or `null` if this annotation is
+ * not the invocation of a named constructor.
*/
SimpleIdentifier _constructorName;
/**
- * The arguments to the constructor being invoked, or `null` if this annotation is not the
- * invocation of a constructor.
+ * The arguments to the constructor being invoked, or `null` if this
+ * annotation is not the invocation of a constructor.
*/
ArgumentList _arguments;
/**
- * The element associated with this annotation, or `null` if the AST structure has not been
- * resolved or if this annotation could not be resolved.
+ * The element associated with this annotation, or `null` if the AST structure
+ * has not been resolved or if this annotation could not be resolved.
*/
Element _element;
@@ -271,17 +249,10 @@
ElementAnnotation elementAnnotation;
/**
- * Initialize a newly created annotation.
- *
- * @param atSign the at sign that introduced the annotation
- * @param name the name of the class defining the constructor that is being invoked or the name of
- * the field that is being referenced
- * @param period the period before the constructor name, or `null` if this annotation is not
- * the invocation of a named constructor
- * @param constructorName the name of the constructor being invoked, or `null` if this
- * annotation is not the invocation of a named constructor
- * @param arguments the arguments to the constructor being invoked, or `null` if this
- * annotation is not the invocation of a constructor
+ * Initialize a newly created annotation. Both the [period] and the
+ * [constructorName] can be `null` if the annotation is not referencing a
+ * named constructor. The [arguments] can be `null` if the annotation is not
+ * referencing a constructor.
*/
Annotation(this.atSign, Identifier name, this.period,
SimpleIdentifier constructorName, ArgumentList arguments) {
@@ -291,17 +262,13 @@
}
/**
- * Return the arguments to the constructor being invoked, or `null` if this annotation is
- * not the invocation of a constructor.
- *
- * @return the arguments to the constructor being invoked
+ * Return the arguments to the constructor being invoked, or `null` if this
+ * annotation is not the invocation of a constructor.
*/
ArgumentList get arguments => _arguments;
/**
* Set the arguments to the constructor being invoked to the given arguments.
- *
- * @param arguments the arguments to the constructor being invoked
*/
void set arguments(ArgumentList arguments) {
_arguments = becomeParentOf(arguments);
@@ -319,27 +286,22 @@
..add(_arguments);
/**
- * Return the name of the constructor being invoked, or `null` if this annotation is not the
- * invocation of a named constructor.
- *
- * @return the name of the constructor being invoked
+ * Return the name of the constructor being invoked, or `null` if this
+ * annotation is not the invocation of a named constructor.
*/
SimpleIdentifier get constructorName => _constructorName;
/**
- * Set the name of the constructor being invoked to the given name.
- *
- * @param constructorName the name of the constructor being invoked
+ * Set the name of the constructor being invoked to the given [name].
*/
- void set constructorName(SimpleIdentifier constructorName) {
- _constructorName = becomeParentOf(constructorName);
+ void set constructorName(SimpleIdentifier name) {
+ _constructorName = becomeParentOf(name);
}
/**
- * Return the element associated with this annotation, or `null` if the AST structure has
- * not been resolved or if this annotation could not be resolved.
- *
- * @return the element associated with this annotation
+ * Return the element associated with this annotation, or `null` if the AST
+ * structure has not been resolved or if this annotation could not be
+ * resolved.
*/
Element get element {
if (_element != null) {
@@ -351,9 +313,7 @@
}
/**
- * Set the element associated with this annotation based.
- *
- * @param element the element to be associated with this identifier
+ * Set the element associated with this annotation to the given [element].
*/
void set element(Element element) {
_element = element;
@@ -370,18 +330,14 @@
}
/**
- * Return the name of the class defining the constructor that is being invoked or the name of the
- * field that is being referenced.
- *
- * @return the name of the constructor being invoked or the name of the field being referenced
+ * Return the name of the class defining the constructor that is being invoked
+ * or the name of the field that is being referenced.
*/
Identifier get name => _name;
/**
- * Set the name of the class defining the constructor that is being invoked or the name of the
- * field that is being referenced to the given name.
- *
- * @param name the name of the constructor being invoked or the name of the field being referenced
+ * Set the name of the class defining the constructor that is being invoked or
+ * the name of the field that is being referenced to the given [name].
*/
void set name(Identifier name) {
_name = becomeParentOf(name);
@@ -392,24 +348,22 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_constructorName, visitor);
- safelyVisitChild(_arguments, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_constructorName, visitor);
+ _safelyVisitChild(_arguments, visitor);
}
}
/**
- * Instances of the class `ArgumentList` represent a list of arguments in the invocation of a
- * executable element: a function, method, or constructor.
+ * A list of arguments in the invocation of an executable element: a function,
+ * method, or constructor.
*
- * <pre>
- * argumentList ::=
- * '(' arguments? ')'
- *
- * arguments ::=
- * [NamedExpression] (',' [NamedExpression])*
- * | [Expression] (',' [NamedExpression])*
- * </pre>
+ * > argumentList ::=
+ * > '(' arguments? ')'
+ * >
+ * > arguments ::=
+ * > [NamedExpression] (',' [NamedExpression])*
+ * > | [Expression] (',' [Expression])* (',' [NamedExpression])*
*/
class ArgumentList extends AstNode {
/**
@@ -428,29 +382,28 @@
Token rightParenthesis;
/**
- * An array containing the elements representing the parameters corresponding to each of the
- * arguments in this list, or `null` if the AST has not been resolved or if the function or
- * method being invoked could not be determined based on static type information. The array must
- * be the same length as the number of arguments, but can contain `null` entries if a given
- * argument does not correspond to a formal parameter.
+ * A list containing the elements representing the parameters corresponding to
+ * each of the arguments in this list, or `null` if the AST has not been
+ * resolved or if the function or method being invoked could not be determined
+ * based on static type information. The list must be the same length as the
+ * number of arguments, but can contain `null` entries if a given argument
+ * does not correspond to a formal parameter.
*/
List<ParameterElement> _correspondingStaticParameters;
/**
- * An array containing the elements representing the parameters corresponding to each of the
- * arguments in this list, or `null` if the AST has not been resolved or if the function or
- * method being invoked could not be determined based on propagated type information. The array
- * must be the same length as the number of arguments, but can contain `null` entries if a
- * given argument does not correspond to a formal parameter.
+ * A list containing the elements representing the parameters corresponding to
+ * each of the arguments in this list, or `null` if the AST has not been
+ * resolved or if the function or method being invoked could not be determined
+ * based on propagated type information. The list must be the same length as
+ * the number of arguments, but can contain `null` entries if a given argument
+ * does not correspond to a formal parameter.
*/
List<ParameterElement> _correspondingPropagatedParameters;
/**
- * Initialize a newly created list of arguments.
- *
- * @param leftParenthesis the left parenthesis
- * @param arguments the expressions producing the values of the arguments
- * @param rightParenthesis the right parenthesis
+ * Initialize a newly created list of arguments. The list of [arguments] can
+ * be `null` if there are no arguments.
*/
ArgumentList(this.leftParenthesis, List<Expression> arguments,
this.rightParenthesis) {
@@ -458,11 +411,9 @@
}
/**
- * Return the expressions producing the values of the arguments. Although the language requires
- * that positional arguments appear before named arguments, this class allows them to be
- * intermixed.
- *
- * @return the expressions producing the values of the arguments
+ * Return the expressions producing the values of the arguments. Although the
+ * language requires that positional arguments appear before named arguments,
+ * this class allows them to be intermixed.
*/
NodeList<Expression> get arguments => _arguments;
@@ -479,12 +430,10 @@
..add(rightParenthesis);
/**
- * Set the parameter elements corresponding to each of the arguments in this list to the given
- * array of parameters. The array of parameters must be the same length as the number of
- * arguments, but can contain `null` entries if a given argument does not correspond to a
- * formal parameter.
- *
- * @param parameters the parameter elements corresponding to the arguments
+ * Set the parameter elements corresponding to each of the arguments in this
+ * list to the given list of [parameters]. The list of parameters must be the
+ * same length as the number of arguments, but can contain `null` entries if a
+ * given argument does not correspond to a formal parameter.
*/
void set
correspondingPropagatedParameters(List<ParameterElement> parameters) {
@@ -496,12 +445,10 @@
}
/**
- * Set the parameter elements corresponding to each of the arguments in this list to the given
- * array of parameters. The array of parameters must be the same length as the number of
- * arguments, but can contain `null` entries if a given argument does not correspond to a
- * formal parameter.
- *
- * @param parameters the parameter elements corresponding to the arguments
+ * Set the parameter elements corresponding to each of the arguments in this
+ * list to the given list of parameters. The list of parameters must be the
+ * same length as the number of arguments, but can contain `null` entries if a
+ * given argument does not correspond to a formal parameter.
*/
void set correspondingStaticParameters(List<ParameterElement> parameters) {
if (parameters.length != _arguments.length) {
@@ -518,17 +465,18 @@
accept(AstVisitor visitor) => visitor.visitArgumentList(this);
/**
- * If the given expression is a child of this list, and the AST structure has been resolved, and
- * the function being invoked is known based on propagated type information, and the expression
- * corresponds to one of the parameters of the function being invoked, then return the parameter
- * element representing the parameter to which the value of the given expression will be bound.
- * Otherwise, return `null`.
+ * If
+ * * the given [expression] is a child of this list,
+ * * the AST structure has been resolved,
+ * * the function being invoked is known based on propagated type information,
+ * and
+ * * the expression corresponds to one of the parameters of the function being
+ * invoked,
+ * then return the parameter element representing the parameter to which the
+ * value of the given expression will be bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.propagatedParameterElement].
- *
- * @param expression the expression corresponding to the parameter to be returned
- * @return the parameter element representing the parameter to which the value of the expression
- * will be bound
+ * This method is only intended to be used by
+ * [Expression.propagatedParameterElement].
*/
ParameterElement getPropagatedParameterElementFor(Expression expression) {
if (_correspondingPropagatedParameters == null) {
@@ -545,17 +493,17 @@
}
/**
- * If the given expression is a child of this list, and the AST structure has been resolved, and
- * the function being invoked is known based on static type information, and the expression
- * corresponds to one of the parameters of the function being invoked, then return the parameter
- * element representing the parameter to which the value of the given expression will be bound.
- * Otherwise, return `null`.
+ * If
+ * * the given [expression] is a child of this list,
+ * * the AST structure has been resolved,
+ * * the function being invoked is known based on static type information, and
+ * * the expression corresponds to one of the parameters of the function being
+ * invoked,
+ * then return the parameter element representing the parameter to which the
+ * value of the given expression will be bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.staticParameterElement].
- *
- * @param expression the expression corresponding to the parameter to be returned
- * @return the parameter element representing the parameter to which the value of the expression
- * will be bound
+ * This method is only intended to be used by
+ * [Expression.staticParameterElement].
*/
ParameterElement getStaticParameterElementFor(Expression expression) {
if (_correspondingStaticParameters == null) {
@@ -578,12 +526,10 @@
}
/**
- * Instances of the class `AsExpression` represent an 'as' expression.
+ * An as expression.
*
- * <pre>
- * asExpression ::=
- * [Expression] 'as' [TypeName]
- * </pre>
+ * > asExpression ::=
+ * > [Expression] 'as' [TypeName]
*/
class AsExpression extends Expression {
/**
@@ -603,10 +549,6 @@
/**
* Initialize a newly created as expression.
- *
- * @param expression the expression used to compute the value being cast
- * @param asOperator the as operator
- * @param type the name of the type being cast to
*/
AsExpression(Expression expression, this.asOperator, TypeName type) {
_expression = becomeParentOf(expression);
@@ -627,15 +569,12 @@
/**
* Return the expression used to compute the value being cast.
- *
- * @return the expression used to compute the value being cast
*/
Expression get expression => _expression;
/**
- * Set the expression used to compute the value being cast to the given expression.
- *
- * @param expression the expression used to compute the value being cast
+ * Set the expression used to compute the value being cast to the given
+ * [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -646,15 +585,11 @@
/**
* Return the name of the type being cast to.
- *
- * @return the name of the type being cast to
*/
TypeName get type => _type;
/**
- * Set the name of the type being cast to to the given name.
- *
- * @param name the name of the type being cast to
+ * Set the name of the type being cast to to the given [name].
*/
void set type(TypeName name) {
_type = becomeParentOf(name);
@@ -665,18 +600,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
- safelyVisitChild(_type, visitor);
+ _safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_type, visitor);
}
}
/**
- * Instances of the class `AssertStatement` represent an assert statement.
+ * An assert statement.
*
- * <pre>
- * assertStatement ::=
- * 'assert' '(' [Expression] ')' ';'
- * </pre>
+ * > assertStatement ::=
+ * > 'assert' '(' [Expression] ')' ';'
*/
class AssertStatement extends Statement {
/**
@@ -706,12 +639,6 @@
/**
* Initialize a newly created assert statement.
- *
- * @param keyword the token representing the 'assert' keyword
- * @param leftParenthesis the left parenthesis
- * @param condition the condition that is being asserted to be `true`
- * @param rightParenthesis the right parenthesis
- * @param semicolon the semicolon terminating the statement
*/
AssertStatement(this.keyword, this.leftParenthesis, Expression condition,
this.rightParenthesis, this.semicolon) {
@@ -734,15 +661,12 @@
/**
* Return the condition that is being asserted to be `true`.
- *
- * @return the condition that is being asserted to be `true`
*/
Expression get condition => _condition;
/**
- * Set the condition that is being asserted to be `true` to the given expression.
- *
- * @param the condition that is being asserted to be `true`
+ * Set the condition that is being asserted to be `true` to the given
+ * [expression].
*/
void set condition(Expression condition) {
_condition = becomeParentOf(condition);
@@ -756,17 +680,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_condition, visitor);
+ _safelyVisitChild(_condition, visitor);
}
}
/**
- * Instances of the class `AssignmentExpression` represent an assignment expression.
+ * An assignment expression.
*
- * <pre>
- * assignmentExpression ::=
- * [Expression] [Token] [Expression]
- * </pre>
+ * > assignmentExpression ::=
+ * > [Expression] operator [Expression]
*/
class AssignmentExpression extends Expression {
/**
@@ -785,25 +707,23 @@
Expression _rightHandSide;
/**
- * The element associated with the operator based on the static type of the left-hand-side, or
- * `null` if the AST structure has not been resolved, if the operator is not a compound
- * operator, or if the operator could not be resolved.
+ * The element associated with the operator based on the static type of the
+ * left-hand-side, or `null` if the AST structure has not been resolved, if
+ * the operator is not a compound operator, or if the operator could not be
+ * resolved.
*/
MethodElement staticElement;
/**
- * The element associated with the operator based on the propagated type of the left-hand-side, or
- * `null` if the AST structure has not been resolved, if the operator is not a compound
- * operator, or if the operator could not be resolved.
+ * The element associated with the operator based on the propagated type of
+ * the left-hand-side, or `null` if the AST structure has not been resolved,
+ * if the operator is not a compound operator, or if the operator could not be
+ * resolved.
*/
MethodElement propagatedElement;
/**
* Initialize a newly created assignment expression.
- *
- * @param leftHandSide the expression used to compute the left hand side
- * @param operator the assignment operator being applied
- * @param rightHandSide the expression used to compute the right hand side
*/
AssignmentExpression(Expression leftHandSide, this.operator,
Expression rightHandSide) {
@@ -830,12 +750,11 @@
Token get beginToken => _leftHandSide.beginToken;
/**
- * Return the best element available for this operator. If resolution was able to find a better
- * element based on type propagation, that element will be returned. Otherwise, the element found
- * using the result of static analysis will be returned. If resolution has not been performed,
- * then `null` will be returned.
- *
- * @return the best element available for this operator
+ * Return the best element available for this operator. If resolution was able
+ * to find a better element based on type propagation, that element will be
+ * returned. Otherwise, the element found using the result of static analysis
+ * will be returned. If resolution has not been performed, then `null` will be
+ * returned.
*/
MethodElement get bestElement {
MethodElement element = propagatedElement;
@@ -855,16 +774,13 @@
Token get endToken => _rightHandSide.endToken;
/**
- * Set the expression used to compute the left hand side to the given expression.
- *
- * @return the expression used to compute the left hand side
+ * Set the expression used to compute the left hand side to the given
+ * [expression].
*/
Expression get leftHandSide => _leftHandSide;
/**
* Return the expression used to compute the left hand side.
- *
- * @param expression the expression used to compute the left hand side
*/
void set leftHandSide(Expression expression) {
_leftHandSide = becomeParentOf(expression);
@@ -874,14 +790,13 @@
int get precedence => 1;
/**
- * If the AST structure has been resolved, and the function being invoked is known based on
- * propagated type information, then return the parameter element representing the parameter to
- * which the value of the right operand will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on propagated type information, then return the parameter
+ * element representing the parameter to which the value of the right operand
+ * will be bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.propagatedParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the right
- * operand will be bound
+ * This method is only intended to be used by
+ * [Expression.propagatedParameterElement].
*/
ParameterElement get propagatedParameterElementForRightHandSide {
ExecutableElement executableElement = null;
@@ -916,29 +831,25 @@
/**
* Return the expression used to compute the right hand side.
- *
- * @return the expression used to compute the right hand side
*/
Expression get rightHandSide => _rightHandSide;
/**
- * Set the expression used to compute the left hand side to the given expression.
- *
- * @param expression the expression used to compute the left hand side
+ * Set the expression used to compute the left hand side to the given
+ * [expression].
*/
void set rightHandSide(Expression expression) {
_rightHandSide = becomeParentOf(expression);
}
/**
- * If the AST structure has been resolved, and the function being invoked is known based on static
- * type information, then return the parameter element representing the parameter to which the
- * value of the right operand will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on static type information, then return the parameter element
+ * representing the parameter to which the value of the right operand will be
+ * bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.staticParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the right
- * operand will be bound
+ * This method is only intended to be used by
+ * [Expression.staticParameterElement].
*/
ParameterElement get staticParameterElementForRightHandSide {
ExecutableElement executableElement = null;
@@ -974,15 +885,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_leftHandSide, visitor);
- safelyVisitChild(_rightHandSide, visitor);
+ _safelyVisitChild(_leftHandSide, visitor);
+ _safelyVisitChild(_rightHandSide, visitor);
}
}
/**
- * An `AstCloner` is an AST visitor that will clone any AST structure that it
- * visits. The cloner will only clone the structure, it will not preserve any
- * resolution results or properties associated with the nodes.
+ * An AST visitor that will clone any AST structure that it visits. The cloner
+ * will only clone the structure, it will not preserve any resolution results or
+ * properties associated with the nodes.
*/
class AstCloner implements AstVisitor<AstNode> {
/**
@@ -995,6 +906,7 @@
* Initialize a newly created AST cloner to optionally clone tokens while
* cloning AST nodes if [cloneTokens] is `true`.
*/
+ // TODO(brianwilkerson) Change this to be a named parameter.
AstCloner([this.cloneTokens = false]);
/**
@@ -1884,13 +1796,14 @@
}
/**
- * An `AstComparator` compares the structure of two AstNodes to see whether
- * they are equal.
+ * An AstVisitor that compares the structure of two AstNodes to see whether they
+ * are equal.
*/
class AstComparator implements AstVisitor<bool> {
/**
- * The AST node with which the node being visited is to be compared. This is only valid at the
- * beginning of each visit method (until [isEqualNodes] is invoked).
+ * The AST node with which the node being visited is to be compared. This is
+ * only valid at the beginning of each visit method (until [isEqualNodes] is
+ * invoked).
*/
AstNode _other;
@@ -2913,13 +2826,8 @@
}
/**
- * Return `true` if the given lists of AST nodes have the same size and corresponding
- * elements are equal.
- *
- * @param first the first node being compared
- * @param second the second node being compared
- * @return `true` if the given AST nodes have the same size and corresponding elements are
- * equal
+ * Return `true` if the [first] and [second] lists of AST nodes have the same
+ * size and corresponding elements are equal.
*/
bool _isEqualNodeLists(NodeList first, NodeList second) {
if (first == null) {
@@ -2940,13 +2848,8 @@
}
/**
- * Return `true` if the given arrays of tokens have the same length and corresponding
- * elements are equal.
- *
- * @param first the first node being compared
- * @param second the second node being compared
- * @return `true` if the given arrays of tokens have the same length and corresponding
- * elements are equal
+ * Return `true` if the [first] and [second] lists of tokens have the same
+ * length and corresponding elements are equal.
*/
bool _isEqualTokenLists(List<Token> first, List<Token> second) {
int length = first.length;
@@ -2962,7 +2865,7 @@
}
/**
- * Return `true` if the [first] node and the [second] node are equal.
+ * Return `true` if the [first] and [second] nodes are equal.
*/
static bool equalNodes(AstNode first, AstNode second) {
AstComparator comparator = new AstComparator();
@@ -2971,39 +2874,38 @@
}
/**
- * The abstract class `AstNode` defines the behavior common to all nodes in the AST structure
- * for a Dart program.
+ * A node in the AST structure for a Dart program.
*/
abstract class AstNode {
/**
- * An empty array of ast nodes.
+ * An empty list of ast nodes.
*/
static const List<AstNode> EMPTY_ARRAY = const <AstNode>[];
/**
- * A comparator that can be used to sort AST nodes in lexical order. In other words,
- * `compare` will return a negative value if the offset of the first node is less than the
- * offset of the second node, zero (0) if the nodes have the same offset, and a positive value if
- * if the offset of the first node is greater than the offset of the second node.
+ * A comparator that can be used to sort AST nodes in lexical order. In other
+ * words, `compare` will return a negative value if the offset of the first
+ * node is less than the offset of the second node, zero (0) if the nodes have
+ * the same offset, and a positive value if if the offset of the first node is
+ * greater than the offset of the second node.
*/
static Comparator<AstNode> LEXICAL_ORDER =
(AstNode first, AstNode second) => second.offset - first.offset;
/**
- * The parent of the node, or `null` if the node is the root of an AST structure.
+ * The parent of the node, or `null` if the node is the root of an AST
+ * structure.
*/
AstNode _parent;
/**
- * A table mapping the names of properties to their values, or `null` if this node does not
- * have any properties associated with it.
+ * A table mapping the names of properties to their values, or `null` if this
+ * node does not have any properties associated with it.
*/
Map<String, Object> _propertyMap;
/**
* Return the first token included in this node's source range.
- *
- * @return the first token included in this node's source range
*/
Token get beginToken;
@@ -3012,38 +2914,32 @@
* up the contents of this node, including doc comments but excluding other
* comments.
*/
- Iterable get childEntities;
+ Iterable /*<AstNode | Token>*/ get childEntities;
/**
- * Return the offset of the character immediately following the last character of this node's
- * source range. This is equivalent to `node.getOffset() + node.getLength()`. For a
- * compilation unit this will be equal to the length of the unit's source. For synthetic nodes
- * this will be equivalent to the node's offset (because the length is zero (0) by definition).
- *
- * @return the offset of the character just past the node's source range
+ * Return the offset of the character immediately following the last character
+ * of this node's source range. This is equivalent to
+ * `node.getOffset() + node.getLength()`. For a compilation unit this will be
+ * equal to the length of the unit's source. For synthetic nodes this will be
+ * equivalent to the node's offset (because the length is zero (0) by
+ * definition).
*/
int get end => offset + length;
/**
* Return the last token included in this node's source range.
- *
- * @return the last token included in this node's source range
*/
Token get endToken;
/**
- * Return `true` if this node is a synthetic node. A synthetic node is a node that was
- * introduced by the parser in order to recover from an error in the code. Synthetic nodes always
- * have a length of zero (`0`).
- *
- * @return `true` if this node is a synthetic node
+ * Return `true` if this node is a synthetic node. A synthetic node is a node
+ * that was introduced by the parser in order to recover from an error in the
+ * code. Synthetic nodes always have a length of zero (`0`).
*/
bool get isSynthetic => false;
/**
* Return the number of characters in the node's source range.
- *
- * @return the number of characters in the node's source range
*/
int get length {
Token beginToken = this.beginToken;
@@ -3055,11 +2951,8 @@
}
/**
- * Return the offset from the beginning of the file to the first character in the node's source
- * range.
- *
- * @return the offset from the beginning of the file to the first character in the node's source
- * range
+ * Return the offset from the beginning of the file to the first character in
+ * the node's source range.
*/
int get offset {
Token beginToken = this.beginToken;
@@ -3070,19 +2963,16 @@
}
/**
- * Return this node's parent node, or `null` if this node is the root of an AST structure.
+ * Return this node's parent node, or `null` if this node is the root of an
+ * AST structure.
*
- * Note that the relationship between an AST node and its parent node may change over the lifetime
- * of a node.
- *
- * @return the parent of this node, or `null` if none
+ * Note that the relationship between an AST node and its parent node may
+ * change over the lifetime of a node.
*/
AstNode get parent => _parent;
/**
- * Set the parent of this node to the given node.
- *
- * @param newParent the node that is to be made the parent of this node
+ * Set the parent of this node to the [newParent].
*/
@deprecated
void set parent(AstNode newParent) {
@@ -3090,10 +2980,9 @@
}
/**
- * Return the node at the root of this node's AST structure. Note that this method's performance
- * is linear with respect to the depth of the node in the AST structure (O(depth)).
- *
- * @return the node at the root of this node's AST structure
+ * Return the node at the root of this node's AST structure. Note that this
+ * method's performance is linear with respect to the depth of the node in the
+ * AST structure (O(depth)).
*/
AstNode get root {
AstNode root = this;
@@ -3106,18 +2995,13 @@
}
/**
- * Use the given visitor to visit this node.
- *
- * @param visitor the visitor that will visit this node
- * @return the value returned by the visitor as a result of visiting this node
+ * Use the given [visitor] to visit this node. Return the value returned by
+ * the visitor as a result of visiting this node.
*/
- accept(AstVisitor visitor);
+ /* <E> E */ accept(AstVisitor /*<E>*/ visitor);
/**
- * Make this node the parent of the given child node.
- *
- * @param child the node that will become a child of this node
- * @return the node that was made a child of this node
+ * Make this node the parent of the given [child] node. Return the child node.
*/
AstNode becomeParentOf(AstNode child) {
if (child != null) {
@@ -3127,13 +3011,12 @@
}
/**
- * Return the node of the given class that most immediately encloses this node, or `null` if
- * there is no enclosing node of the given class.
- *
- * @param nodeClass the class of the node to be returned
- * @return the node of the given type that encloses this node
+ * Return the most immediate ancestor of this node for which the [predicate]
+ * returns `true`, or `null` if there is no such ancestor. Note that this node
+ * will never be returned.
*/
AstNode getAncestor(Predicate<AstNode> predicate) {
+ // TODO(brianwilkerson) It is a bug that this method can return `this`.
AstNode node = this;
while (node != null && !predicate(node)) {
node = node.parent;
@@ -3142,24 +3025,20 @@
}
/**
- * Return the value of the property with the given name, or `null` if this node does not
- * have a property with the given name.
- *
- * @return the value of the property with the given name
+ * Return the value of the property with the given [name], or `null` if this
+ * node does not have a property with the given name.
*/
- Object getProperty(String propertyName) {
+ Object getProperty(String name) {
if (_propertyMap == null) {
return null;
}
- return _propertyMap[propertyName];
+ return _propertyMap[name];
}
/**
- * If the given child is not `null`, use the given visitor to visit it.
- *
- * @param child the child to be visited
- * @param visitor the visitor that will be used to visit the child
+ * If the given [child] is not `null`, use the given [visitor] to visit it.
*/
+ @deprecated
void safelyVisitChild(AstNode child, AstVisitor visitor) {
if (child != null) {
child.accept(visitor);
@@ -3167,16 +3046,13 @@
}
/**
- * Set the value of the property with the given name to the given value. If the value is
- * `null`, the property will effectively be removed.
- *
- * @param propertyName the name of the property whose value is to be set
- * @param propertyValue the new value of the property
+ * Set the value of the property with the given [name] to the given [value].
+ * If the value is `null`, the property will effectively be removed.
*/
- void setProperty(String propertyName, Object propertyValue) {
- if (propertyValue == null) {
+ void setProperty(String name, Object value) {
+ if (value == null) {
if (_propertyMap != null) {
- _propertyMap.remove(propertyName);
+ _propertyMap.remove(name);
if (_propertyMap.isEmpty) {
_propertyMap = null;
}
@@ -3185,15 +3061,14 @@
if (_propertyMap == null) {
_propertyMap = new HashMap<String, Object>();
}
- _propertyMap[propertyName] = propertyValue;
+ _propertyMap[name] = value;
}
}
/**
- * Return a textual description of this node in a form approximating valid source. The returned
- * string will not be valid source primarily in the case where the node itself is not well-formed.
- *
- * @return the source code equivalent of this node
+ * Return a textual description of this node in a form approximating valid
+ * source. The returned string will not be valid source primarily in the case
+ * where the node itself is not well-formed.
*/
String toSource() {
PrintStringWriter writer = new PrintStringWriter();
@@ -3205,17 +3080,23 @@
String toString() => toSource();
/**
- * Use the given visitor to visit all of the children of this node. The children will be visited
- * in source order.
- *
- * @param visitor the visitor that will be used to visit the children of this node
+ * Use the given [visitor] to visit all of the children of this node. The
+ * children will be visited in lexical order.
*/
void visitChildren(AstVisitor visitor);
+
+ /**
+ * If the given [child] is not `null`, use the given [visitor] to visit it.
+ */
+ void _safelyVisitChild(AstNode child, AstVisitor visitor) {
+ if (child != null) {
+ child.accept(visitor);
+ }
+ }
}
/**
- * The interface `AstVisitor` defines the behavior of objects that can be used to visit an AST
- * structure.
+ * An object that can be used to visit an AST structure.
*/
abstract class AstVisitor<R> {
R visitAdjacentStrings(AdjacentStrings node);
@@ -3433,7 +3314,10 @@
}
/**
- * Instances of the class `AwaitExpression` implement an await expression.
+ * An await expression.
+ *
+ * > awaitExpression ::=
+ * > 'await' [Expression]
*/
class AwaitExpression extends Expression {
/**
@@ -3448,9 +3332,6 @@
/**
* Initialize a newly created await expression.
- *
- * @param awaitKeyword the 'await' keyword
- * @param expression the expression whose value is being waited on
*/
AwaitExpression(this.awaitKeyword, Expression expression) {
_expression = becomeParentOf(expression);
@@ -3474,15 +3355,11 @@
/**
* Return the expression whose value is being waited on.
- *
- * @return the expression whose value is being waited on
*/
Expression get expression => _expression;
/**
- * Set the expression whose value is being waited on to the given expression.
- *
- * @param expression the expression whose value is being waited on
+ * Set the expression whose value is being waited on to the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -3496,17 +3373,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * Instances of the class `BinaryExpression` represent a binary (infix) expression.
+ * A binary (infix) expression.
*
- * <pre>
- * binaryExpression ::=
- * [Expression] [Token] [Expression]
- * </pre>
+ * > binaryExpression ::=
+ * > [Expression] [Token] [Expression]
*/
class BinaryExpression extends Expression {
/**
@@ -3525,25 +3400,22 @@
Expression _rightOperand;
/**
- * The element associated with the operator based on the static type of the left operand, or
- * `null` if the AST structure has not been resolved, if the operator is not user definable,
- * or if the operator could not be resolved.
+ * The element associated with the operator based on the static type of the
+ * left operand, or `null` if the AST structure has not been resolved, if the
+ * operator is not user definable, or if the operator could not be resolved.
*/
MethodElement staticElement;
/**
- * The element associated with the operator based on the propagated type of the left operand, or
- * `null` if the AST structure has not been resolved, if the operator is not user definable,
- * or if the operator could not be resolved.
+ * The element associated with the operator based on the propagated type of
+ * the left operand, or `null` if the AST structure has not been resolved, if
+ * the operator is not user definable, or if the operator could not be
+ * resolved.
*/
MethodElement propagatedElement;
/**
* Initialize a newly created binary expression.
- *
- * @param leftOperand the expression used to compute the left operand
- * @param operator the binary operator being applied
- * @param rightOperand the expression used to compute the right operand
*/
BinaryExpression(Expression leftOperand, this.operator,
Expression rightOperand) {
@@ -3555,12 +3427,11 @@
Token get beginToken => _leftOperand.beginToken;
/**
- * Return the best element available for this operator. If resolution was able to find a better
- * element based on type propagation, that element will be returned. Otherwise, the element found
- * using the result of static analysis will be returned. If resolution has not been performed,
- * then `null` will be returned.
- *
- * @return the best element available for this operator
+ * Return the best element available for this operator. If resolution was able
+ * to find a better element based on type propagation, that element will be
+ * returned. Otherwise, the element found using the result of static analysis
+ * will be returned. If resolution has not been performed, then `null` will be
+ * returned.
*/
MethodElement get bestElement {
MethodElement element = propagatedElement;
@@ -3581,15 +3452,12 @@
/**
* Return the expression used to compute the left operand.
- *
- * @return the expression used to compute the left operand
*/
Expression get leftOperand => _leftOperand;
/**
- * Set the expression used to compute the left operand to the given expression.
- *
- * @param expression the expression used to compute the left operand
+ * Set the expression used to compute the left operand to the given
+ * [expression].
*/
void set leftOperand(Expression expression) {
_leftOperand = becomeParentOf(expression);
@@ -3599,14 +3467,13 @@
int get precedence => operator.type.precedence;
/**
- * If the AST structure has been resolved, and the function being invoked is known based on
- * propagated type information, then return the parameter element representing the parameter to
- * which the value of the right operand will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on propagated type information, then return the parameter
+ * element representing the parameter to which the value of the right operand
+ * will be bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.propagatedParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the right
- * operand will be bound
+ * This method is only intended to be used by
+ * [Expression.propagatedParameterElement].
*/
ParameterElement get propagatedParameterElementForRightOperand {
if (propagatedElement == null) {
@@ -3621,29 +3488,25 @@
/**
* Return the expression used to compute the right operand.
- *
- * @return the expression used to compute the right operand
*/
Expression get rightOperand => _rightOperand;
/**
- * Set the expression used to compute the right operand to the given expression.
- *
- * @param expression the expression used to compute the right operand
+ * Set the expression used to compute the right operand to the given
+ * [expression].
*/
void set rightOperand(Expression expression) {
_rightOperand = becomeParentOf(expression);
}
/**
- * If the AST structure has been resolved, and the function being invoked is known based on static
- * type information, then return the parameter element representing the parameter to which the
- * value of the right operand will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on static type information, then return the parameter element
+ * representing the parameter to which the value of the right operand will be
+ * bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.staticParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the right
- * operand will be bound
+ * This method is only intended to be used by
+ * [Expression.staticParameterElement].
*/
ParameterElement get staticParameterElementForRightOperand {
if (staticElement == null) {
@@ -3661,18 +3524,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_leftOperand, visitor);
- safelyVisitChild(_rightOperand, visitor);
+ _safelyVisitChild(_leftOperand, visitor);
+ _safelyVisitChild(_rightOperand, visitor);
}
}
/**
- * Instances of the class `Block` represent a sequence of statements.
+ * A sequence of statements.
*
- * <pre>
- * block ::=
- * '{' statement* '}'
- * </pre>
+ * > block ::=
+ * > '{' statement* '}'
*/
class Block extends Statement {
/**
@@ -3692,10 +3553,6 @@
/**
* Initialize a newly created block of code.
- *
- * @param leftBracket the left curly bracket
- * @param statements the statements contained in the block
- * @param rightBracket the right curly bracket
*/
Block(this.leftBracket, List<Statement> statements, this.rightBracket) {
_statements = new NodeList<Statement>(this, statements);
@@ -3715,8 +3572,6 @@
/**
* Return the statements contained in the block.
- *
- * @return the statements contained in the block
*/
NodeList<Statement> get statements => _statements;
@@ -3730,23 +3585,21 @@
}
/**
- * Instances of the class `BlockFunctionBody` represent a function body that consists of a
- * block of statements.
+ * A function body that consists of a block of statements.
*
- * <pre>
- * blockFunctionBody ::=
- * ('async' | 'async' '*' | 'sync' '*')? [Block]
- * </pre>
+ * > blockFunctionBody ::=
+ * > ('async' | 'async' '*' | 'sync' '*')? [Block]
*/
class BlockFunctionBody extends FunctionBody {
/**
- * The token representing the 'async' or 'sync' keyword, or `null` if there is no such
- * keyword.
+ * The token representing the 'async' or 'sync' keyword, or `null` if there is
+ * no such keyword.
*/
Token keyword;
/**
- * The star optionally following the 'async' or following the 'sync' keyword.
+ * The star optionally following the 'async' or 'sync' keyword, or `null` if
+ * there is wither no such keyword or no star.
*/
Token star;
@@ -3756,11 +3609,10 @@
Block _block;
/**
- * Initialize a newly created function body consisting of a block of statements.
- *
- * @param keyword the token representing the 'async' or 'sync' keyword
- * @param star the star following the 'async' or 'sync' keyword
- * @param block the block representing the body of the function
+ * Initialize a newly created function body consisting of a block of
+ * statements. The [keyword] can be `null` if there is no keyword specified
+ * for the block. The [star] can be `null` if there is no star following the
+ * keyword (and must be `null` if there is no keyword).
*/
BlockFunctionBody(this.keyword, this.star, Block block) {
_block = becomeParentOf(block);
@@ -3771,15 +3623,11 @@
/**
* Return the block representing the body of the function.
- *
- * @return the block representing the body of the function
*/
Block get block => _block;
/**
- * Set the block representing the body of the function to the given block.
- *
- * @param block the block representing the body of the function
+ * Set the block representing the body of the function to the given [block].
*/
void set block(Block block) {
_block = becomeParentOf(block);
@@ -3814,17 +3662,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_block, visitor);
+ _safelyVisitChild(_block, visitor);
}
}
/**
- * Instances of the class `BooleanLiteral` represent a boolean literal expression.
+ * A boolean literal expression.
*
- * <pre>
- * booleanLiteral ::=
- * 'false' | 'true'
- * </pre>
+ * > booleanLiteral ::=
+ * > 'false' | 'true'
*/
class BooleanLiteral extends Literal {
/**
@@ -3839,9 +3685,6 @@
/**
* Initialize a newly created boolean literal.
- *
- * @param literal the token representing the literal
- * @param value the value of the literal
*/
BooleanLiteral(this.literal, this.value);
@@ -3870,41 +3713,44 @@
}
/**
- * Instances of the class `BreadthFirstVisitor` implement an AST visitor that will recursively
- * visit all of the nodes in an AST structure, similar to [GeneralizingAstVisitor]. This
- * visitor uses a breadth-first ordering rather than the depth-first ordering of
+ * An AST visitor that will recursively visit all of the nodes in an AST
+ * structure, similar to [GeneralizingAstVisitor]. This visitor uses a
+ * breadth-first ordering rather than the depth-first ordering of
* [GeneralizingAstVisitor].
*
- * Subclasses that override a visit method must either invoke the overridden visit method or
- * explicitly invoke the more general visit method. Failure to do so will cause the visit methods
- * for superclasses of the node to not be invoked and will cause the children of the visited node to
- * not be visited.
+ * Subclasses that override a visit method must either invoke the overridden
+ * visit method or explicitly invoke the more general visit method. Failure to
+ * do so will cause the visit methods for superclasses of the node to not be
+ * invoked and will cause the children of the visited node to not be visited.
*
- * In addition, subclasses should <b>not</b> explicitly visit the children of a node, but should
- * ensure that the method [visitNode] is used to visit the children (either directly
- * or indirectly). Failure to do will break the order in which nodes are visited.
+ * In addition, subclasses should <b>not</b> explicitly visit the children of a
+ * node, but should ensure that the method [visitNode] is used to visit the
+ * children (either directly or indirectly). Failure to do will break the order
+ * in which nodes are visited.
*/
class BreadthFirstVisitor<R> extends GeneralizingAstVisitor<R> {
/**
- * A queue holding the nodes that have not yet been visited in the order in which they ought to be
- * visited.
+ * A queue holding the nodes that have not yet been visited in the order in
+ * which they ought to be visited.
*/
Queue<AstNode> _queue = new Queue<AstNode>();
/**
- * A visitor, used to visit the children of the current node, that will add the nodes it visits to
- * the [queue].
+ * A visitor, used to visit the children of the current node, that will add
+ * the nodes it visits to the [_queue].
*/
GeneralizingAstVisitor<Object> _childVisitor;
+ /**
+ * Initialize a newly created visitor.
+ */
BreadthFirstVisitor() {
_childVisitor = new GeneralizingAstVisitor_BreadthFirstVisitor(this);
}
/**
- * Visit all nodes in the tree starting at the given `root` node, in breadth-first order.
- *
- * @param root the root of the AST structure to be visited
+ * Visit all nodes in the tree starting at the given [root] node, in
+ * breadth-first order.
*/
void visitAllNodes(AstNode root) {
_queue.add(root);
@@ -3922,12 +3768,10 @@
}
/**
- * Instances of the class `BreakStatement` represent a break statement.
+ * A break statement.
*
- * <pre>
- * breakStatement ::=
- * 'break' [SimpleIdentifier]? ';'
- * </pre>
+ * > breakStatement ::=
+ * > 'break' [SimpleIdentifier]? ';'
*/
class BreakStatement extends Statement {
/**
@@ -3947,21 +3791,18 @@
/**
* The AstNode which this break statement is breaking from. This will be
- * either a Statement (in the case of breaking out of a loop) or a
- * SwitchMember (in the case of a labeled break statement whose label matches
- * a label on a switch case in an enclosing switch statement). Null if the
- * AST has not yet been resolved or if the target could not be resolved.
- * Note that if the source code has errors, the target may be invalid (e.g.
- * trying to break to a switch case).
+ * either a [Statement] (in the case of breaking out of a loop), a
+ * [SwitchMember] (in the case of a labeled break statement whose label
+ * matches a label on a switch case in an enclosing switch statement), or
+ * `null` if the AST has not yet been resolved or if the target could not be
+ * resolved. Note that if the source code has errors, the target might be
+ * invalid (e.g. trying to break to a switch case).
*/
AstNode target;
/**
- * Initialize a newly created break statement.
- *
- * @param keyword the token representing the 'break' keyword
- * @param label the label associated with the statement
- * @param semicolon the semicolon terminating the statement
+ * Initialize a newly created break statement. The [label] can be `null` if
+ * there is no label associated with the statement.
*/
BreakStatement(this.keyword, SimpleIdentifier label, this.semicolon) {
_label = becomeParentOf(label);
@@ -3983,16 +3824,13 @@
Token get endToken => semicolon;
/**
- * Return the label associated with the statement, or `null` if there is no label.
- *
- * @return the label associated with the statement
+ * Return the label associated with the statement, or `null` if there is no
+ * label.
*/
SimpleIdentifier get label => _label;
/**
- * Set the label associated with the statement to the given identifier.
- *
- * @param identifier the label associated with the statement
+ * Set the label associated with the statement to the given [identifier].
*/
void set label(SimpleIdentifier identifier) {
_label = becomeParentOf(identifier);
@@ -4003,27 +3841,25 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_label, visitor);
+ _safelyVisitChild(_label, visitor);
}
}
/**
- * Instances of the class `CascadeExpression` represent a sequence of cascaded expressions:
- * expressions that share a common target. There are three kinds of expressions that can be used in
- * a cascade expression: [IndexExpression], [MethodInvocation] and
- * [PropertyAccess].
+ * A sequence of cascaded expressions: expressions that share a common target.
+ * There are three kinds of expressions that can be used in a cascade
+ * expression: [IndexExpression], [MethodInvocation] and [PropertyAccess].
*
- * <pre>
- * cascadeExpression ::=
- * [Expression] cascadeSection*
- *
- * cascadeSection ::=
- * '..' (cascadeSelector arguments*) (assignableSelector arguments*)* (assignmentOperator expressionWithoutCascade)?
- *
- * cascadeSelector ::=
- * '[ ' expression '] '
- * | identifier
- * </pre>
+ * > cascadeExpression ::=
+ * > [Expression] cascadeSection*
+ * >
+ * > cascadeSection ::=
+ * > '..' (cascadeSelector arguments*) (assignableSelector arguments*)*
+ * > (assignmentOperator expressionWithoutCascade)?
+ * >
+ * > cascadeSelector ::=
+ * > '[ ' expression '] '
+ * > | identifier
*/
class CascadeExpression extends Expression {
/**
@@ -4037,10 +3873,8 @@
NodeList<Expression> _cascadeSections;
/**
- * Initialize a newly created cascade expression.
- *
- * @param target the target of the cascade sections
- * @param cascadeSections the cascade sections sharing the common target
+ * Initialize a newly created cascade expression. The list of
+ * [cascadeSections] must contain at least one element.
*/
CascadeExpression(Expression target, List<Expression> cascadeSections) {
_target = becomeParentOf(target);
@@ -4052,8 +3886,6 @@
/**
* Return the cascade sections sharing the common target.
- *
- * @return the cascade sections sharing the common target
*/
NodeList<Expression> get cascadeSections => _cascadeSections;
@@ -4070,15 +3902,11 @@
/**
* Return the target of the cascade sections.
- *
- * @return the target of the cascade sections
*/
Expression get target => _target;
/**
- * Set the target of the cascade sections to the given expression.
- *
- * @param target the target of the cascade sections
+ * Set the target of the cascade sections to the given [expression].
*/
void set target(Expression target) {
_target = becomeParentOf(target);
@@ -4089,37 +3917,37 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_target, visitor);
+ _safelyVisitChild(_target, visitor);
_cascadeSections.accept(visitor);
}
}
/**
- * Instances of the class `CatchClause` represent a catch clause within a try statement.
+ * A catch clause within a try statement.
*
- * <pre>
- * onPart ::=
- * catchPart [Block]
- * | 'on' type catchPart? [Block]
- *
- * catchPart ::=
- * 'catch' '(' [SimpleIdentifier] (',' [SimpleIdentifier])? ')'
- * </pre>
+ * > onPart ::=
+ * > catchPart [Block]
+ * > | 'on' type catchPart? [Block]
+ * >
+ * > catchPart ::=
+ * > 'catch' '(' [SimpleIdentifier] (',' [SimpleIdentifier])? ')'
*/
class CatchClause extends AstNode {
/**
- * The token representing the 'on' keyword, or `null` if there is no 'on' keyword.
+ * The token representing the 'on' keyword, or `null` if there is no 'on'
+ * keyword.
*/
Token onKeyword;
/**
- * The type of exceptions caught by this catch clause, or `null` if this catch clause
- * catches every type of exception.
+ * The type of exceptions caught by this catch clause, or `null` if this catch
+ * clause catches every type of exception.
*/
TypeName _exceptionType;
/**
- * The token representing the 'catch' keyword, or `null` if there is no 'catch' keyword.
+ * The token representing the 'catch' keyword, or `null` if there is no
+ * 'catch' keyword.
*/
Token catchKeyword;
@@ -4134,14 +3962,14 @@
SimpleIdentifier _exceptionParameter;
/**
- * The comma separating the exception parameter from the stack trace parameter, or `null` if
- * there is no stack trace parameter.
+ * The comma separating the exception parameter from the stack trace
+ * parameter, or `null` if there is no stack trace parameter.
*/
Token comma;
/**
- * The parameter whose value will be the stack trace associated with the exception, or
- * `null` if there is no stack trace parameter.
+ * The parameter whose value will be the stack trace associated with the
+ * exception, or `null` if there is no stack trace parameter.
*/
SimpleIdentifier _stackTraceParameter;
@@ -4156,17 +3984,10 @@
Block _body;
/**
- * Initialize a newly created catch clause.
- *
- * @param onKeyword the token representing the 'on' keyword
- * @param exceptionType the type of exceptions caught by this catch clause
- * @param leftParenthesis the left parenthesis
- * @param exceptionParameter the parameter whose value will be the exception that was thrown
- * @param comma the comma separating the exception parameter from the stack trace parameter
- * @param stackTraceParameter the parameter whose value will be the stack trace associated with
- * the exception
- * @param rightParenthesis the right parenthesis
- * @param body the body of the catch block
+ * Initialize a newly created catch clause. The [onKeyword] and
+ * [exceptionType] can be `null` if the clause will catch all exceptions. The
+ * [comma] and [stackTraceParameter] can be `null` if the stack trace is not
+ * referencable within the body.
*/
CatchClause(this.onKeyword, TypeName exceptionType, this.catchKeyword,
this.leftParenthesis, SimpleIdentifier exceptionParameter, this.comma,
@@ -4187,15 +4008,11 @@
/**
* Return the body of the catch block.
- *
- * @return the body of the catch block
*/
Block get body => _body;
/**
- * Set the body of the catch block to the given block.
- *
- * @param block the body of the catch block
+ * Set the body of the catch block to the given [block].
*/
void set body(Block block) {
_body = becomeParentOf(block);
@@ -4218,51 +4035,40 @@
/**
* Return the parameter whose value will be the exception that was thrown.
- *
- * @return the parameter whose value will be the exception that was thrown
*/
SimpleIdentifier get exceptionParameter => _exceptionParameter;
/**
- * Set the parameter whose value will be the exception that was thrown to the given parameter.
- *
- * @param parameter the parameter whose value will be the exception that was thrown
+ * Set the parameter whose value will be the exception that was thrown to the
+ * given [parameter].
*/
void set exceptionParameter(SimpleIdentifier parameter) {
_exceptionParameter = becomeParentOf(parameter);
}
/**
- * Return the type of exceptions caught by this catch clause, or `null` if this catch clause
- * catches every type of exception.
- *
- * @return the type of exceptions caught by this catch clause
+ * Return the type of exceptions caught by this catch clause, or `null` if
+ * this catch clause catches every type of exception.
*/
TypeName get exceptionType => _exceptionType;
/**
- * Set the type of exceptions caught by this catch clause to the given type.
- *
- * @param exceptionType the type of exceptions caught by this catch clause
+ * Set the type of exceptions caught by this catch clause to the given
+ * [exceptionType].
*/
void set exceptionType(TypeName exceptionType) {
_exceptionType = becomeParentOf(exceptionType);
}
/**
- * Return the parameter whose value will be the stack trace associated with the exception, or
- * `null` if there is no stack trace parameter.
- *
- * @return the parameter whose value will be the stack trace associated with the exception
+ * Return the parameter whose value will be the stack trace associated with
+ * the exception, or `null` if there is no stack trace parameter.
*/
SimpleIdentifier get stackTraceParameter => _stackTraceParameter;
/**
- * Set the parameter whose value will be the stack trace associated with the exception to the
- * given parameter.
- *
- * @param parameter the parameter whose value will be the stack trace associated with the
- * exception
+ * Set the parameter whose value will be the stack trace associated with the
+ * exception to the given [parameter].
*/
void set stackTraceParameter(SimpleIdentifier parameter) {
_stackTraceParameter = becomeParentOf(parameter);
@@ -4273,10 +4079,10 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_exceptionType, visitor);
- safelyVisitChild(_exceptionParameter, visitor);
- safelyVisitChild(_stackTraceParameter, visitor);
- safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_exceptionType, visitor);
+ _safelyVisitChild(_exceptionParameter, visitor);
+ _safelyVisitChild(_stackTraceParameter, visitor);
+ _safelyVisitChild(_body, visitor);
}
}
@@ -4310,15 +4116,13 @@
}
/**
- * Instances of the class `ClassDeclaration` represent the declaration of a class.
+ * The declaration of a class.
*
- * <pre>
- * classDeclaration ::=
- * 'abstract'? 'class' [SimpleIdentifier] [TypeParameterList]?
- * ([ExtendsClause] [WithClause]?)?
- * [ImplementsClause]?
- * '{' [ClassMember]* '}'
- * </pre>
+ * > classDeclaration ::=
+ * > 'abstract'? 'class' [SimpleIdentifier] [TypeParameterList]?
+ * > ([ExtendsClause] [WithClause]?)?
+ * > [ImplementsClause]?
+ * > '{' [ClassMember]* '}'
*/
class ClassDeclaration extends CompilationUnitMember {
/**
@@ -4337,29 +4141,32 @@
SimpleIdentifier _name;
/**
- * The type parameters for the class, or `null` if the class does not have any type
- * parameters.
+ * The type parameters for the class, or `null` if the class does not have any
+ * type parameters.
*/
TypeParameterList _typeParameters;
/**
- * The extends clause for the class, or `null` if the class does not extend any other class.
+ * The extends clause for the class, or `null` if the class does not extend
+ * any other class.
*/
ExtendsClause _extendsClause;
/**
- * The with clause for the class, or `null` if the class does not have a with clause.
+ * The with clause for the class, or `null` if the class does not have a with
+ * clause.
*/
WithClause _withClause;
/**
- * The implements clause for the class, or `null` if the class does not implement any
- * interfaces.
+ * The implements clause for the class, or `null` if the class does not
+ * implement any interfaces.
*/
ImplementsClause _implementsClause;
/**
- * The native clause for the class, or `null` if the class does not have a native clause.
+ * The native clause for the class, or `null` if the class does not have a
+ * native clause.
*/
NativeClause _nativeClause;
@@ -4379,20 +4186,14 @@
Token rightBracket;
/**
- * Initialize a newly created class declaration.
- *
- * @param comment the documentation comment associated with this class
- * @param metadata the annotations associated with this class
- * @param abstractKeyword the 'abstract' keyword, or `null` if the keyword was absent
- * @param classKeyword the token representing the 'class' keyword
- * @param name the name of the class being declared
- * @param typeParameters the type parameters for the class
- * @param extendsClause the extends clause for the class
- * @param withClause the with clause for the class
- * @param implementsClause the implements clause for the class
- * @param leftBracket the left curly bracket
- * @param members the members defined by the class
- * @param rightBracket the right curly bracket
+ * Initialize a newly created class declaration. Either or both of the
+ * [comment] and [metadata] can be `null` if the class does not have the
+ * corresponding attribute. The [abstractKeyword] can be `null` if the class
+ * is not abstract. The [typeParameters] can be `null` if the class does not
+ * have any type parameters. Any or all of the [extendsClause], [withClause],
+ * and [implementsClause] can be `null` if the class does not have the
+ * corresponding clause. The list of [members] can be `null` if the class does
+ * not have any members.
*/
ClassDeclaration(Comment comment, List<Annotation> metadata,
this.abstractKeyword, this.classKeyword, SimpleIdentifier name,
@@ -4430,17 +4231,13 @@
Token get endToken => rightBracket;
/**
- * Return the extends clause for this class, or `null` if the class does not extend any
- * other class.
- *
- * @return the extends clause for this class
+ * Return the extends clause for this class, or `null` if the class does not
+ * extend any other class.
*/
ExtendsClause get extendsClause => _extendsClause;
/**
- * Set the extends clause for this class to the given clause.
- *
- * @param extendsClause the extends clause for this class
+ * Set the extends clause for this class to the given [extendsClause].
*/
void set extendsClause(ExtendsClause extendsClause) {
_extendsClause = becomeParentOf(extendsClause);
@@ -4455,17 +4252,13 @@
}
/**
- * Return the implements clause for the class, or `null` if the class does not implement any
- * interfaces.
- *
- * @return the implements clause for the class
+ * Return the implements clause for the class, or `null` if the class does not
+ * implement any interfaces.
*/
ImplementsClause get implementsClause => _implementsClause;
/**
- * Set the implements clause for the class to the given clause.
- *
- * @param implementsClause the implements clause for the class
+ * Set the implements clause for the class to the given [implementsClause].
*/
void set implementsClause(ImplementsClause implementsClause) {
_implementsClause = becomeParentOf(implementsClause);
@@ -4473,79 +4266,60 @@
/**
* Return `true` if this class is declared to be an abstract class.
- *
- * @return `true` if this class is declared to be an abstract class
*/
bool get isAbstract => abstractKeyword != null;
/**
* Return the members defined by the class.
- *
- * @return the members defined by the class
*/
NodeList<ClassMember> get members => _members;
/**
* Return the name of the class being declared.
- *
- * @return the name of the class being declared
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the class being declared to the given identifier.
- *
- * @param identifier the name of the class being declared
+ * Set the name of the class being declared to the given [identifier].
*/
void set name(SimpleIdentifier identifier) {
_name = becomeParentOf(identifier);
}
/**
- * Return the native clause for this class, or `null` if the class does not have a native
- * cluse.
- *
- * @return the native clause for this class
+ * Return the native clause for this class, or `null` if the class does not
+ * have a native clause.
*/
NativeClause get nativeClause => _nativeClause;
/**
- * Set the native clause for this class to the given clause.
- *
- * @param nativeClause the native clause for this class
+ * Set the native clause for this class to the given [nativeClause].
*/
void set nativeClause(NativeClause nativeClause) {
_nativeClause = becomeParentOf(nativeClause);
}
/**
- * Return the type parameters for the class, or `null` if the class does not have any type
- * parameters.
- *
- * @return the type parameters for the class
+ * Return the type parameters for the class, or `null` if the class does not
+ * have any type parameters.
*/
TypeParameterList get typeParameters => _typeParameters;
/**
- * Set the type parameters for the class to the given list of type parameters.
- *
- * @param typeParameters the type parameters for the class
+ * Set the type parameters for the class to the given list of [typeParameters].
*/
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = becomeParentOf(typeParameters);
}
/**
- * Return the with clause for the class, or `null` if the class does not have a with clause.
- *
- * @return the with clause for the class
+ * Return the with clause for the class, or `null` if the class does not have
+ * a with clause.
*/
WithClause get withClause => _withClause;
/**
- * Set the with clause for the class to the given clause.
- *
- * @param withClause the with clause for the class
+ * Set the with clause for the class to the given [withClause].
*/
void set withClause(WithClause withClause) {
_withClause = becomeParentOf(withClause);
@@ -4555,10 +4329,9 @@
accept(AstVisitor visitor) => visitor.visitClassDeclaration(this);
/**
- * Return the constructor declared in the class with the given name.
- *
- * @param name the name of the constructor to find, `null` for default
- * @return the found constructor or `null` if not found
+ * Return the constructor declared in the class with the given [name], or
+ * `null` if there is no such constructor. If the [name] is `null` then the
+ * default constructor will be searched for.
*/
ConstructorDeclaration getConstructor(String name) {
for (ClassMember classMember in _members) {
@@ -4577,10 +4350,8 @@
}
/**
- * Return the field declared in the class with the given name.
- *
- * @param name the name of the field to find
- * @return the found field or `null` if not found
+ * Return the field declared in the class with the given [name], or `null` if
+ * there is no such field.
*/
VariableDeclaration getField(String name) {
for (ClassMember classMember in _members) {
@@ -4600,10 +4371,8 @@
}
/**
- * Return the method declared in the class with the given name.
- *
- * @param name the name of the method to find
- * @return the found method or `null` if not found
+ * Return the method declared in the class with the given [name], or `null` if
+ * there is no such method.
*/
MethodDeclaration getMethod(String name) {
for (ClassMember classMember in _members) {
@@ -4621,41 +4390,40 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_typeParameters, visitor);
- safelyVisitChild(_extendsClause, visitor);
- safelyVisitChild(_withClause, visitor);
- safelyVisitChild(_implementsClause, visitor);
- safelyVisitChild(_nativeClause, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_typeParameters, visitor);
+ _safelyVisitChild(_extendsClause, visitor);
+ _safelyVisitChild(_withClause, visitor);
+ _safelyVisitChild(_implementsClause, visitor);
+ _safelyVisitChild(_nativeClause, visitor);
members.accept(visitor);
}
}
/**
- * The abstract class `ClassMember` defines the behavior common to nodes that declare a name
- * within the scope of a class.
+ * A node that declares a name within the scope of a class.
*/
abstract class ClassMember extends Declaration {
/**
- * Initialize a newly created member of a class.
- *
- * @param comment the documentation comment associated with this member
- * @param metadata the annotations associated with this member
+ * Initialize a newly created member of a class. Either or both of the
+ * [comment] and [metadata] can be `null` if the member does not have the
+ * corresponding attribute.
*/
ClassMember(Comment comment, List<Annotation> metadata)
: super(comment, metadata);
}
/**
- * Instances of the class `ClassTypeAlias` represent a class type alias.
+ * A class type alias.
*
- * <pre>
- * classTypeAlias ::=
- * [SimpleIdentifier] [TypeParameterList]? '=' 'abstract'? mixinApplication
+ * > classTypeAlias ::=
+ * > [SimpleIdentifier] [TypeParameterList]? '=' 'abstract'? mixinApplication
+ * >
+ * > mixinApplication ::=
+ * > [TypeName] [WithClause] [ImplementsClause]? ';'
*
- * mixinApplication ::=
- * [TypeName] [WithClause] [ImplementsClause]? ';'
- * </pre>
+ * Deprecated: This class captures obsolete syntax that is no longer part of the
+ * Dart language.
*/
class ClassTypeAlias extends TypeAlias {
/**
@@ -4664,8 +4432,8 @@
SimpleIdentifier _name;
/**
- * The type parameters for the class, or `null` if the class does not have any type
- * parameters.
+ * The type parameters for the class, or `null` if the class does not have any
+ * type parameters.
*/
TypeParameterList _typeParameters;
@@ -4675,8 +4443,8 @@
Token equals;
/**
- * The token for the 'abstract' keyword, or `null` if this is not defining an abstract
- * class.
+ * The token for the 'abstract' keyword, or `null` if this is not defining an
+ * abstract class.
*/
Token abstractKeyword;
@@ -4691,24 +4459,18 @@
WithClause _withClause;
/**
- * The implements clause for this class, or `null` if there is no implements clause.
+ * The implements clause for this class, or `null` if there is no implements
+ * clause.
*/
ImplementsClause _implementsClause;
/**
- * Initialize a newly created class type alias.
- *
- * @param comment the documentation comment associated with this type alias
- * @param metadata the annotations associated with this type alias
- * @param keyword the token representing the 'typedef' keyword
- * @param name the name of the class being declared
- * @param typeParameters the type parameters for the class
- * @param equals the token for the '=' separating the name from the definition
- * @param abstractKeyword the token for the 'abstract' keyword
- * @param superclass the name of the superclass of the class being declared
- * @param withClause the with clause for this class
- * @param implementsClause the implements clause for this class
- * @param semicolon the semicolon terminating the declaration
+ * Initialize a newly created class type alias. Either or both of the
+ * [comment] and [metadata] can be `null` if the class type alias does not
+ * have the corresponding attribute. The [typeParameters] can be `null` if the
+ * class does not have any type parameters. The [abstractKeyword] can be
+ * `null` if the class is not abstract. The [implementsClause] can be `null`
+ * if the class does not implement any interfaces.
*/
ClassTypeAlias(Comment comment, List<Annotation> metadata, Token keyword,
SimpleIdentifier name, TypeParameterList typeParameters, this.equals,
@@ -4739,16 +4501,13 @@
_name != null ? (_name.staticElement as ClassElement) : null;
/**
- * Return the implements clause for this class, or `null` if there is no implements clause.
- *
- * @return the implements clause for this class
+ * Return the implements clause for this class, or `null` if there is no
+ * implements clause.
*/
ImplementsClause get implementsClause => _implementsClause;
/**
- * Set the implements clause for this class to the given implements clause.
- *
- * @param implementsClause the implements clause for this class
+ * Set the implements clause for this class to the given [implementsClause].
*/
void set implementsClause(ImplementsClause implementsClause) {
_implementsClause = becomeParentOf(implementsClause);
@@ -4756,22 +4515,16 @@
/**
* Return `true` if this class is declared to be an abstract class.
- *
- * @return `true` if this class is declared to be an abstract class
*/
bool get isAbstract => abstractKeyword != null;
/**
* Return the name of the class being declared.
- *
- * @return the name of the class being declared
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the class being declared to the given identifier.
- *
- * @param name the name of the class being declared
+ * Set the name of the class being declared to the given [identifier].
*/
void set name(SimpleIdentifier name) {
_name = becomeParentOf(name);
@@ -4779,32 +4532,25 @@
/**
* Return the name of the superclass of the class being declared.
- *
- * @return the name of the superclass of the class being declared
*/
TypeName get superclass => _superclass;
/**
- * Set the name of the superclass of the class being declared to the given name.
- *
- * @param superclass the name of the superclass of the class being declared
+ * Set the name of the superclass of the class being declared to the given
+ * [superclass] name.
*/
void set superclass(TypeName superclass) {
_superclass = becomeParentOf(superclass);
}
/**
- * Return the type parameters for the class, or `null` if the class does not have any type
- * parameters.
- *
- * @return the type parameters for the class
+ * Return the type parameters for the class, or `null` if the class does not
+ * have any type parameters.
*/
TypeParameterList get typeParameters => _typeParameters;
/**
- * Set the type parameters for the class to the given list of parameters.
- *
- * @param typeParameters the type parameters for the class
+ * Set the type parameters for the class to the given list of [typeParameters].
*/
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = becomeParentOf(typeParameters);
@@ -4812,15 +4558,11 @@
/**
* Return the with clause for this class.
- *
- * @return the with clause for this class
*/
WithClause get withClause => _withClause;
/**
- * Set the with clause for this class to the given with clause.
- *
- * @param withClause the with clause for this class
+ * Set the with clause for this class to the given with [withClause].
*/
void set withClause(WithClause withClause) {
_withClause = becomeParentOf(withClause);
@@ -4832,35 +4574,30 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_typeParameters, visitor);
- safelyVisitChild(_superclass, visitor);
- safelyVisitChild(_withClause, visitor);
- safelyVisitChild(_implementsClause, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_typeParameters, visitor);
+ _safelyVisitChild(_superclass, visitor);
+ _safelyVisitChild(_withClause, visitor);
+ _safelyVisitChild(_implementsClause, visitor);
}
}
/**
- * Instances of the class `Combinator` represent the combinator associated with an import
- * directive.
+ * A combinator associated with an import or export directive.
*
- * <pre>
- * combinator ::=
- * [HideCombinator]
- * | [ShowCombinator]
- * </pre>
+ * > combinator ::=
+ * > [HideCombinator]
+ * > | [ShowCombinator]
*/
abstract class Combinator extends AstNode {
/**
- * The keyword specifying what kind of processing is to be done on the imported names.
+ * The keyword specifying what kind of processing is to be done on the
+ * imported names.
*/
Token keyword;
/**
* Initialize a newly created import combinator.
- *
- * @param keyword the keyword specifying what kind of processing is to be done on the imported
- * names
*/
Combinator(this.keyword);
@@ -4869,24 +4606,22 @@
}
/**
- * Instances of the class `Comment` represent a comment within the source code.
+ * A comment within the source code.
*
- * <pre>
- * comment ::=
- * endOfLineComment
- * | blockComment
- * | documentationComment
- *
- * endOfLineComment ::=
- * '//' (CHARACTER - EOL)* EOL
- *
- * blockComment ::=
- * '/ *' CHARACTER* '*/'
- *
- * documentationComment ::=
- * '/ **' (CHARACTER | [CommentReference])* '*/'
- * | ('///' (CHARACTER - EOL)* EOL)+
- * </pre>
+ * > comment ::=
+ * > endOfLineComment
+ * > | blockComment
+ * > | documentationComment
+ * >
+ * > endOfLineComment ::=
+ * > '//' (CHARACTER - EOL)* EOL
+ * >
+ * > blockComment ::=
+ * > '/ *' CHARACTER* '*/'
+ * >
+ * > documentationComment ::=
+ * > '/ **' (CHARACTER | [CommentReference])* '*/'
+ * > | ('///' (CHARACTER - EOL)* EOL)+
*/
class Comment extends AstNode {
/**
@@ -4900,17 +4635,17 @@
final CommentType _type;
/**
- * The references embedded within the documentation comment. This list will be empty unless this
- * is a documentation comment that has references embedded within it.
+ * The references embedded within the documentation comment. This list will be
+ * empty unless this is a documentation comment that has references embedded
+ * within it.
*/
NodeList<CommentReference> _references;
/**
- * Initialize a newly created comment.
- *
- * @param tokens the tokens representing the comment
- * @param type the type of the comment
- * @param references the references embedded within the documentation comment
+ * Initialize a newly created comment. The list of [tokens] must contain at
+ * least one token. The [type] is the type of the comment. The list of
+ * [references] can be empty if the comment does not contain any embedded
+ * references.
*/
Comment(this.tokens, this._type, List<CommentReference> references) {
_references = new NodeList<CommentReference>(this, references);
@@ -4927,29 +4662,21 @@
/**
* Return `true` if this is a block comment.
- *
- * @return `true` if this is a block comment
*/
bool get isBlock => _type == CommentType.BLOCK;
/**
* Return `true` if this is a documentation comment.
- *
- * @return `true` if this is a documentation comment
*/
bool get isDocumentation => _type == CommentType.DOCUMENTATION;
/**
* Return `true` if this is an end-of-line comment.
- *
- * @return `true` if this is an end-of-line comment
*/
bool get isEndOfLine => _type == CommentType.END_OF_LINE;
/**
* Return the references embedded within the documentation comment.
- *
- * @return the references embedded within the documentation comment
*/
NodeList<CommentReference> get references => _references;
@@ -4962,56 +4689,42 @@
}
/**
- * Create a block comment.
- *
- * @param tokens the tokens representing the comment
- * @return the block comment that was created
+ * Create a block comment consisting of the given [tokens].
*/
static Comment createBlockComment(List<Token> tokens) =>
new Comment(tokens, CommentType.BLOCK, null);
/**
- * Create a documentation comment.
- *
- * @param tokens the tokens representing the comment
- * @return the documentation comment that was created
+ * Create a documentation comment consisting of the given [tokens].
*/
static Comment createDocumentationComment(List<Token> tokens) =>
new Comment(tokens, CommentType.DOCUMENTATION, new List<CommentReference>());
/**
- * Create a documentation comment.
- *
- * @param tokens the tokens representing the comment
- * @param references the references embedded within the documentation comment
- * @return the documentation comment that was created
+ * Create a documentation comment consisting of the given [tokens] and having
+ * the given [references] embedded within it.
*/
static Comment createDocumentationCommentWithReferences(List<Token> tokens,
List<CommentReference> references) =>
new Comment(tokens, CommentType.DOCUMENTATION, references);
/**
- * Create an end-of-line comment.
- *
- * @param tokens the tokens representing the comment
- * @return the end-of-line comment that was created
+ * Create an end-of-line comment consisting of the given [tokens].
*/
static Comment createEndOfLineComment(List<Token> tokens) =>
new Comment(tokens, CommentType.END_OF_LINE, null);
}
/**
- * Instances of the class `CommentReference` represent a reference to a Dart element that is
- * found within a documentation comment.
+ * A reference to a Dart element that is found within a documentation comment.
*
- * <pre>
- * commentReference ::=
- * '[' 'new'? [Identifier] ']'
- * </pre>
+ * > commentReference ::=
+ * > '[' 'new'? [Identifier] ']'
*/
class CommentReference extends AstNode {
/**
- * The token representing the 'new' keyword, or `null` if there was no 'new' keyword.
+ * The token representing the 'new' keyword, or `null` if there was no 'new'
+ * keyword.
*/
Token newKeyword;
@@ -5021,10 +4734,8 @@
Identifier _identifier;
/**
- * Initialize a newly created reference to a Dart element.
- *
- * @param newKeyword the token representing the 'new' keyword
- * @param identifier the identifier being referenced
+ * Initialize a newly created reference to a Dart element. The [newKeyword]
+ * can be `null` if the reference is not to a constructor.
*/
CommentReference(this.newKeyword, Identifier identifier) {
_identifier = becomeParentOf(identifier);
@@ -5043,15 +4754,11 @@
/**
* Return the identifier being referenced.
- *
- * @return the identifier being referenced
*/
Identifier get identifier => _identifier;
/**
- * Set the identifier being referenced to the given identifier.
- *
- * @param identifier the identifier being referenced
+ * Set the identifier being referenced to the given [identifier].
*/
void set identifier(Identifier identifier) {
_identifier = becomeParentOf(identifier);
@@ -5062,13 +4769,12 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_identifier, visitor);
+ _safelyVisitChild(_identifier, visitor);
}
}
/**
- * The enumeration `CommentType` encodes all the different types of comments
- * that are recognized by the parser.
+ * The possible types of comments that are recognized by the parser.
*/
class CommentType {
/**
@@ -5101,38 +4807,38 @@
}
/**
- * Instances of the class `CompilationUnit` represent a compilation unit.
+ * A compilation unit.
*
- * While the grammar restricts the order of the directives and declarations within a compilation
- * unit, this class does not enforce those restrictions. In particular, the children of a
- * compilation unit will be visited in lexical order even if lexical order does not conform to the
- * restrictions of the grammar.
+ * While the grammar restricts the order of the directives and declarations
+ * within a compilation unit, this class does not enforce those restrictions.
+ * In particular, the children of a compilation unit will be visited in lexical
+ * order even if lexical order does not conform to the restrictions of the
+ * grammar.
*
- * <pre>
- * compilationUnit ::=
- * directives declarations
- *
- * directives ::=
- * [ScriptTag]? [LibraryDirective]? namespaceDirective* [PartDirective]*
- * | [PartOfDirective]
- *
- * namespaceDirective ::=
- * [ImportDirective]
- * | [ExportDirective]
- *
- * declarations ::=
- * [CompilationUnitMember]*
- * </pre>
+ * > compilationUnit ::=
+ * > directives declarations
+ * >
+ * > directives ::=
+ * > [ScriptTag]? [LibraryDirective]? namespaceDirective* [PartDirective]*
+ * > | [PartOfDirective]
+ * >
+ * > namespaceDirective ::=
+ * > [ImportDirective]
+ * > | [ExportDirective]
+ * >
+ * > declarations ::=
+ * > [CompilationUnitMember]*
*/
class CompilationUnit extends AstNode {
/**
- * The first token in the token stream that was parsed to form this compilation unit.
+ * The first token in the token stream that was parsed to form this
+ * compilation unit.
*/
Token beginToken;
/**
- * The script tag at the beginning of the compilation unit, or `null` if there is no script
- * tag in this compilation unit.
+ * The script tag at the beginning of the compilation unit, or `null` if there
+ * is no script tag in this compilation unit.
*/
ScriptTag _scriptTag;
@@ -5147,14 +4853,14 @@
NodeList<CompilationUnitMember> _declarations;
/**
- * The last token in the token stream that was parsed to form this compilation unit. This token
- * should always have a type of [TokenType.EOF].
+ * The last token in the token stream that was parsed to form this compilation
+ * unit. This token should always have a type of [TokenType.EOF].
*/
final Token endToken;
/**
- * The element associated with this compilation unit, or `null` if the AST structure has not
- * been resolved.
+ * The element associated with this compilation unit, or `null` if the AST
+ * structure has not been resolved.
*/
CompilationUnitElement element;
@@ -5164,13 +4870,11 @@
LineInfo lineInfo;
/**
- * Initialize a newly created compilation unit to have the given directives and declarations.
- *
- * @param beginToken the first token in the token stream
- * @param scriptTag the script tag at the beginning of the compilation unit
- * @param directives the directives contained in this compilation unit
- * @param declarations the declarations contained in this compilation unit
- * @param endToken the last token in the token stream
+ * Initialize a newly created compilation unit to have the given directives
+ * and declarations. The [scriptTag] can be `null` if there is no script tag
+ * in the compilation unit. The list of [directives] can be `null` if there
+ * are no directives in the compilation unit. The list of [declarations] can
+ * be `null` if there are no declarations in the compilation unit.
*/
CompilationUnit(this.beginToken, ScriptTag scriptTag,
List<Directive> directives, List<CompilationUnitMember> declarations,
@@ -5195,15 +4899,11 @@
/**
* Return the declarations contained in this compilation unit.
- *
- * @return the declarations contained in this compilation unit
*/
NodeList<CompilationUnitMember> get declarations => _declarations;
/**
* Return the directives contained in this compilation unit.
- *
- * @return the directives contained in this compilation unit
*/
NodeList<Directive> get directives => _directives;
@@ -5220,28 +4920,22 @@
int get offset => 0;
/**
- * Return the script tag at the beginning of the compilation unit, or `null` if there is no
- * script tag in this compilation unit.
- *
- * @return the script tag at the beginning of the compilation unit
+ * Return the script tag at the beginning of the compilation unit, or `null`
+ * if there is no script tag in this compilation unit.
*/
ScriptTag get scriptTag => _scriptTag;
/**
- * Set the script tag at the beginning of the compilation unit to the given script tag.
- *
- * @param scriptTag the script tag at the beginning of the compilation unit
+ * Set the script tag at the beginning of the compilation unit to the given
+ * [scriptTag].
*/
void set scriptTag(ScriptTag scriptTag) {
_scriptTag = becomeParentOf(scriptTag);
}
/**
- * Return an array containing all of the directives and declarations in this compilation unit,
- * sorted in lexical order.
- *
- * @return the directives and declarations in this compilation unit in the order in which they
- * appeared in the original source
+ * Return a list containing all of the directives and declarations in this
+ * compilation unit, sorted in lexical order.
*/
List<AstNode> get sortedDirectivesAndDeclarations {
return <AstNode>[]
@@ -5255,7 +4949,7 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_scriptTag, visitor);
+ _safelyVisitChild(_scriptTag, visitor);
if (_directivesAreBeforeDeclarations()) {
_directives.accept(visitor);
_declarations.accept(visitor);
@@ -5267,9 +4961,8 @@
}
/**
- * Return `true` if all of the directives are lexically before any declarations.
- *
- * @return `true` if all of the directives are lexically before any declarations
+ * Return `true` if all of the directives are lexically before any
+ * declarations.
*/
bool _directivesAreBeforeDeclarations() {
if (_directives.isEmpty || _declarations.isEmpty) {
@@ -5282,37 +4975,31 @@
}
/**
- * Instances of the class `CompilationUnitMember` defines the behavior common to nodes that
- * declare a name within the scope of a compilation unit.
+ * A node that declares a name within the scope of a compilation unit.
*
- * <pre>
- * compilationUnitMember ::=
- * [ClassDeclaration]
- * | [TypeAlias]
- * | [FunctionDeclaration]
- * | [MethodDeclaration]
- * | [VariableDeclaration]
- * | [VariableDeclaration]
- * </pre>
+ * > compilationUnitMember ::=
+ * > [ClassDeclaration]
+ * > | [TypeAlias]
+ * > | [FunctionDeclaration]
+ * > | [MethodDeclaration]
+ * > | [VariableDeclaration]
+ * > | [VariableDeclaration]
*/
abstract class CompilationUnitMember extends Declaration {
/**
- * Initialize a newly created generic compilation unit member.
- *
- * @param comment the documentation comment associated with this member
- * @param metadata the annotations associated with this member
+ * Initialize a newly created generic compilation unit member. Either or both
+ * of the [comment] and [metadata] can be `null` if the member does not have
+ * the corresponding attribute.
*/
CompilationUnitMember(Comment comment, List<Annotation> metadata)
: super(comment, metadata);
}
/**
- * Instances of the class `ConditionalExpression` represent a conditional expression.
+ * A conditional expression.
*
- * <pre>
- * conditionalExpression ::=
- * [Expression] '?' [Expression] ':' [Expression]
- * </pre>
+ * > conditionalExpression ::=
+ * > [Expression] '?' [Expression] ':' [Expression]
*/
class ConditionalExpression extends Expression {
/**
@@ -5342,14 +5029,6 @@
/**
* Initialize a newly created conditional expression.
- *
- * @param condition the condition used to determine which expression is executed next
- * @param question the token used to separate the condition from the then expression
- * @param thenExpression the expression that is executed if the condition evaluates to
- * `true`
- * @param colon the token used to separate the then expression from the else expression
- * @param elseExpression the expression that is executed if the condition evaluates to
- * `false`
*/
ConditionalExpression(Expression condition, this.question,
Expression thenExpression, this.colon, Expression elseExpression) {
@@ -5373,34 +5052,28 @@
..add(_elseExpression);
/**
- * Return the condition used to determine which of the expressions is executed next.
- *
- * @return the condition used to determine which expression is executed next
+ * Return the condition used to determine which of the expressions is executed
+ * next.
*/
Expression get condition => _condition;
/**
- * Set the condition used to determine which of the expressions is executed next to the given
- * expression.
- *
- * @param expression the condition used to determine which expression is executed next
+ * Set the condition used to determine which of the expressions is executed
+ * next to the given [expression].
*/
void set condition(Expression expression) {
_condition = becomeParentOf(expression);
}
/**
- * Return the expression that is executed if the condition evaluates to `false`.
- *
- * @return the expression that is executed if the condition evaluates to `false`
+ * Return the expression that is executed if the condition evaluates to
+ * `false`.
*/
Expression get elseExpression => _elseExpression;
/**
- * Set the expression that is executed if the condition evaluates to `false` to the given
- * expression.
- *
- * @param expression the expression that is executed if the condition evaluates to `false`
+ * Set the expression that is executed if the condition evaluates to `false`
+ * to the given [expression].
*/
void set elseExpression(Expression expression) {
_elseExpression = becomeParentOf(expression);
@@ -5413,17 +5086,14 @@
int get precedence => 3;
/**
- * Return the expression that is executed if the condition evaluates to `true`.
- *
- * @return the expression that is executed if the condition evaluates to `true`
+ * Return the expression that is executed if the condition evaluates to
+ * `true`.
*/
Expression get thenExpression => _thenExpression;
/**
- * Set the expression that is executed if the condition evaluates to `true` to the given
- * expression.
- *
- * @param expression the expression that is executed if the condition evaluates to `true`
+ * Set the expression that is executed if the condition evaluates to `true` to
+ * the given [expression].
*/
void set thenExpression(Expression expression) {
_thenExpression = becomeParentOf(expression);
@@ -5434,53 +5104,56 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_condition, visitor);
- safelyVisitChild(_thenExpression, visitor);
- safelyVisitChild(_elseExpression, visitor);
+ _safelyVisitChild(_condition, visitor);
+ _safelyVisitChild(_thenExpression, visitor);
+ _safelyVisitChild(_elseExpression, visitor);
}
}
/**
- * Instances of the class `ConstantEvaluator` evaluate constant expressions to produce their
- * compile-time value. According to the Dart Language Specification: <blockquote> A constant
- * expression is one of the following:
+ * An object that can be used to evaluate constant expressions to produce their
+ * compile-time value. According to the Dart Language Specification:
+ * <blockquote>A constant expression is one of the following:
* * A literal number.
* * A literal boolean.
- * * A literal string where any interpolated expression is a compile-time constant that evaluates
- * to a numeric, string or boolean value or to `null`.
+ * * A literal string where any interpolated expression is a compile-time
+ * constant that evaluates to a numeric, string or boolean value or to `null`.
* * `null`.
* * A reference to a static constant variable.
- * * An identifier expression that denotes a constant variable, a class or a type parameter.
+ * * An identifier expression that denotes a constant variable, a class or a
+ * type parameter.
* * A constant constructor invocation.
* * A constant list literal.
* * A constant map literal.
- * * A simple or qualified identifier denoting a top-level function or a static method.
+ * * A simple or qualified identifier denoting a top-level function or a static
+ * method.
* * A parenthesized expression `(e)` where `e` is a constant expression.
* * An expression of one of the forms `identical(e1, e2)`, `e1 == e2`,
- * `e1 != e2` where `e1` and `e2` are constant expressions that evaluate to a
- * numeric, string or boolean value or to `null`.
+ * `e1 != e2` where `e1` and `e2` are constant expressions that evaluate to a
+ * numeric, string or boolean value or to `null`.
* * An expression of one of the forms `!e`, `e1 && e2` or `e1 || e2`, where
- * `e`, `e1` and `e2` are constant expressions that evaluate to a boolean value or
- * to `null`.
- * * An expression of one of the forms `~e`, `e1 ^ e2`, `e1 & e2`,
- * `e1 | e2`, `e1 >> e2` or `e1 << e2`, where `e`, `e1` and `e2`
- * are constant expressions that evaluate to an integer value or to `null`.
- * * An expression of one of the forms `-e`, `e1 + e2`, `e1 - e2`,
- * `e1 * e2`, `e1 / e2`, `e1 ~/ e2`, `e1 > e2`, `e1 < e2`,
- * `e1 >= e2`, `e1 <= e2` or `e1 % e2`, where `e`, `e1` and `e2`
- * are constant expressions that evaluate to a numeric value or to `null`.
- * </blockquote> The values returned by instances of this class are therefore `null` and
+ * `e`, `e1` and `e2` are constant expressions that evaluate to a boolean
+ * value or to `null`.
+ * * An expression of one of the forms `~e`, `e1 ^ e2`, `e1 & e2`, `e1 | e2`,
+ * `e1 >> e2` or `e1 << e2`, where `e`, `e1` and `e2` are constant expressions
+ * that evaluate to an integer value or to `null`.
+ * * An expression of one of the forms `-e`, `e1 + e2`, `e1 - e2`, `e1 * e2`,
+ * `e1 / e2`, `e1 ~/ e2`, `e1 > e2`, `e1 < e2`, `e1 >= e2`, `e1 <= e2` or
+ * `e1 % e2`, where `e`, `e1` and `e2` are constant expressions that evaluate
+ * to a numeric value or to `null`.
+ * </blockquote>
+ * The values returned by instances of this class are therefore `null` and
* instances of the classes `Boolean`, `BigInteger`, `Double`, `String`, and
* `DartObject`.
*
- * In addition, this class defines several values that can be returned to indicate various
- * conditions encountered during evaluation. These are documented with the static field that define
- * those values.
+ * In addition, this class defines several values that can be returned to
+ * indicate various conditions encountered during evaluation. These are
+ * documented with the static fields that define those values.
*/
class ConstantEvaluator extends GeneralizingAstVisitor<Object> {
/**
- * The value returned for expressions (or non-expression nodes) that are not compile-time constant
- * expressions.
+ * The value returned for expressions (or non-expression nodes) that are not
+ * compile-time constant expressions.
*/
static Object NOT_A_CONSTANT = new Object();
@@ -5789,10 +5462,8 @@
}
/**
- * Return the constant value of the static constant represented by the given element.
- *
- * @param element the element whose value is to be returned
- * @return the constant value of the static constant
+ * Return the constant value of the static constant represented by the given
+ * [element].
*/
Object _getConstantValue(Element element) {
// TODO(brianwilkerson) Implement this
@@ -5812,60 +5483,61 @@
}
/**
- * Instances of the class `ConstructorDeclaration` represent a constructor declaration.
+ * A constructor declaration.
*
- * <pre>
- * constructorDeclaration ::=
- * constructorSignature [FunctionBody]?
- * | constructorName formalParameterList ':' 'this' ('.' [SimpleIdentifier])? arguments
- *
- * constructorSignature ::=
- * 'external'? constructorName formalParameterList initializerList?
- * | 'external'? 'factory' factoryName formalParameterList initializerList?
- * | 'external'? 'const' constructorName formalParameterList initializerList?
- *
- * constructorName ::=
- * [SimpleIdentifier] ('.' [SimpleIdentifier])?
- *
- * factoryName ::=
- * [Identifier] ('.' [SimpleIdentifier])?
- *
- * initializerList ::=
- * ':' [ConstructorInitializer] (',' [ConstructorInitializer])*
- * </pre>
+ * > constructorDeclaration ::=
+ * > constructorSignature [FunctionBody]?
+ * > | constructorName formalParameterList ':' 'this' ('.' [SimpleIdentifier])? arguments
+ * >
+ * > constructorSignature ::=
+ * > 'external'? constructorName formalParameterList initializerList?
+ * > | 'external'? 'factory' factoryName formalParameterList initializerList?
+ * > | 'external'? 'const' constructorName formalParameterList initializerList?
+ * >
+ * > constructorName ::=
+ * > [SimpleIdentifier] ('.' [SimpleIdentifier])?
+ * >
+ * > factoryName ::=
+ * > [Identifier] ('.' [SimpleIdentifier])?
+ * >
+ * > initializerList ::=
+ * > ':' [ConstructorInitializer] (',' [ConstructorInitializer])*
*/
class ConstructorDeclaration extends ClassMember {
/**
- * The token for the 'external' keyword, or `null` if the constructor is not external.
+ * The token for the 'external' keyword, or `null` if the constructor is not
+ * external.
*/
Token externalKeyword;
/**
- * The token for the 'const' keyword, or `null` if the constructor is not a const
- * constructor.
+ * The token for the 'const' keyword, or `null` if the constructor is not a
+ * const constructor.
*/
Token constKeyword;
/**
- * The token for the 'factory' keyword, or `null` if the constructor is not a factory
- * constructor.
+ * The token for the 'factory' keyword, or `null` if the constructor is not a
+ * factory constructor.
*/
Token factoryKeyword;
/**
- * The type of object being created. This can be different than the type in which the constructor
- * is being declared if the constructor is the implementation of a factory constructor.
+ * The type of object being created. This can be different than the type in
+ * which the constructor is being declared if the constructor is the
+ * implementation of a factory constructor.
*/
Identifier _returnType;
/**
- * The token for the period before the constructor name, or `null` if the constructor being
- * declared is unnamed.
+ * The token for the period before the constructor name, or `null` if the
+ * constructor being declared is unnamed.
*/
Token period;
/**
- * The name of the constructor, or `null` if the constructor being declared is unnamed.
+ * The name of the constructor, or `null` if the constructor being declared is
+ * unnamed.
*/
SimpleIdentifier _name;
@@ -5875,8 +5547,8 @@
FormalParameterList _parameters;
/**
- * The token for the separator (colon or equals) before the initializer list or redirection, or
- * `null` if there are no initializers.
+ * The token for the separator (colon or equals) before the initializer list
+ * or redirection, or `null` if there are no initializers.
*/
Token separator;
@@ -5886,39 +5558,38 @@
NodeList<ConstructorInitializer> _initializers;
/**
- * The name of the constructor to which this constructor will be redirected, or `null` if
- * this is not a redirecting factory constructor.
+ * The name of the constructor to which this constructor will be redirected,
+ * or `null` if this is not a redirecting factory constructor.
*/
ConstructorName _redirectedConstructor;
/**
- * The body of the constructor, or `null` if the constructor does not have a body.
+ * The body of the constructor, or `null` if the constructor does not have a
+ * body.
*/
FunctionBody _body;
/**
- * The element associated with this constructor, or `null` if the AST structure has not been
- * resolved or if this constructor could not be resolved.
+ * The element associated with this constructor, or `null` if the AST
+ * structure has not been resolved or if this constructor could not be
+ * resolved.
*/
ConstructorElement element;
/**
- * Initialize a newly created constructor declaration.
- *
- * @param externalKeyword the token for the 'external' keyword
- * @param comment the documentation comment associated with this constructor
- * @param metadata the annotations associated with this constructor
- * @param constKeyword the token for the 'const' keyword
- * @param factoryKeyword the token for the 'factory' keyword
- * @param returnType the return type of the constructor
- * @param period the token for the period before the constructor name
- * @param name the name of the constructor
- * @param parameters the parameters associated with the constructor
- * @param separator the token for the colon or equals before the initializers
- * @param initializers the initializers associated with the constructor
- * @param redirectedConstructor the name of the constructor to which this constructor will be
- * redirected
- * @param body the body of the constructor
+ * Initialize a newly created constructor declaration. The [externalKeyword]
+ * can be `null` if the constructor is not external. Either or both of the
+ * [comment] and [metadata] can be `null` if the constructor does not have the
+ * corresponding attribute. The [constKeyword] can be `null` if the
+ * constructor cannot be used to create a constant. The [factoryKeyword] can
+ * be `null` if the constructor is not a factory. The [period] and [name] can
+ * both be `null` if the constructor is not a named constructor. The
+ * [separator] can be `null` if the constructor does not have any initializers
+ * and does not redirect to a different constructor. The list of
+ * [initializers] can be `null` if the constructor does not have any
+ * initializers. The [redirectedConstructor] can be `null` if the constructor
+ * does not redirect to a different constructor. The [body] can be `null` if
+ * the constructor does not have a body.
*/
ConstructorDeclaration(Comment comment, List<Annotation> metadata,
this.externalKeyword, this.constKeyword, this.factoryKeyword,
@@ -5936,16 +5607,13 @@
}
/**
- * Return the body of the constructor, or `null` if the constructor does not have a body.
- *
- * @return the body of the constructor
+ * Return the body of the constructor, or `null` if the constructor does not
+ * have a body.
*/
FunctionBody get body => _body;
/**
- * Set the body of the constructor to the given function body.
- *
- * @param functionBody the body of the constructor
+ * Set the body of the constructor to the given [functionBody].
*/
void set body(FunctionBody functionBody) {
_body = becomeParentOf(functionBody);
@@ -5987,23 +5655,17 @@
/**
* Return the initializers associated with the constructor.
- *
- * @return the initializers associated with the constructor
*/
NodeList<ConstructorInitializer> get initializers => _initializers;
/**
- * Return the name of the constructor, or `null` if the constructor being declared is
- * unnamed.
- *
- * @return the name of the constructor
+ * Return the name of the constructor, or `null` if the constructor being
+ * declared is unnamed.
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the constructor to the given identifier.
- *
- * @param identifier the name of the constructor
+ * Set the name of the constructor to the given [identifier].
*/
void set name(SimpleIdentifier identifier) {
_name = becomeParentOf(identifier);
@@ -6011,52 +5673,40 @@
/**
* Return the parameters associated with the constructor.
- *
- * @return the parameters associated with the constructor
*/
FormalParameterList get parameters => _parameters;
/**
- * Set the parameters associated with the constructor to the given list of parameters.
- *
- * @param parameters the parameters associated with the constructor
+ * Set the parameters associated with the constructor to the given list of
+ * [parameters].
*/
void set parameters(FormalParameterList parameters) {
_parameters = becomeParentOf(parameters);
}
/**
- * Return the name of the constructor to which this constructor will be redirected, or
- * `null` if this is not a redirecting factory constructor.
- *
- * @return the name of the constructor to which this constructor will be redirected
+ * Return the name of the constructor to which this constructor will be
+ * redirected, or `null` if this is not a redirecting factory constructor.
*/
ConstructorName get redirectedConstructor => _redirectedConstructor;
/**
- * Set the name of the constructor to which this constructor will be redirected to the given
- * constructor name.
- *
- * @param redirectedConstructor the name of the constructor to which this constructor will be
- * redirected
+ * Set the name of the constructor to which this constructor will be
+ * redirected to the given [redirectedConstructor] name.
*/
void set redirectedConstructor(ConstructorName redirectedConstructor) {
_redirectedConstructor = becomeParentOf(redirectedConstructor);
}
/**
- * Return the type of object being created. This can be different than the type in which the
- * constructor is being declared if the constructor is the implementation of a factory
- * constructor.
- *
- * @return the type of object being created
+ * Return the type of object being created. This can be different than the
+ * type in which the constructor is being declared if the constructor is the
+ * implementation of a factory constructor.
*/
Identifier get returnType => _returnType;
/**
- * Set the type of object being created to the given type name.
- *
- * @param typeName the type of object being created
+ * Set the type of object being created to the given [typeName].
*/
void set returnType(Identifier typeName) {
_returnType = becomeParentOf(typeName);
@@ -6068,23 +5718,20 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_returnType, visitor);
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_parameters, visitor);
+ _safelyVisitChild(_returnType, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_parameters, visitor);
_initializers.accept(visitor);
- safelyVisitChild(_redirectedConstructor, visitor);
- safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_redirectedConstructor, visitor);
+ _safelyVisitChild(_body, visitor);
}
}
/**
- * Instances of the class `ConstructorFieldInitializer` represent the initialization of a
- * field within a constructor's initialization list.
+ * The initialization of a field within a constructor's initialization list.
*
- * <pre>
- * fieldInitializer ::=
- * ('this' '.')? [SimpleIdentifier] '=' [Expression]
- * </pre>
+ * > fieldInitializer ::=
+ * > ('this' '.')? [SimpleIdentifier] '=' [Expression]
*/
class ConstructorFieldInitializer extends ConstructorInitializer {
/**
@@ -6093,8 +5740,8 @@
Token keyword;
/**
- * The token for the period after the 'this' keyword, or `null` if there is no 'this'
- * keyword.
+ * The token for the period after the 'this' keyword, or `null` if there is no
+ * 'this' keyword.
*/
Token period;
@@ -6114,14 +5761,9 @@
Expression _expression;
/**
- * Initialize a newly created field initializer to initialize the field with the given name to the
- * value of the given expression.
- *
- * @param keyword the token for the 'this' keyword
- * @param period the token for the period after the 'this' keyword
- * @param fieldName the name of the field being initialized
- * @param equals the token for the equal sign between the field name and the expression
- * @param expression the expression computing the value to which the field will be initialized
+ * Initialize a newly created field initializer to initialize the field with
+ * the given name to the value of the given expression. The [keyword] and
+ * [period] can be `null` if the 'this' keyword was not specified.
*/
ConstructorFieldInitializer(this.keyword, this.period,
SimpleIdentifier fieldName, this.equals, Expression expression) {
@@ -6149,17 +5791,14 @@
Token get endToken => _expression.endToken;
/**
- * Return the expression computing the value to which the field will be initialized.
- *
- * @return the expression computing the value to which the field will be initialized
+ * Return the expression computing the value to which the field will be
+ * initialized.
*/
Expression get expression => _expression;
/**
- * Set the expression computing the value to which the field will be initialized to the given
- * expression.
- *
- * @param expression the expression computing the value to which the field will be initialized
+ * Set the expression computing the value to which the field will be
+ * initialized to the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -6167,15 +5806,11 @@
/**
* Return the name of the field being initialized.
- *
- * @return the name of the field being initialized
*/
SimpleIdentifier get fieldName => _fieldName;
/**
- * Set the name of the field being initialized to the given identifier.
- *
- * @param identifier the name of the field being initialized
+ * Set the name of the field being initialized to the given [identifier].
*/
void set fieldName(SimpleIdentifier identifier) {
_fieldName = becomeParentOf(identifier);
@@ -6186,31 +5821,26 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_fieldName, visitor);
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_fieldName, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * Instances of the class `ConstructorInitializer` defines the behavior of nodes that can
- * occur in the initializer list of a constructor declaration.
+ * A node that can occur in the initializer list of a constructor declaration.
*
- * <pre>
- * constructorInitializer ::=
- * [SuperConstructorInvocation]
- * | [ConstructorFieldInitializer]
- * </pre>
+ * > constructorInitializer ::=
+ * > [SuperConstructorInvocation]
+ * > | [ConstructorFieldInitializer]
*/
abstract class ConstructorInitializer extends AstNode {
}
/**
- * Instances of the class `ConstructorName` represent the name of the constructor.
+ * The name of the constructor.
*
- * <pre>
- * constructorName:
- * type ('.' identifier)?
- * </pre>
+ * > constructorName ::=
+ * > type ('.' identifier)?
*/
class ConstructorName extends AstNode {
/**
@@ -6219,30 +5849,27 @@
TypeName _type;
/**
- * The token for the period before the constructor name, or `null` if the specified
- * constructor is the unnamed constructor.
+ * The token for the period before the constructor name, or `null` if the
+ * specified constructor is the unnamed constructor.
*/
Token period;
/**
- * The name of the constructor, or `null` if the specified constructor is the unnamed
- * constructor.
+ * The name of the constructor, or `null` if the specified constructor is the
+ * unnamed constructor.
*/
SimpleIdentifier _name;
/**
- * The element associated with this constructor name based on static type information, or
- * `null` if the AST structure has not been resolved or if this constructor name could not
- * be resolved.
+ * The element associated with this constructor name based on static type
+ * information, or `null` if the AST structure has not been resolved or if
+ * this constructor name could not be resolved.
*/
ConstructorElement staticElement;
/**
- * Initialize a newly created constructor name.
- *
- * @param type the name of the type defining the constructor
- * @param period the token for the period before the constructor name
- * @param name the name of the constructor
+ * Initialize a newly created constructor name. The [period] and [name] can be
+ * `null` if the constructor being named is the unnamed constructor.
*/
ConstructorName(TypeName type, this.period, SimpleIdentifier name) {
_type = becomeParentOf(type);
@@ -6267,17 +5894,13 @@
}
/**
- * Return the name of the constructor, or `null` if the specified constructor is the unnamed
- * constructor.
- *
- * @return the name of the constructor
+ * Return the name of the constructor, or `null` if the specified constructor
+ * is the unnamed constructor.
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the constructor to the given name.
- *
- * @param name the name of the constructor
+ * Set the name of the constructor to the given [name].
*/
void set name(SimpleIdentifier name) {
_name = becomeParentOf(name);
@@ -6285,15 +5908,11 @@
/**
* Return the name of the type defining the constructor.
- *
- * @return the name of the type defining the constructor
*/
TypeName get type => _type;
/**
- * Set the name of the type defining the constructor to the given type name.
- *
- * @param type the name of the type defining the constructor
+ * Set the name of the type defining the constructor to the given [type] name.
*/
void set type(TypeName type) {
_type = becomeParentOf(type);
@@ -6304,18 +5923,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_type, visitor);
- safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_type, visitor);
+ _safelyVisitChild(_name, visitor);
}
}
/**
- * Instances of the class `ContinueStatement` represent a continue statement.
+ * A continue statement.
*
- * <pre>
- * continueStatement ::=
- * 'continue' [SimpleIdentifier]? ';'
- * </pre>
+ * > continueStatement ::=
+ * > 'continue' [SimpleIdentifier]? ';'
*/
class ContinueStatement extends Statement {
/**
@@ -6344,11 +5961,8 @@
AstNode target;
/**
- * Initialize a newly created continue statement.
- *
- * @param keyword the token representing the 'continue' keyword
- * @param label the label associated with the statement
- * @param semicolon the semicolon terminating the statement
+ * Initialize a newly created continue statement. The [label] can be `null` if
+ * there is no label associated with the statement.
*/
ContinueStatement(this.keyword, SimpleIdentifier label, this.semicolon) {
_label = becomeParentOf(label);
@@ -6370,16 +5984,13 @@
Token get endToken => semicolon;
/**
- * Return the label associated with the statement, or `null` if there is no label.
- *
- * @return the label associated with the statement
+ * Return the label associated with the statement, or `null` if there is no
+ * label.
*/
SimpleIdentifier get label => _label;
/**
- * Set the label associated with the statement to the given label.
- *
- * @param identifier the label associated with the statement
+ * Set the label associated with the statement to the given [identifier].
*/
void set label(SimpleIdentifier identifier) {
_label = becomeParentOf(identifier);
@@ -6390,52 +6001,47 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_label, visitor);
+ _safelyVisitChild(_label, visitor);
}
}
/**
- * The abstract class `Declaration` defines the behavior common to nodes that represent the
- * declaration of a name. Each declared name is visible within a name scope.
+ * A node that represents the declaration of a name. Each declared name is
+ * visible within a name scope.
*/
abstract class Declaration extends AnnotatedNode {
/**
- * Initialize a newly created declaration.
- *
- * @param comment the documentation comment associated with this declaration
- * @param metadata the annotations associated with this declaration
+ * Initialize a newly created declaration. Either or both of the [comment] and
+ * [metadata] can be `null` if the declaration does not have the corresponding
+ * attribute.
*/
Declaration(Comment comment, List<Annotation> metadata)
: super(comment, metadata);
/**
- * Return the element associated with this declaration, or `null` if either this node
- * corresponds to a list of declarations or if the AST structure has not been resolved.
- *
- * @return the element associated with this declaration
+ * Return the element associated with this declaration, or `null` if either
+ * this node corresponds to a list of declarations or if the AST structure has
+ * not been resolved.
*/
Element get element;
}
/**
- * Instances of the class `DeclaredIdentifier` represent the declaration of a single
- * identifier.
+ * The declaration of a single identifier.
*
- * <pre>
- * declaredIdentifier ::=
- * [Annotation] finalConstVarOrType [SimpleIdentifier]
- * </pre>
+ * > declaredIdentifier ::=
+ * > [Annotation] finalConstVarOrType [SimpleIdentifier]
*/
class DeclaredIdentifier extends Declaration {
/**
- * The token representing either the 'final', 'const' or 'var' keyword, or `null` if no
- * keyword was used.
+ * The token representing either the 'final', 'const' or 'var' keyword, or
+ * `null` if no keyword was used.
*/
Token keyword;
/**
- * The name of the declared type of the parameter, or `null` if the parameter does not have
- * a declared type.
+ * The name of the declared type of the parameter, or `null` if the parameter
+ * does not have a declared type.
*/
TypeName _type;
@@ -6445,13 +6051,10 @@
SimpleIdentifier _identifier;
/**
- * Initialize a newly created formal parameter.
- *
- * @param comment the documentation comment associated with this parameter
- * @param metadata the annotations associated with this parameter
- * @param keyword the token representing either the 'final', 'const' or 'var' keyword
- * @param type the name of the declared type of the parameter
- * @param identifier the name of the parameter being declared
+ * Initialize a newly created formal parameter. Either or both of the
+ * [comment] and [metadata] can be `null` if the declaration does not have the
+ * corresponding attribute. The [keyword] can be `null` if a type name is
+ * given. The [type] must be `null` if the keyword is 'var'.
*/
DeclaredIdentifier(Comment comment, List<Annotation> metadata, this.keyword,
TypeName type, SimpleIdentifier identifier)
@@ -6492,15 +6095,11 @@
/**
* Return the name of the variable being declared.
- *
- * @return the name of the variable being declared
*/
SimpleIdentifier get identifier => _identifier;
/**
- * Set the name of the variable being declared to the given name.
- *
- * @param identifier the new name of the variable being declared
+ * Set the name of the variable being declared to the given [identifier].
*/
void set identifier(SimpleIdentifier identifier) {
_identifier = becomeParentOf(identifier);
@@ -6508,34 +6107,26 @@
/**
* Return `true` if this variable was declared with the 'const' modifier.
- *
- * @return `true` if this variable was declared with the 'const' modifier
*/
bool get isConst =>
(keyword is KeywordToken) && (keyword as KeywordToken).keyword == Keyword.CONST;
/**
- * Return `true` if this variable was declared with the 'final' modifier. Variables that are
- * declared with the 'const' modifier will return `false` even though they are implicitly
- * final.
- *
- * @return `true` if this variable was declared with the 'final' modifier
+ * Return `true` if this variable was declared with the 'final' modifier.
+ * Variables that are declared with the 'const' modifier will return `false`
+ * even though they are implicitly final.
*/
bool get isFinal =>
(keyword is KeywordToken) && (keyword as KeywordToken).keyword == Keyword.FINAL;
/**
- * Return the name of the declared type of the parameter, or `null` if the parameter does
- * not have a declared type.
- *
- * @return the name of the declared type of the parameter
+ * Return the name of the declared type of the parameter, or `null` if the
+ * parameter does not have a declared type.
*/
TypeName get type => _type;
/**
- * Set the name of the declared type of the parameter to the given type name.
- *
- * @param typeName the name of the declared type of the parameter
+ * Set the name of the declared type of the parameter to the given [typeName].
*/
void set type(TypeName typeName) {
_type = becomeParentOf(typeName);
@@ -6547,23 +6138,21 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_type, visitor);
- safelyVisitChild(_identifier, visitor);
+ _safelyVisitChild(_type, visitor);
+ _safelyVisitChild(_identifier, visitor);
}
}
/**
- * Instances of the class `DefaultFormalParameter` represent a formal parameter with a default
- * value. There are two kinds of parameters that are both represented by this class: named formal
- * parameters and positional formal parameters.
+ * A formal parameter with a default value. There are two kinds of parameters
+ * that are both represented by this class: named formal parameters and
+ * positional formal parameters.
*
- * <pre>
- * defaultFormalParameter ::=
- * [NormalFormalParameter] ('=' [Expression])?
- *
- * defaultNamedParameter ::=
- * [NormalFormalParameter] (':' [Expression])?
- * </pre>
+ * > defaultFormalParameter ::=
+ * > [NormalFormalParameter] ('=' [Expression])?
+ * >
+ * > defaultNamedParameter ::=
+ * > [NormalFormalParameter] (':' [Expression])?
*/
class DefaultFormalParameter extends FormalParameter {
/**
@@ -6577,24 +6166,20 @@
ParameterKind kind;
/**
- * The token separating the parameter from the default value, or `null` if there is no
- * default value.
+ * The token separating the parameter from the default value, or `null` if
+ * there is no default value.
*/
Token separator;
/**
- * The expression computing the default value for the parameter, or `null` if there is no
- * default value.
+ * The expression computing the default value for the parameter, or `null` if
+ * there is no default value.
*/
Expression _defaultValue;
/**
- * Initialize a newly created default formal parameter.
- *
- * @param parameter the formal parameter with which the default value is associated
- * @param kind the kind of this parameter
- * @param separator the token separating the parameter from the default value
- * @param defaultValue the expression computing the default value for the parameter
+ * Initialize a newly created default formal parameter. The [separator] and
+ * [defaultValue] can be `null` if there is no default value.
*/
DefaultFormalParameter(NormalFormalParameter parameter, this.kind,
this.separator, Expression defaultValue) {
@@ -6615,17 +6200,14 @@
..add(_defaultValue);
/**
- * Return the expression computing the default value for the parameter, or `null` if there
- * is no default value.
- *
- * @return the expression computing the default value for the parameter
+ * Return the expression computing the default value for the parameter, or
+ * `null` if there is no default value.
*/
Expression get defaultValue => _defaultValue;
/**
- * Set the expression computing the default value for the parameter to the given expression.
- *
- * @param expression the expression computing the default value for the parameter
+ * Set the expression computing the default value for the parameter to the
+ * given [expression].
*/
void set defaultValue(Expression expression) {
_defaultValue = becomeParentOf(expression);
@@ -6650,15 +6232,12 @@
/**
* Return the formal parameter with which the default value is associated.
- *
- * @return the formal parameter with which the default value is associated
*/
NormalFormalParameter get parameter => _parameter;
/**
- * Set the formal parameter with which the default value is associated to the given parameter.
- *
- * @param formalParameter the formal parameter with which the default value is associated
+ * Set the formal parameter with which the default value is associated to the
+ * given [formalParameter].
*/
void set parameter(NormalFormalParameter formalParameter) {
_parameter = becomeParentOf(formalParameter);
@@ -6669,18 +6248,23 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_parameter, visitor);
- safelyVisitChild(_defaultValue, visitor);
+ _safelyVisitChild(_parameter, visitor);
+ _safelyVisitChild(_defaultValue, visitor);
}
}
/**
- * This recursive Ast visitor is used to run over [Expression]s to determine if the expression
- * is composed by at least one deferred [PrefixedIdentifier].
+ * A recursive AST visitor that is used to run over [Expression]s to determine
+ * whether the expression is composed by at least one deferred
+ * [PrefixedIdentifier].
*
* See [PrefixedIdentifier.isDeferred].
*/
class DeferredLibraryReferenceDetector extends RecursiveAstVisitor<Object> {
+ /**
+ * A flag indicating whether an identifier from a deferred library has been
+ * found.
+ */
bool _result = false;
/**
@@ -6701,50 +6285,42 @@
}
/**
- * The abstract class `Directive` defines the behavior common to nodes that represent a
- * directive.
+ * A node that represents a directive.
*
- * <pre>
- * directive ::=
- * [ExportDirective]
- * | [ImportDirective]
- * | [LibraryDirective]
- * | [PartDirective]
- * | [PartOfDirective]
- * </pre>
+ * > directive ::=
+ * > [ExportDirective]
+ * > | [ImportDirective]
+ * > | [LibraryDirective]
+ * > | [PartDirective]
+ * > | [PartOfDirective]
*/
abstract class Directive extends AnnotatedNode {
/**
- * The element associated with this directive, or `null` if the AST structure has not been
- * resolved or if this directive could not be resolved.
+ * The element associated with this directive, or `null` if the AST structure
+ * has not been resolved or if this directive could not be resolved.
*/
Element element;
/**
- * Initialize a newly create directive.
- *
- * @param comment the documentation comment associated with this directive
- * @param metadata the annotations associated with the directive
+ * Initialize a newly create directive. Either or both of the [comment] and
+ * [metadata] can be `null` if the directive does not have the corresponding
+ * attribute.
*/
Directive(Comment comment, List<Annotation> metadata)
: super(comment, metadata);
/**
- * Return the token representing the keyword that introduces this directive ('import', 'export',
- * 'library' or 'part').
- *
- * @return the token representing the keyword that introduces this directive
+ * Return the token representing the keyword that introduces this directive
+ * ('import', 'export', 'library' or 'part').
*/
Token get keyword;
}
/**
- * Instances of the class `DoStatement` represent a do statement.
+ * A do statement.
*
- * <pre>
- * doStatement ::=
- * 'do' [Statement] 'while' '(' [Expression] ')' ';'
- * </pre>
+ * > doStatement ::=
+ * > 'do' [Statement] 'while' '(' [Expression] ')' ';'
*/
class DoStatement extends Statement {
/**
@@ -6784,14 +6360,6 @@
/**
* Initialize a newly created do loop.
- *
- * @param doKeyword the token representing the 'do' keyword
- * @param body the body of the loop
- * @param whileKeyword the token representing the 'while' keyword
- * @param leftParenthesis the left parenthesis
- * @param condition the condition that determines when the loop will terminate
- * @param rightParenthesis the right parenthesis
- * @param semicolon the semicolon terminating the statement
*/
DoStatement(this.doKeyword, Statement body, this.whileKeyword,
this.leftParenthesis, Expression condition, this.rightParenthesis,
@@ -6805,15 +6373,11 @@
/**
* Return the body of the loop.
- *
- * @return the body of the loop
*/
Statement get body => _body;
/**
- * Set the body of the loop to the given statement.
- *
- * @param statement the body of the loop
+ * Set the body of the loop to the given [statement].
*/
void set body(Statement statement) {
_body = becomeParentOf(statement);
@@ -6831,15 +6395,12 @@
/**
* Return the condition that determines when the loop will terminate.
- *
- * @return the condition that determines when the loop will terminate
*/
Expression get condition => _condition;
/**
- * Set the condition that determines when the loop will terminate to the given expression.
- *
- * @param expression the condition that determines when the loop will terminate
+ * Set the condition that determines when the loop will terminate to the given
+ * [expression].
*/
void set condition(Expression expression) {
_condition = becomeParentOf(expression);
@@ -6853,22 +6414,20 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_body, visitor);
- safelyVisitChild(_condition, visitor);
+ _safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_condition, visitor);
}
}
/**
- * Instances of the class `DoubleLiteral` represent a floating point literal expression.
+ * A floating point literal expression.
*
- * <pre>
- * doubleLiteral ::=
- * decimalDigit+ ('.' decimalDigit*)? exponent?
- * | '.' decimalDigit+ exponent?
- *
- * exponent ::=
- * ('e' | 'E') ('+' | '-')? decimalDigit+
- * </pre>
+ * > doubleLiteral ::=
+ * > decimalDigit+ ('.' decimalDigit*)? exponent?
+ * > | '.' decimalDigit+ exponent?
+ * >
+ * > exponent ::=
+ * > ('e' | 'E') ('+' | '-')? decimalDigit+
*/
class DoubleLiteral extends Literal {
/**
@@ -6883,9 +6442,6 @@
/**
* Initialize a newly created floating point literal.
- *
- * @param literal the token representing the literal
- * @param value the value of the literal
*/
DoubleLiteral(this.literal, this.value);
@@ -6911,15 +6467,12 @@
}
/**
- * Instances of the class `ElementLocator` locate the [Element]
- * associated with a given [AstNode].
+ * An object used to locate the [Element] associated with a given [AstNode].
*/
class ElementLocator {
/**
- * Locate the [Element] associated with the given [AstNode].
- *
- * @param node the node (not `null`)
- * @return the associated element, or `null` if none is found
+ * Return the element associated with the given [node], or `null` if there is
+ * no element associated with the node.
*/
static Element locate(AstNode node) {
ElementLocator_ElementMapper mapper = new ElementLocator_ElementMapper();
@@ -6927,11 +6480,8 @@
}
/**
- * Locate the [Element] associated with the given [AstNode] and offset.
- *
- * @param node the node (not `null`)
- * @param offset the offset relative to source
- * @return the associated element, or `null` if none is found
+ * Return the element associated with the given [node], or `null` if there is
+ * no element associated with the node.
*/
static Element locateWithOffset(AstNode node, int offset) {
if (node == null) {
@@ -7056,24 +6606,21 @@
}
/**
- * Instances of the class `EmptyFunctionBody` represent an empty function body, which can only
- * appear in constructors or abstract methods.
+ * An empty function body, which can only appear in constructors or abstract
+ * methods.
*
- * <pre>
- * emptyFunctionBody ::=
- * ';'
- * </pre>
+ * > emptyFunctionBody ::=
+ * > ';'
*/
class EmptyFunctionBody extends FunctionBody {
/**
- * The token representing the semicolon that marks the end of the function body.
+ * The token representing the semicolon that marks the end of the function
+ * body.
*/
Token semicolon;
/**
* Initialize a newly created function body.
- *
- * @param semicolon the token representing the semicolon that marks the end of the function body
*/
EmptyFunctionBody(this.semicolon);
@@ -7099,12 +6646,10 @@
}
/**
- * Instances of the class `EmptyStatement` represent an empty statement.
+ * An empty statement.
*
- * <pre>
- * emptyStatement ::=
- * ';'
- * </pre>
+ * > emptyStatement ::=
+ * > ';'
*/
class EmptyStatement extends Statement {
/**
@@ -7114,8 +6659,6 @@
/**
* Initialize a newly created empty statement.
- *
- * @param semicolon the semicolon terminating the statement
*/
EmptyStatement(this.semicolon);
@@ -7141,8 +6684,7 @@
}
/**
- * Instances of the class `EnumConstantDeclaration` represent the declaration of an enum
- * constant.
+ * The declaration of an enum constant.
*/
class EnumConstantDeclaration extends Declaration {
/**
@@ -7151,11 +6693,10 @@
SimpleIdentifier _name;
/**
- * Initialize a newly created enum constant declaration.
- *
- * @param comment the documentation comment associated with this declaration
- * @param metadata the annotations associated with this declaration
- * @param name the name of the constant
+ * Initialize a newly created enum constant declaration. Either or both of the
+ * [comment] and [metadata] can be `null` if the constant does not have the
+ * corresponding attribute. (Technically, enum constants cannot have metadata,
+ * but we allow it for consistency.)
*/
EnumConstantDeclaration(Comment comment, List<Annotation> metadata,
SimpleIdentifier name)
@@ -7181,15 +6722,11 @@
/**
* Return the name of the constant.
- *
- * @return the name of the constant
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the constant to the given name.
- *
- * @param name the name of the constant
+ * Set the name of the constant to the given [name].
*/
void set name(SimpleIdentifier name) {
_name = becomeParentOf(name);
@@ -7201,17 +6738,15 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_name, visitor);
}
}
/**
- * Instances of the class `EnumDeclaration` represent the declaration of an enumeration.
+ * The declaration of an enumeration.
*
- * <pre>
- * enumType ::=
- * metadata 'enum' [SimpleIdentifier] '{' [SimpleIdentifier] (',' [SimpleIdentifier])* (',')? '}'
- * </pre>
+ * > enumType ::=
+ * > metadata 'enum' [SimpleIdentifier] '{' [SimpleIdentifier] (',' [SimpleIdentifier])* (',')? '}'
*/
class EnumDeclaration extends CompilationUnitMember {
/**
@@ -7240,15 +6775,10 @@
Token rightBracket;
/**
- * Initialize a newly created enumeration declaration.
- *
- * @param comment the documentation comment associated with this member
- * @param metadata the annotations associated with this member
- * @param keyword the 'enum' keyword
- * @param name the name of the enumeration
- * @param leftBracket the left curly bracket
- * @param constants the enumeration constants being declared
- * @param rightBracket the right curly bracket
+ * Initialize a newly created enumeration declaration. Either or both of the
+ * [comment] and [metadata] can be `null` if the declaration does not have the
+ * corresponding attribute. The list of [constants] must contain at least one
+ * value.
*/
EnumDeclaration(Comment comment, List<Annotation> metadata, this.keyword,
SimpleIdentifier name, this.leftBracket,
@@ -7271,8 +6801,6 @@
/**
* Return the enumeration constants being declared.
- *
- * @return the enumeration constants being declared
*/
NodeList<EnumConstantDeclaration> get constants => _constants;
@@ -7288,15 +6816,11 @@
/**
* Return the name of the enumeration.
- *
- * @return the name of the enumeration
*/
SimpleIdentifier get name => _name;
/**
- * set the name of the enumeration to the given identifier.
- *
- * @param name the name of the enumeration
+ * Set the name of the enumeration to the given [name].
*/
void set name(SimpleIdentifier name) {
_name = becomeParentOf(name);
@@ -7308,13 +6832,14 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_name, visitor);
_constants.accept(visitor);
}
}
/**
- * Ephemeral identifiers are created as needed to mimic the presence of an empty identifier.
+ * Ephemeral identifiers are created as needed to mimic the presence of an empty
+ * identifier.
*/
class EphemeralIdentifier extends SimpleIdentifier {
EphemeralIdentifier(AstNode parent, int location)
@@ -7324,23 +6849,17 @@
}
/**
- * Instances of the class `ExportDirective` represent an export directive.
+ * An export directive.
*
- * <pre>
- * exportDirective ::=
- * [Annotation] 'export' [StringLiteral] [Combinator]* ';'
- * </pre>
+ * > exportDirective ::=
+ * > [Annotation] 'export' [StringLiteral] [Combinator]* ';'
*/
class ExportDirective extends NamespaceDirective {
/**
- * Initialize a newly created export directive.
- *
- * @param comment the documentation comment associated with this directive
- * @param metadata the annotations associated with the directive
- * @param keyword the token representing the 'export' keyword
- * @param libraryUri the URI of the library being exported
- * @param combinators the combinators used to control which names are exported
- * @param semicolon the semicolon terminating the directive
+ * Initialize a newly created export directive. Either or both of the
+ * [comment] and [metadata] can be `null` if the directive does not have the
+ * corresponding attribute. The list of [combinators] can be `null` if there
+ * are no combinators.
*/
ExportDirective(Comment comment, List<Annotation> metadata, Token keyword,
StringLiteral libraryUri, List<Combinator> combinators, Token semicolon)
@@ -7374,15 +6893,12 @@
}
/**
- * Instances of the class `Expression` defines the behavior common to nodes that represent an
- * expression.
+ * A node that represents an expression.
*
- * <pre>
- * expression ::=
- * [AssignmentExpression]
- * | [ConditionalExpression] cascadeSection*
- * | [ThrowExpression]
- * </pre>
+ * > expression ::=
+ * > [AssignmentExpression]
+ * > | [ConditionalExpression] cascadeSection*
+ * > | [ThrowExpression]
*/
abstract class Expression extends AstNode {
/**
@@ -7391,23 +6907,22 @@
static const List<Expression> EMPTY_ARRAY = const <Expression>[];
/**
- * The static type of this expression, or `null` if the AST structure has not been resolved.
+ * The static type of this expression, or `null` if the AST structure has not
+ * been resolved.
*/
DartType staticType;
/**
- * The propagated type of this expression, or `null` if type propagation has not been
- * performed on the AST structure.
+ * The propagated type of this expression, or `null` if type propagation has
+ * not been performed on the AST structure.
*/
DartType propagatedType;
/**
- * Return the best parameter element information available for this expression. If type
- * propagation was able to find a better parameter element than static analysis, that type will be
- * returned. Otherwise, the result of static analysis will be returned.
- *
- * @return the parameter element representing the parameter to which the value of this expression
- * will be bound
+ * Return the best parameter element information available for this
+ * expression. If type propagation was able to find a better parameter element
+ * than static analysis, that type will be returned. Otherwise, the result of
+ * static analysis will be returned.
*/
ParameterElement get bestParameterElement {
ParameterElement propagatedElement = propagatedParameterElement;
@@ -7418,12 +6933,11 @@
}
/**
- * Return the best type information available for this expression. If type propagation was able to
- * find a better type than static analysis, that type will be returned. Otherwise, the result of
- * static analysis will be returned. If no type analysis has been performed, then the type
- * 'dynamic' will be returned.
- *
- * @return the best type information available for this expression
+ * Return the best type information available for this expression. If type
+ * propagation was able to find a better type than static analysis, that type
+ * will be returned. Otherwise, the result of static analysis will be
+ * returned. If no type analysis has been performed, then the type 'dynamic'
+ * will be returned.
*/
DartType get bestType {
if (propagatedType != null) {
@@ -7437,33 +6951,28 @@
/**
* Return `true` if this expression is syntactically valid for the LHS of an
* [AssignmentExpression].
- *
- * @return `true` if this expression matches the `assignableExpression` production
*/
bool get isAssignable => false;
/**
- * Return the precedence of this expression. The precedence is a positive integer value that
- * defines how the source code is parsed into an AST. For example `a * b + c` is parsed as
- * `(a * b) + c` because the precedence of `*` is greater than the precedence of
- * `+`.
+ * Return the precedence of this expression. The precedence is a positive
+ * integer value that defines how the source code is parsed into an AST. For
+ * example `a * b + c` is parsed as `(a * b) + c` because the precedence of
+ * `*` is greater than the precedence of `+`.
*
- * You should not assume that returned values will stay the same, they might change as result of
- * specification change. Only relative order should be used.
- *
- * @return the precedence of this expression
+ * Clients should not assume that returned values will stay the same, they
+ * might change as result of specification change. Only relative order should
+ * be used.
*/
int get precedence;
/**
- * If this expression is an argument to an invocation, and the AST structure has been resolved,
- * and the function being invoked is known based on propagated type information, and this
- * expression corresponds to one of the parameters of the function being invoked, then return the
- * parameter element representing the parameter to which the value of this expression will be
+ * If this expression is an argument to an invocation, and the AST structure
+ * has been resolved, and the function being invoked is known based on
+ * propagated type information, and this expression corresponds to one of the
+ * parameters of the function being invoked, then return the parameter element
+ * representing the parameter to which the value of this expression will be
* bound. Otherwise, return `null`.
- *
- * @return the parameter element representing the parameter to which the value of this expression
- * will be bound
*/
ParameterElement get propagatedParameterElement {
AstNode parent = this.parent;
@@ -7493,14 +7002,12 @@
}
/**
- * If this expression is an argument to an invocation, and the AST structure has been resolved,
- * and the function being invoked is known based on static type information, and this expression
- * corresponds to one of the parameters of the function being invoked, then return the parameter
- * element representing the parameter to which the value of this expression will be bound.
- * Otherwise, return `null`.
- *
- * @return the parameter element representing the parameter to which the value of this expression
- * will be bound
+ * If this expression is an argument to an invocation, and the AST structure
+ * has been resolved, and the function being invoked is known based on static
+ * type information, and this expression corresponds to one of the parameters
+ * of the function being invoked, then return the parameter element
+ * representing the parameter to which the value of this expression will be
+ * bound. Otherwise, return `null`.
*/
ParameterElement get staticParameterElement {
AstNode parent = this.parent;
@@ -7531,22 +7038,21 @@
}
/**
- * Instances of the class `ExpressionFunctionBody` represent a function body consisting of a
- * single expression.
+ * A function body consisting of a single expression.
*
- * <pre>
- * expressionFunctionBody ::=
- * 'async'? '=>' [Expression] ';'
- * </pre>
+ * > expressionFunctionBody ::=
+ * > 'async'? '=>' [Expression] ';'
*/
class ExpressionFunctionBody extends FunctionBody {
/**
- * The token representing the 'async' keyword, or `null` if there is no such keyword.
+ * The token representing the 'async' keyword, or `null` if there is no such
+ * keyword.
*/
Token keyword;
/**
- * The token introducing the expression that represents the body of the function.
+ * The token introducing the expression that represents the body of the
+ * function.
*/
Token functionDefinition;
@@ -7561,13 +7067,9 @@
Token semicolon;
/**
- * Initialize a newly created function body consisting of a block of statements.
- *
- * @param keyword the token representing the 'async' keyword
- * @param functionDefinition the token introducing the expression that represents the body of the
- * function
- * @param expression the expression representing the body of the function
- * @param semicolon the semicolon terminating the statement
+ * Initialize a newly created function body consisting of a block of
+ * statements. The [keyword] can be `null` if the function body is not an
+ * async function body.
*/
ExpressionFunctionBody(this.keyword, this.functionDefinition,
Expression expression, this.semicolon) {
@@ -7594,15 +7096,12 @@
/**
* Return the expression representing the body of the function.
- *
- * @return the expression representing the body of the function
*/
Expression get expression => _expression;
/**
- * Set the expression representing the body of the function to the given expression.
- *
- * @param expression the expression representing the body of the function
+ * Set the expression representing the body of the function to the given
+ * [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -7619,17 +7118,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * Instances of the class `ExpressionStatement` wrap an expression as a statement.
+ * An expression used as a statement.
*
- * <pre>
- * expressionStatement ::=
- * [Expression]? ';'
- * </pre>
+ * > expressionStatement ::=
+ * > [Expression]? ';'
*/
class ExpressionStatement extends Statement {
/**
@@ -7638,16 +7135,13 @@
Expression _expression;
/**
- * The semicolon terminating the statement, or `null` if the expression is a function
- * expression and therefore isn't followed by a semicolon.
+ * The semicolon terminating the statement, or `null` if the expression is a
+ * function expression and therefore isn't followed by a semicolon.
*/
Token semicolon;
/**
* Initialize a newly created expression statement.
- *
- * @param expression the expression that comprises the statement
- * @param semicolon the semicolon terminating the statement
*/
ExpressionStatement(Expression expression, this.semicolon) {
_expression = becomeParentOf(expression);
@@ -7671,15 +7165,11 @@
/**
* Return the expression that comprises the statement.
- *
- * @return the expression that comprises the statement
*/
Expression get expression => _expression;
/**
- * Set the expression that comprises the statement to the given expression.
- *
- * @param expression the expression that comprises the statement
+ * Set the expression that comprises the statement to the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -7693,18 +7183,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * Instances of the class `ExtendsClause` represent the "extends" clause in a class
- * declaration.
+ * The "extends" clause in a class declaration.
*
- * <pre>
- * extendsClause ::=
- * 'extends' [TypeName]
- * </pre>
+ * > extendsClause ::=
+ * > 'extends' [TypeName]
*/
class ExtendsClause extends AstNode {
/**
@@ -7719,9 +7206,6 @@
/**
* Initialize a newly created extends clause.
- *
- * @param keyword the token representing the 'extends' keyword
- * @param superclass the name of the class that is being extended
*/
ExtendsClause(this.keyword, TypeName superclass) {
_superclass = becomeParentOf(superclass);
@@ -7740,15 +7224,11 @@
/**
* Return the name of the class that is being extended.
- *
- * @return the name of the class that is being extended
*/
TypeName get superclass => _superclass;
/**
- * Set the name of the class that is being extended to the given name.
- *
- * @param name the name of the class that is being extended
+ * Set the name of the class that is being extended to the given [name].
*/
void set superclass(TypeName name) {
_superclass = becomeParentOf(name);
@@ -7759,22 +7239,20 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_superclass, visitor);
+ _safelyVisitChild(_superclass, visitor);
}
}
/**
- * Instances of the class `FieldDeclaration` represent the declaration of one or more fields
- * of the same type.
+ * The declaration of one or more fields of the same type.
*
- * <pre>
- * fieldDeclaration ::=
- * 'static'? [VariableDeclarationList] ';'
- * </pre>
+ * > fieldDeclaration ::=
+ * > 'static'? [VariableDeclarationList] ';'
*/
class FieldDeclaration extends ClassMember {
/**
- * The token representing the 'static' keyword, or `null` if the fields are not static.
+ * The token representing the 'static' keyword, or `null` if the fields are
+ * not static.
*/
Token staticKeyword;
@@ -7789,13 +7267,10 @@
Token semicolon;
/**
- * Initialize a newly created field declaration.
- *
- * @param comment the documentation comment associated with this field
- * @param metadata the annotations associated with this field
- * @param staticKeyword the token representing the 'static' keyword
- * @param fieldList the fields being declared
- * @param semicolon the semicolon terminating the declaration
+ * Initialize a newly created field declaration. Either or both of the
+ * [comment] and [metadata] can be `null` if the declaration does not have the
+ * corresponding attribute. The [staticKeyword] can be `null` if the field is
+ * not a static field.
*/
FieldDeclaration(Comment comment, List<Annotation> metadata,
this.staticKeyword, VariableDeclarationList fieldList, this.semicolon)
@@ -7817,18 +7292,14 @@
/**
* Return the fields being declared.
- *
- * @return the fields being declared
*/
VariableDeclarationList get fields => _fieldList;
/**
- * Set the fields being declared to the given list of variables.
- *
- * @param fieldList the fields being declared
+ * Set the fields being declared to the given list of [fields].
*/
- void set fields(VariableDeclarationList fieldList) {
- _fieldList = becomeParentOf(fieldList);
+ void set fields(VariableDeclarationList fields) {
+ _fieldList = becomeParentOf(fields);
}
@override
@@ -7840,9 +7311,7 @@
}
/**
- * Return `true` if the fields are static.
- *
- * @return `true` if the fields are declared to be static
+ * Return `true` if the fields are declared to be static.
*/
bool get isStatic => staticKeyword != null;
@@ -7852,28 +7321,27 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_fieldList, visitor);
+ _safelyVisitChild(_fieldList, visitor);
}
}
/**
- * Instances of the class `FieldFormalParameter` represent a field formal parameter.
+ * A field formal parameter.
*
- * <pre>
- * fieldFormalParameter ::=
- * ('final' [TypeName] | 'const' [TypeName] | 'var' | [TypeName])? 'this' '.' [SimpleIdentifier] [FormalParameterList]?
- * </pre>
+ * > fieldFormalParameter ::=
+ * > ('final' [TypeName] | 'const' [TypeName] | 'var' | [TypeName])?
+ * > 'this' '.' [SimpleIdentifier] [FormalParameterList]?
*/
class FieldFormalParameter extends NormalFormalParameter {
/**
- * The token representing either the 'final', 'const' or 'var' keyword, or `null` if no
- * keyword was used.
+ * The token representing either the 'final', 'const' or 'var' keyword, or
+ * `null` if no keyword was used.
*/
Token keyword;
/**
- * The name of the declared type of the parameter, or `null` if the parameter does not have
- * a declared type.
+ * The name of the declared type of the parameter, or `null` if the parameter
+ * does not have a declared type.
*/
TypeName _type;
@@ -7888,23 +7356,19 @@
Token period;
/**
- * The parameters of the function-typed parameter, or `null` if this is not a function-typed
- * field formal parameter.
+ * The parameters of the function-typed parameter, or `null` if this is not a
+ * function-typed field formal parameter.
*/
FormalParameterList _parameters;
/**
- * Initialize a newly created formal parameter.
- *
- * @param comment the documentation comment associated with this parameter
- * @param metadata the annotations associated with this parameter
- * @param keyword the token representing either the 'final', 'const' or 'var' keyword
- * @param type the name of the declared type of the parameter
- * @param thisToken the token representing the 'this' keyword
- * @param period the token representing the period
- * @param identifier the name of the parameter being declared
- * @param parameters the parameters of the function-typed parameter, or `null` if this is
- * not a function-typed field formal parameter
+ * Initialize a newly created formal parameter. Either or both of the
+ * [comment] and [metadata] can be `null` if the parameter does not have the
+ * corresponding attribute. The [keyword] can be `null` if there is a type.
+ * The [type] must be `null` if the keyword is 'var'. The [thisToken] and
+ * [period] can be `null` if the keyword 'this' was not provided. The
+ * [parameters] can be `null` if this is not a function-typed field formal
+ * parameter.
*/
FieldFormalParameter(Comment comment, List<Annotation> metadata, this.keyword,
TypeName type, this.thisToken, this.period, SimpleIdentifier identifier,
@@ -7950,35 +7414,29 @@
(keyword is KeywordToken) && (keyword as KeywordToken).keyword == Keyword.FINAL;
/**
- * Return the parameters of the function-typed parameter, or `null` if this is not a
- * function-typed field formal parameter.
- *
- * @return the parameters of the function-typed parameter
+ * Return the parameters of the function-typed parameter, or `null` if this is
+ * not a function-typed field formal parameter.
*/
FormalParameterList get parameters => _parameters;
/**
- * Set the parameters of the function-typed parameter to the given parameters.
- *
- * @param parameters the parameters of the function-typed parameter
+ * Set the parameters of the function-typed parameter to the given
+ * [parameters].
*/
void set parameters(FormalParameterList parameters) {
_parameters = becomeParentOf(parameters);
}
/**
- * Return the name of the declared type of the parameter, or `null` if the parameter does
- * not have a declared type. Note that if this is a function-typed field formal parameter this is
- * the return type of the function.
- *
- * @return the name of the declared type of the parameter
+ * Return the name of the declared type of the parameter, or `null` if the
+ * parameter does not have a declared type. Note that if this is a
+ * function-typed field formal parameter this is the return type of the
+ * function.
*/
TypeName get type => _type;
/**
- * Set the name of the declared type of the parameter to the given type name.
- *
- * @param typeName the name of the declared type of the parameter
+ * Set the name of the declared type of the parameter to the given [typeName].
*/
void set type(TypeName typeName) {
_type = becomeParentOf(typeName);
@@ -7990,24 +7448,23 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_type, visitor);
- safelyVisitChild(identifier, visitor);
- safelyVisitChild(_parameters, visitor);
+ _safelyVisitChild(_type, visitor);
+ _safelyVisitChild(identifier, visitor);
+ _safelyVisitChild(_parameters, visitor);
}
}
/**
- * Instances of the class `ForEachStatement` represent a for-each statement.
+ * A for-each statement.
*
- * <pre>
- * forEachStatement ::=
- * 'await'? 'for' '(' [DeclaredIdentifier] 'in' [Expression] ')' [Block]
- * | 'await'? 'for' '(' [SimpleIdentifier] 'in' [Expression] ')' [Block]
- * </pre>
+ * > forEachStatement ::=
+ * > 'await'? 'for' '(' [DeclaredIdentifier] 'in' [Expression] ')' [Block]
+ * > | 'await'? 'for' '(' [SimpleIdentifier] 'in' [Expression] ')' [Block]
*/
class ForEachStatement extends Statement {
/**
- * The token representing the 'await' keyword, or `null` if there is no 'await' keyword.
+ * The token representing the 'await' keyword, or `null` if there is no
+ * 'await' keyword.
*/
Token awaitKeyword;
@@ -8022,8 +7479,8 @@
Token leftParenthesis;
/**
- * The declaration of the loop variable, or `null` if the loop variable is a simple
- * identifier.
+ * The declaration of the loop variable, or `null` if the loop variable is a
+ * simple identifier.
*/
DeclaredIdentifier _loopVariable;
@@ -8053,15 +7510,8 @@
Statement _body;
/**
- * Initialize a newly created for-each statement.
- *
- * @param awaitKeyword the token representing the 'await' keyword
- * @param forKeyword the token representing the 'for' keyword
- * @param leftParenthesis the left parenthesis
- * @param loopVariable the declaration of the loop variable
- * @param iterator the expression evaluated to produce the iterator
- * @param rightParenthesis the right parenthesis
- * @param body the body of the loop
+ * Initialize a newly created for-each statement. The [awaitKeyword] can be
+ * `null` if this is not an asynchronous for loop.
*/
ForEachStatement.con1(this.awaitKeyword, this.forKeyword,
this.leftParenthesis, DeclaredIdentifier loopVariable, this.inKeyword,
@@ -8072,15 +7522,8 @@
}
/**
- * Initialize a newly created for-each statement.
- *
- * @param awaitKeyword the token representing the 'await' keyword
- * @param forKeyword the token representing the 'for' keyword
- * @param leftParenthesis the left parenthesis
- * @param identifier the loop variable
- * @param iterator the expression evaluated to produce the iterator
- * @param rightParenthesis the right parenthesis
- * @param body the body of the loop
+ * Initialize a newly created for-each statement. The [awaitKeyword] can be
+ * `null` if this is not an asynchronous for loop.
*/
ForEachStatement.con2(this.awaitKeyword, this.forKeyword,
this.leftParenthesis, SimpleIdentifier identifier, this.inKeyword,
@@ -8095,18 +7538,14 @@
/**
* Return the body of the loop.
- *
- * @return the body of the loop
*/
Statement get body => _body;
/**
- * Set the body of the loop to the given block.
- *
- * @param body the body of the loop
+ * Set the body of the loop to the given [statement].
*/
- void set body(Statement body) {
- _body = becomeParentOf(body);
+ void set body(Statement statement) {
+ _body = becomeParentOf(statement);
}
@override
@@ -8125,16 +7564,13 @@
Token get endToken => _body.endToken;
/**
- * Return the loop variable, or `null` if the loop variable is declared in the 'for'.
- *
- * @return the loop variable
+ * Return the loop variable, or `null` if the loop variable is declared in the
+ * 'for'.
*/
SimpleIdentifier get identifier => _identifier;
/**
- * Set the loop variable to the given variable.
- *
- * @param identifier the loop variable
+ * Set the loop variable to the given [identifier].
*/
void set identifier(SimpleIdentifier identifier) {
_identifier = becomeParentOf(identifier);
@@ -8142,15 +7578,12 @@
/**
* Return the expression evaluated to produce the iterator.
- *
- * @return the expression evaluated to produce the iterator
*/
Expression get iterable => _iterable;
/**
- * Set the expression evaluated to produce the iterator to the given expression.
- *
- * @param expression the expression evaluated to produce the iterator
+ * Set the expression evaluated to produce the iterator to the given
+ * [expression].
*/
void set iterable(Expression expression) {
_iterable = becomeParentOf(expression);
@@ -8165,17 +7598,13 @@
Expression get iterator => iterable;
/**
- * Return the declaration of the loop variable, or `null` if the loop variable is a simple
- * identifier.
- *
- * @return the declaration of the loop variable
+ * Return the declaration of the loop variable, or `null` if the loop variable
+ * is a simple identifier.
*/
DeclaredIdentifier get loopVariable => _loopVariable;
/**
- * Set the declaration of the loop variable to the given variable.
- *
- * @param variable the declaration of the loop variable
+ * Set the declaration of the loop variable to the given [variable].
*/
void set loopVariable(DeclaredIdentifier variable) {
_loopVariable = becomeParentOf(variable);
@@ -8186,29 +7615,24 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_loopVariable, visitor);
- safelyVisitChild(_identifier, visitor);
- safelyVisitChild(_iterable, visitor);
- safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_loopVariable, visitor);
+ _safelyVisitChild(_identifier, visitor);
+ _safelyVisitChild(_iterable, visitor);
+ _safelyVisitChild(_body, visitor);
}
}
/**
- * The abstract class `FormalParameter` defines the behavior of objects representing a
- * parameter to a function.
+ * A node representing a parameter to a function.
*
- * <pre>
- * formalParameter ::=
- * [NormalFormalParameter]
- * | [DefaultFormalParameter]
- * </pre>
+ * > formalParameter ::=
+ * > [NormalFormalParameter]
+ * > | [DefaultFormalParameter]
*/
abstract class FormalParameter extends AstNode {
/**
- * Return the element representing this parameter, or `null` if this parameter has not been
- * resolved.
- *
- * @return the element representing this parameter
+ * Return the element representing this parameter, or `null` if this parameter
+ * has not been resolved.
*/
ParameterElement get element {
SimpleIdentifier identifier = this.identifier;
@@ -8220,63 +7644,54 @@
/**
* Return the name of the parameter being declared.
- *
- * @return the name of the parameter being declared
*/
SimpleIdentifier get identifier;
/**
* Return `true` if this parameter was declared with the 'const' modifier.
- *
- * @return `true` if this parameter was declared with the 'const' modifier
*/
bool get isConst;
/**
- * Return `true` if this parameter was declared with the 'final' modifier. Parameters that
- * are declared with the 'const' modifier will return `false` even though they are
- * implicitly final.
- *
- * @return `true` if this parameter was declared with the 'final' modifier
+ * Return `true` if this parameter was declared with the 'final' modifier.
+ * Parameters that are declared with the 'const' modifier will return `false`
+ * even though they are implicitly final.
*/
bool get isFinal;
/**
* Return the kind of this parameter.
- *
- * @return the kind of this parameter
*/
ParameterKind get kind;
}
/**
- * Instances of the class `FormalParameterList` represent the formal parameter list of a
- * method declaration, function declaration, or function type alias.
+ * The formal parameter list of a method declaration, function declaration, or
+ * function type alias.
*
- * While the grammar requires all optional formal parameters to follow all of the normal formal
- * parameters and at most one grouping of optional formal parameters, this class does not enforce
- * those constraints. All parameters are flattened into a single list, which can have any or all
- * kinds of parameters (normal, named, and positional) in any order.
+ * While the grammar requires all optional formal parameters to follow all of
+ * the normal formal parameters and at most one grouping of optional formal
+ * parameters, this class does not enforce those constraints. All parameters are
+ * flattened into a single list, which can have any or all kinds of parameters
+ * (normal, named, and positional) in any order.
*
- * <pre>
- * formalParameterList ::=
- * '(' ')'
- * | '(' normalFormalParameters (',' optionalFormalParameters)? ')'
- * | '(' optionalFormalParameters ')'
- *
- * normalFormalParameters ::=
- * [NormalFormalParameter] (',' [NormalFormalParameter])*
- *
- * optionalFormalParameters ::=
- * optionalPositionalFormalParameters
- * | namedFormalParameters
- *
- * optionalPositionalFormalParameters ::=
- * '[' [DefaultFormalParameter] (',' [DefaultFormalParameter])* ']'
- *
- * namedFormalParameters ::=
- * '{' [DefaultFormalParameter] (',' [DefaultFormalParameter])* '}'
- * </pre>
+ * > formalParameterList ::=
+ * > '(' ')'
+ * > | '(' normalFormalParameters (',' optionalFormalParameters)? ')'
+ * > | '(' optionalFormalParameters ')'
+ * >
+ * > normalFormalParameters ::=
+ * > [NormalFormalParameter] (',' [NormalFormalParameter])*
+ * >
+ * > optionalFormalParameters ::=
+ * > optionalPositionalFormalParameters
+ * > | namedFormalParameters
+ * >
+ * > optionalPositionalFormalParameters ::=
+ * > '[' [DefaultFormalParameter] (',' [DefaultFormalParameter])* ']'
+ * >
+ * > namedFormalParameters ::=
+ * > '{' [DefaultFormalParameter] (',' [DefaultFormalParameter])* '}'
*/
class FormalParameterList extends AstNode {
/**
@@ -8290,14 +7705,14 @@
NodeList<FormalParameter> _parameters;
/**
- * The left square bracket ('[') or left curly brace ('{') introducing the optional parameters, or
- * `null` if there are no optional parameters.
+ * The left square bracket ('[') or left curly brace ('{') introducing the
+ * optional parameters, or `null` if there are no optional parameters.
*/
Token leftDelimiter;
/**
- * The right square bracket (']') or right curly brace ('}') introducing the optional parameters,
- * or `null` if there are no optional parameters.
+ * The right square bracket (']') or right curly brace ('}') introducing the
+ * optional parameters, or `null` if there are no optional parameters.
*/
Token rightDelimiter;
@@ -8307,13 +7722,9 @@
Token rightParenthesis;
/**
- * Initialize a newly created parameter list.
- *
- * @param leftParenthesis the left parenthesis
- * @param parameters the parameters associated with the method
- * @param leftDelimiter the left delimiter introducing the optional parameters
- * @param rightDelimiter the right delimiter introducing the optional parameters
- * @param rightParenthesis the right parenthesis
+ * Initialize a newly created parameter list. The list of [parameters] can be
+ * `null` if there are no parameters. The [leftDelimiter] and [rightDelimiter]
+ * can be `null` if there are no optional parameters.
*/
FormalParameterList(this.leftParenthesis, List<FormalParameter> parameters,
this.leftDelimiter, this.rightDelimiter, this.rightParenthesis) {
@@ -8344,10 +7755,9 @@
Token get endToken => rightParenthesis;
/**
- * Return an array containing the elements representing the parameters in this list. The array
- * will contain `null`s if the parameters in this list have not been resolved.
- *
- * @return the elements representing the parameters in this list
+ * Return a list containing the elements representing the parameters in this
+ * list. The list will contain `null`s if the parameters in this list have not
+ * been resolved.
*/
List<ParameterElement> get parameterElements {
int count = _parameters.length;
@@ -8360,8 +7770,6 @@
/**
* Return the parameters associated with the method.
- *
- * @return the parameters associated with the method
*/
NodeList<FormalParameter> get parameters => _parameters;
@@ -8375,19 +7783,17 @@
}
/**
- * Instances of the class `ForStatement` represent a for statement.
+ * A for statement.
*
- * <pre>
- * forStatement ::=
- * 'for' '(' forLoopParts ')' [Statement]
- *
- * forLoopParts ::=
- * forInitializerStatement ';' [Expression]? ';' [Expression]?
- *
- * forInitializerStatement ::=
- * [DefaultFormalParameter]
- * | [Expression]?
- * </pre>
+ * > forStatement ::=
+ * > 'for' '(' forLoopParts ')' [Statement]
+ * >
+ * > forLoopParts ::=
+ * > forInitializerStatement ';' [Expression]? ';' [Expression]?
+ * >
+ * > forInitializerStatement ::=
+ * > [DefaultFormalParameter]
+ * > | [Expression]?
*/
class ForStatement extends Statement {
/**
@@ -8401,16 +7807,16 @@
Token leftParenthesis;
/**
- * The declaration of the loop variables, or `null` if there are no variables. Note that a
- * for statement cannot have both a variable list and an initialization expression, but can
- * validly have neither.
+ * The declaration of the loop variables, or `null` if there are no variables.
+ * Note that a for statement cannot have both a variable list and an
+ * initialization expression, but can validly have neither.
*/
VariableDeclarationList _variableList;
/**
- * The initialization expression, or `null` if there is no initialization expression. Note
- * that a for statement cannot have both a variable list and an initialization expression, but can
- * validly have neither.
+ * The initialization expression, or `null` if there is no initialization
+ * expression. Note that a for statement cannot have both a variable list and
+ * an initialization expression, but can validly have neither.
*/
Expression _initialization;
@@ -8420,8 +7826,8 @@
Token leftSeparator;
/**
- * The condition used to determine when to terminate the loop, or `null` if there is no
- * condition.
+ * The condition used to determine when to terminate the loop, or `null` if
+ * there is no condition.
*/
Expression _condition;
@@ -8446,18 +7852,10 @@
Statement _body;
/**
- * Initialize a newly created for statement.
- *
- * @param forKeyword the token representing the 'for' keyword
- * @param leftParenthesis the left parenthesis
- * @param variableList the declaration of the loop variables
- * @param initialization the initialization expression
- * @param leftSeparator the semicolon separating the initializer and the condition
- * @param condition the condition used to determine when to terminate the loop
- * @param rightSeparator the semicolon separating the condition and the updater
- * @param updaters the list of expressions run after each execution of the loop body
- * @param rightParenthesis the right parenthesis
- * @param body the body of the loop
+ * Initialize a newly created for statement. Either the [variableList] or the
+ * [initialization] must be `null`. Either the [condition] and the list of
+ * [updaters] can be `null` if the loop does not have the corresponding
+ * attribute.
*/
ForStatement(this.forKeyword, this.leftParenthesis,
VariableDeclarationList variableList, Expression initialization,
@@ -8475,18 +7873,14 @@
/**
* Return the body of the loop.
- *
- * @return the body of the loop
*/
Statement get body => _body;
/**
- * Set the body of the loop to the given statement.
- *
- * @param body the body of the loop
+ * Set the body of the loop to the given [statement].
*/
- void set body(Statement body) {
- _body = becomeParentOf(body);
+ void set body(Statement statement) {
+ _body = becomeParentOf(statement);
}
@override
@@ -8503,17 +7897,14 @@
..add(_body);
/**
- * Return the condition used to determine when to terminate the loop, or `null` if there is
- * no condition.
- *
- * @return the condition used to determine when to terminate the loop
+ * Return the condition used to determine when to terminate the loop, or
+ * `null` if there is no condition.
*/
Expression get condition => _condition;
/**
- * Set the condition used to determine when to terminate the loop to the given expression.
- *
- * @param expression the condition used to determine when to terminate the loop
+ * Set the condition used to determine when to terminate the loop to the given
+ * [expression].
*/
void set condition(Expression expression) {
_condition = becomeParentOf(expression);
@@ -8523,16 +7914,13 @@
Token get endToken => _body.endToken;
/**
- * Return the initialization expression, or `null` if there is no initialization expression.
- *
- * @return the initialization expression
+ * Return the initialization expression, or `null` if there is no
+ * initialization expression.
*/
Expression get initialization => _initialization;
/**
- * Set the initialization expression to the given expression.
- *
- * @param initialization the initialization expression
+ * Set the initialization expression to the given [expression].
*/
void set initialization(Expression initialization) {
_initialization = becomeParentOf(initialization);
@@ -8540,22 +7928,17 @@
/**
* Return the list of expressions run after each execution of the loop body.
- *
- * @return the list of expressions run after each execution of the loop body
*/
NodeList<Expression> get updaters => _updaters;
/**
- * Return the declaration of the loop variables, or `null` if there are no variables.
- *
- * @return the declaration of the loop variables, or `null` if there are no variables
+ * Return the declaration of the loop variables, or `null` if there are no
+ * variables.
*/
VariableDeclarationList get variables => _variableList;
/**
- * Set the declaration of the loop variables to the given parameter.
- *
- * @param variableList the declaration of the loop variables
+ * Set the declaration of the loop variables to the given [variableList].
*/
void set variables(VariableDeclarationList variableList) {
_variableList = becomeParentOf(variableList);
@@ -8566,79 +7949,65 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_variableList, visitor);
- safelyVisitChild(_initialization, visitor);
- safelyVisitChild(_condition, visitor);
+ _safelyVisitChild(_variableList, visitor);
+ _safelyVisitChild(_initialization, visitor);
+ _safelyVisitChild(_condition, visitor);
_updaters.accept(visitor);
- safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_body, visitor);
}
}
/**
- * The abstract class `FunctionBody` defines the behavior common to objects representing the
- * body of a function or method.
+ * A node representing the body of a function or method.
*
- * <pre>
- * functionBody ::=
- * [BlockFunctionBody]
- * | [EmptyFunctionBody]
- * | [ExpressionFunctionBody]
- * </pre>
+ * > functionBody ::=
+ * > [BlockFunctionBody]
+ * > | [EmptyFunctionBody]
+ * > | [ExpressionFunctionBody]
*/
abstract class FunctionBody extends AstNode {
/**
* Return `true` if this function body is asynchronous.
- *
- * @return `true` if this function body is asynchronous
*/
bool get isAsynchronous => false;
/**
* Return `true` if this function body is a generator.
- *
- * @return `true` if this function body is a generator
*/
bool get isGenerator => false;
/**
* Return `true` if this function body is synchronous.
- *
- * @return `true` if this function body is synchronous
*/
bool get isSynchronous => true;
/**
- * Return the token representing the 'async' or 'sync' keyword, or `null` if there is no
- * such keyword.
- *
- * @return the token representing the 'async' or 'sync' keyword
+ * Return the token representing the 'async' or 'sync' keyword, or `null` if
+ * there is no such keyword.
*/
Token get keyword => null;
/**
- * Return the star following the 'async' or 'sync' keyword, or `null` if there is no star.
- *
- * @return the star following the 'async' or 'sync' keyword
+ * Return the star following the 'async' or 'sync' keyword, or `null` if there
+ * is no star.
*/
Token get star => null;
}
/**
- * Instances of the class `FunctionDeclaration` wrap a [FunctionExpression] as a top-level declaration.
+ * A top-level declaration.
*
- * <pre>
- * functionDeclaration ::=
- * 'external' functionSignature
- * | functionSignature [FunctionBody]
- *
- * functionSignature ::=
- * [Type]? ('get' | 'set')? [SimpleIdentifier] [FormalParameterList]
- * </pre>
+ * > functionDeclaration ::=
+ * > 'external' functionSignature
+ * > | functionSignature [FunctionBody]
+ * >
+ * > functionSignature ::=
+ * > [Type]? ('get' | 'set')? [SimpleIdentifier] [FormalParameterList]
*/
class FunctionDeclaration extends CompilationUnitMember {
/**
- * The token representing the 'external' keyword, or `null` if this is not an external
- * function.
+ * The token representing the 'external' keyword, or `null` if this is not an
+ * external function.
*/
Token externalKeyword;
@@ -8648,8 +8017,8 @@
TypeName _returnType;
/**
- * The token representing the 'get' or 'set' keyword, or `null` if this is a function
- * declaration rather than a property declaration.
+ * The token representing the 'get' or 'set' keyword, or `null` if this is a
+ * function declaration rather than a property declaration.
*/
Token propertyKeyword;
@@ -8664,15 +8033,12 @@
FunctionExpression _functionExpression;
/**
- * Initialize a newly created function declaration.
- *
- * @param comment the documentation comment associated with this function
- * @param metadata the annotations associated with this function
- * @param externalKeyword the token representing the 'external' keyword
- * @param returnType the return type of the function
- * @param propertyKeyword the token representing the 'get' or 'set' keyword
- * @param name the name of the function
- * @param functionExpression the function expression being wrapped
+ * Initialize a newly created function declaration. Either or both of the
+ * [comment] and [metadata] can be `null` if the function does not have the
+ * corresponding attribute. The [externalKeyword] can be `null` if the
+ * function is not an external function. The [returnType] can be `null` if no
+ * return type was specified. The [propertyKeyword] can be `null` if the
+ * function is neither a getter or a setter.
*/
FunctionDeclaration(Comment comment, List<Annotation> metadata,
this.externalKeyword, TypeName returnType, this.propertyKeyword,
@@ -8714,15 +8080,12 @@
/**
* Return the function expression being wrapped.
- *
- * @return the function expression being wrapped
*/
FunctionExpression get functionExpression => _functionExpression;
/**
- * Set the function expression being wrapped to the given function expression.
- *
- * @param functionExpression the function expression being wrapped
+ * Set the function expression being wrapped to the given
+ * [functionExpression].
*/
void set functionExpression(FunctionExpression functionExpression) {
_functionExpression = becomeParentOf(functionExpression);
@@ -8730,8 +8093,6 @@
/**
* Return `true` if this function declares a getter.
- *
- * @return `true` if this function declares a getter
*/
bool get isGetter =>
propertyKeyword != null &&
@@ -8739,8 +8100,6 @@
/**
* Return `true` if this function declares a setter.
- *
- * @return `true` if this function declares a setter
*/
bool get isSetter =>
propertyKeyword != null &&
@@ -8748,31 +8107,24 @@
/**
* Return the name of the function, or `null` if the function is not named.
- *
- * @return the name of the function
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the function to the given identifier.
- *
- * @param identifier the name of the function
+ * Set the name of the function to the given [identifier].
*/
void set name(SimpleIdentifier identifier) {
_name = becomeParentOf(identifier);
}
/**
- * Return the return type of the function, or `null` if no return type was declared.
- *
- * @return the return type of the function
+ * Return the return type of the function, or `null` if no return type was
+ * declared.
*/
TypeName get returnType => _returnType;
/**
- * Set the return type of the function to the given name.
- *
- * @param returnType the return type of the function
+ * Set the return type of the function to the given [returnType].
*/
void set returnType(TypeName returnType) {
_returnType = becomeParentOf(returnType);
@@ -8784,15 +8136,14 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_returnType, visitor);
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_functionExpression, visitor);
+ _safelyVisitChild(_returnType, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_functionExpression, visitor);
}
}
/**
- * Instances of the class `FunctionDeclarationStatement` wrap a [FunctionDeclaration
- ] as a statement.
+ * A [FunctionDeclaration] used as a statement.
*/
class FunctionDeclarationStatement extends Statement {
/**
@@ -8802,8 +8153,6 @@
/**
* Initialize a newly created function declaration statement.
- *
- * @param functionDeclaration the the function declaration being wrapped
*/
FunctionDeclarationStatement(FunctionDeclaration functionDeclaration) {
_functionDeclaration = becomeParentOf(functionDeclaration);
@@ -8820,15 +8169,12 @@
/**
* Return the function declaration being wrapped.
- *
- * @return the function declaration being wrapped
*/
FunctionDeclaration get functionDeclaration => _functionDeclaration;
/**
- * Set the function declaration being wrapped to the given function declaration.
- *
- * @param functionDeclaration the function declaration being wrapped
+ * Set the function declaration being wrapped to the given
+ * [functionDeclaration].
*/
void set functionDeclaration(FunctionDeclaration functionDeclaration) {
_functionDeclaration = becomeParentOf(functionDeclaration);
@@ -8839,17 +8185,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_functionDeclaration, visitor);
+ _safelyVisitChild(_functionDeclaration, visitor);
}
}
/**
- * Instances of the class `FunctionExpression` represent a function expression.
+ * A function expression.
*
- * <pre>
- * functionExpression ::=
- * [FormalParameterList] [FunctionBody]
- * </pre>
+ * > functionExpression ::=
+ * > [FormalParameterList] [FunctionBody]
*/
class FunctionExpression extends Expression {
/**
@@ -8863,16 +8207,13 @@
FunctionBody _body;
/**
- * The element associated with the function, or `null` if the AST structure has not been
- * resolved.
+ * The element associated with the function, or `null` if the AST structure
+ * has not been resolved.
*/
ExecutableElement element;
/**
* Initialize a newly created function declaration.
- *
- * @param parameters the parameters associated with the function
- * @param body the body of the function
*/
FunctionExpression(FormalParameterList parameters, FunctionBody body) {
_parameters = becomeParentOf(parameters);
@@ -8893,15 +8234,11 @@
/**
* Return the body of the function, or `null` if this is an external function.
- *
- * @return the body of the function
*/
FunctionBody get body => _body;
/**
- * Set the body of the function to the given function body.
- *
- * @param functionBody the body of the function
+ * Set the body of the function to the given [functionBody].
*/
void set body(FunctionBody functionBody) {
_body = becomeParentOf(functionBody);
@@ -8926,15 +8263,12 @@
/**
* Return the parameters associated with the function.
- *
- * @return the parameters associated with the function
*/
FormalParameterList get parameters => _parameters;
/**
- * Set the parameters associated with the function to the given list of parameters.
- *
- * @param parameters the parameters associated with the function
+ * Set the parameters associated with the function to the given list of
+ * [parameters].
*/
void set parameters(FormalParameterList parameters) {
_parameters = becomeParentOf(parameters);
@@ -8948,22 +8282,19 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_parameters, visitor);
- safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_parameters, visitor);
+ _safelyVisitChild(_body, visitor);
}
}
/**
- * Instances of the class `FunctionExpressionInvocation` represent the invocation of a
- * function resulting from evaluating an expression. Invocations of methods and other forms of
- * functions are represented by [MethodInvocation] nodes. Invocations of
- * getters and setters are represented by either [PrefixedIdentifier] or
- * [PropertyAccess] nodes.
+ * The invocation of a function resulting from evaluating an expression.
+ * Invocations of methods and other forms of functions are represented by
+ * [MethodInvocation] nodes. Invocations of getters and setters are represented
+ * by either [PrefixedIdentifier] or [PropertyAccess] nodes.
*
- * <pre>
- * functionExpressionInvoction ::=
- * [Expression] [ArgumentList]
- * </pre>
+ * > functionExpressionInvoction ::=
+ * > [Expression] [ArgumentList]
*/
class FunctionExpressionInvocation extends Expression {
/**
@@ -8977,22 +8308,21 @@
ArgumentList _argumentList;
/**
- * The element associated with the function being invoked based on static type information, or
- * `null` if the AST structure has not been resolved or the function could not be resolved.
+ * The element associated with the function being invoked based on static type
+ * information, or `null` if the AST structure has not been resolved or the
+ * function could not be resolved.
*/
ExecutableElement staticElement;
/**
- * The element associated with the function being invoked based on propagated type information, or
- * `null` if the AST structure has not been resolved or the function could not be resolved.
+ * The element associated with the function being invoked based on propagated
+ * type information, or `null` if the AST structure has not been resolved or
+ * the function could not be resolved.
*/
ExecutableElement propagatedElement;
/**
* Initialize a newly created function expression invocation.
- *
- * @param function the expression producing the function being invoked
- * @param argumentList the list of arguments to the method
*/
FunctionExpressionInvocation(Expression function, ArgumentList argumentList) {
_function = becomeParentOf(function);
@@ -9001,15 +8331,11 @@
/**
* Return the list of arguments to the method.
- *
- * @return the list of arguments to the method
*/
ArgumentList get argumentList => _argumentList;
/**
- * Set the list of arguments to the method to the given list.
- *
- * @param argumentList the list of arguments to the method
+ * Set the list of arguments to the method to the given [argumentList].
*/
void set argumentList(ArgumentList argumentList) {
_argumentList = becomeParentOf(argumentList);
@@ -9019,12 +8345,11 @@
Token get beginToken => _function.beginToken;
/**
- * Return the best element available for the function being invoked. If resolution was able to
- * find a better element based on type propagation, that element will be returned. Otherwise, the
- * element found using the result of static analysis will be returned. If resolution has not been
+ * Return the best element available for the function being invoked. If
+ * resolution was able to find a better element based on type propagation,
+ * that element will be returned. Otherwise, the element found using the
+ * result of static analysis will be returned. If resolution has not been
* performed, then `null` will be returned.
- *
- * @return the best element available for this function
*/
ExecutableElement get bestElement {
ExecutableElement element = propagatedElement;
@@ -9047,18 +8372,15 @@
/**
* Return the expression producing the function being invoked.
- *
- * @return the expression producing the function being invoked
*/
Expression get function => _function;
/**
- * Set the expression producing the function being invoked to the given expression.
- *
- * @param function the expression producing the function being invoked
+ * Set the expression producing the function being invoked to the given
+ * [expression].
*/
- void set function(Expression function) {
- _function = becomeParentOf(function);
+ void set function(Expression expression) {
+ _function = becomeParentOf(expression);
}
@override
@@ -9069,26 +8391,24 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_function, visitor);
- safelyVisitChild(_argumentList, visitor);
+ _safelyVisitChild(_function, visitor);
+ _safelyVisitChild(_argumentList, visitor);
}
}
/**
- * Instances of the class `FunctionTypeAlias` represent a function type alias.
+ * A function type alias.
*
- * <pre>
- * functionTypeAlias ::=
- * functionPrefix [TypeParameterList]? [FormalParameterList] ';'
- *
- * functionPrefix ::=
- * [TypeName]? [SimpleIdentifier]
- * </pre>
+ * > functionTypeAlias ::=
+ * > functionPrefix [TypeParameterList]? [FormalParameterList] ';'
+ * >
+ * > functionPrefix ::=
+ * > [TypeName]? [SimpleIdentifier]
*/
class FunctionTypeAlias extends TypeAlias {
/**
- * The name of the return type of the function type being defined, or `null` if no return
- * type was given.
+ * The name of the return type of the function type being defined, or `null`
+ * if no return type was given.
*/
TypeName _returnType;
@@ -9098,8 +8418,8 @@
SimpleIdentifier _name;
/**
- * The type parameters for the function type, or `null` if the function type does not have
- * any type parameters.
+ * The type parameters for the function type, or `null` if the function type
+ * does not have any type parameters.
*/
TypeParameterList _typeParameters;
@@ -9109,16 +8429,11 @@
FormalParameterList _parameters;
/**
- * Initialize a newly created function type alias.
- *
- * @param comment the documentation comment associated with this type alias
- * @param metadata the annotations associated with this type alias
- * @param keyword the token representing the 'typedef' keyword
- * @param returnType the name of the return type of the function type being defined
- * @param name the name of the type being declared
- * @param typeParameters the type parameters for the type
- * @param parameters the parameters associated with the function
- * @param semicolon the semicolon terminating the declaration
+ * Initialize a newly created function type alias. Either or both of the
+ * [comment] and [metadata] can be `null` if the function does not have the
+ * corresponding attribute. The [returnType] can be `null` if no return type
+ * was specified. The [typeParameters] can be `null` if the function has no
+ * type parameters.
*/
FunctionTypeAlias(Comment comment, List<Annotation> metadata, Token keyword,
TypeName returnType, SimpleIdentifier name, TypeParameterList typeParameters,
@@ -9145,15 +8460,11 @@
/**
* Return the name of the function type being declared.
- *
- * @return the name of the function type being declared
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the function type being declared to the given identifier.
- *
- * @param name the name of the function type being declared
+ * Set the name of the function type being declared to the given [name].
*/
void set name(SimpleIdentifier name) {
_name = becomeParentOf(name);
@@ -9161,49 +8472,40 @@
/**
* Return the parameters associated with the function type.
- *
- * @return the parameters associated with the function type
*/
FormalParameterList get parameters => _parameters;
/**
- * Set the parameters associated with the function type to the given list of parameters.
- *
- * @param parameters the parameters associated with the function type
+ * Set the parameters associated with the function type to the given list of
+ * [parameters].
*/
void set parameters(FormalParameterList parameters) {
_parameters = becomeParentOf(parameters);
}
/**
- * Return the name of the return type of the function type being defined, or `null` if no
- * return type was given.
- *
- * @return the name of the return type of the function type being defined
+ * Return the name of the return type of the function type being defined, or
+ * `null` if no return type was given.
*/
TypeName get returnType => _returnType;
/**
- * Set the name of the return type of the function type being defined to the given type name.
- *
- * @param typeName the name of the return type of the function type being defined
+ * Set the name of the return type of the function type being defined to the
+ * given [typeName].
*/
void set returnType(TypeName typeName) {
_returnType = becomeParentOf(typeName);
}
/**
- * Return the type parameters for the function type, or `null` if the function type does not
- * have any type parameters.
- *
- * @return the type parameters for the function type
+ * Return the type parameters for the function type, or `null` if the function
+ * type does not have any type parameters.
*/
TypeParameterList get typeParameters => _typeParameters;
/**
- * Set the type parameters for the function type to the given list of parameters.
- *
- * @param typeParameters the type parameters for the function type
+ * Set the type parameters for the function type to the given list of
+ * [typeParameters].
*/
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = becomeParentOf(typeParameters);
@@ -9215,25 +8517,23 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_returnType, visitor);
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_typeParameters, visitor);
- safelyVisitChild(_parameters, visitor);
+ _safelyVisitChild(_returnType, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_typeParameters, visitor);
+ _safelyVisitChild(_parameters, visitor);
}
}
/**
- * Instances of the class `FunctionTypedFormalParameter` represent a function-typed formal
- * parameter.
+ * A function-typed formal parameter.
*
- * <pre>
- * functionSignature ::=
- * [TypeName]? [SimpleIdentifier] [FormalParameterList]
- * </pre>
+ * > functionSignature ::=
+ * > [TypeName]? [SimpleIdentifier] [FormalParameterList]
*/
class FunctionTypedFormalParameter extends NormalFormalParameter {
/**
- * The return type of the function, or `null` if the function does not have a return type.
+ * The return type of the function, or `null` if the function does not have a
+ * return type.
*/
TypeName _returnType;
@@ -9243,14 +8543,10 @@
FormalParameterList _parameters;
/**
- * Initialize a newly created formal parameter.
- *
- * @param comment the documentation comment associated with this parameter
- * @param metadata the annotations associated with this parameter
- * @param returnType the return type of the function, or `null` if the function does not
- * have a return type
- * @param identifier the name of the function-typed parameter
- * @param parameters the parameters of the function-typed parameter
+ * Initialize a newly created formal parameter. Either or both of the
+ * [comment] and [metadata] can be `null` if the parameter does not have the
+ * corresponding attribute. The [returnType] can be `null` if no return type
+ * was specified.
*/
FunctionTypedFormalParameter(Comment comment, List<Annotation> metadata,
TypeName returnType, SimpleIdentifier identifier,
@@ -9288,35 +8584,28 @@
/**
* Return the parameters of the function-typed parameter.
- *
- * @return the parameters of the function-typed parameter
*/
FormalParameterList get parameters => _parameters;
/**
- * Set the parameters of the function-typed parameter to the given parameters.
- *
- * @param parameters the parameters of the function-typed parameter
+ * Set the parameters of the function-typed parameter to the given
+ * [parameters].
*/
void set parameters(FormalParameterList parameters) {
_parameters = becomeParentOf(parameters);
}
/**
- * Return the return type of the function, or `null` if the function does not have a return
- * type.
- *
- * @return the return type of the function
+ * Return the return type of the function, or `null` if the function does not
+ * have a return type.
*/
TypeName get returnType => _returnType;
/**
- * Set the return type of the function to the given type.
- *
- * @param returnType the return type of the function
+ * Set the return type of the function to the given [type].
*/
- void set returnType(TypeName returnType) {
- _returnType = becomeParentOf(returnType);
+ void set returnType(TypeName type) {
+ _returnType = becomeParentOf(type);
}
@override
@@ -9325,27 +8614,28 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_returnType, visitor);
- safelyVisitChild(identifier, visitor);
- safelyVisitChild(_parameters, visitor);
+ _safelyVisitChild(_returnType, visitor);
+ _safelyVisitChild(identifier, visitor);
+ _safelyVisitChild(_parameters, visitor);
}
}
/**
- * Instances of the class `GeneralizingAstVisitor` implement an AST visitor that will
- * recursively visit all of the nodes in an AST structure (like instances of the class
- * [RecursiveAstVisitor]). In addition, when a node of a specific type is visited not only
- * will the visit method for that specific type of node be invoked, but additional methods for the
- * superclasses of that node will also be invoked. For example, using an instance of this class to
- * visit a [Block] will cause the method [visitBlock] to be invoked but will
- * also cause the methods [visitStatement] and [visitNode] to be
- * subsequently invoked. This allows visitors to be written that visit all statements without
- * needing to override the visit method for each of the specific subclasses of [Statement].
+ * An AST visitor that will recursively visit all of the nodes in an AST
+ * structure (like instances of the class [RecursiveAstVisitor]). In addition,
+ * when a node of a specific type is visited not only will the visit method for
+ * that specific type of node be invoked, but additional methods for the
+ * superclasses of that node will also be invoked. For example, using an
+ * instance of this class to visit a [Block] will cause the method [visitBlock]
+ * to be invoked but will also cause the methods [visitStatement] and
+ * [visitNode] to be subsequently invoked. This allows visitors to be written
+ * that visit all statements without needing to override the visit method for
+ * each of the specific subclasses of [Statement].
*
- * Subclasses that override a visit method must either invoke the overridden visit method or
- * explicitly invoke the more general visit method. Failure to do so will cause the visit methods
- * for superclasses of the node to not be invoked and will cause the children of the visited node to
- * not be visited.
+ * Subclasses that override a visit method must either invoke the overridden
+ * visit method or explicitly invoke the more general visit method. Failure to
+ * do so will cause the visit methods for superclasses of the node to not be
+ * invoked and will cause the children of the visited node to not be visited.
*/
class GeneralizingAstVisitor<R> implements AstVisitor<R> {
@override
@@ -9763,13 +9053,11 @@
}
/**
- * Instances of the class `HideCombinator` represent a combinator that restricts the names
- * being imported to those that are not in a given list.
+ * A combinator that restricts the names being imported to those that are not in
+ * a given list.
*
- * <pre>
- * hideCombinator ::=
- * 'hide' [SimpleIdentifier] (',' [SimpleIdentifier])*
- * </pre>
+ * > hideCombinator ::=
+ * > 'hide' [SimpleIdentifier] (',' [SimpleIdentifier])*
*/
class HideCombinator extends Combinator {
/**
@@ -9779,9 +9067,6 @@
/**
* Initialize a newly created import show combinator.
- *
- * @param keyword the comma introducing the combinator
- * @param hiddenNames the list of names from the library that are hidden by this combinator
*/
HideCombinator(Token keyword, List<SimpleIdentifier> hiddenNames)
: super(keyword) {
@@ -9797,9 +9082,8 @@
Token get endToken => _hiddenNames.endToken;
/**
- * Return the list of names from the library that are hidden by this combinator.
- *
- * @return the list of names from the library that are hidden by this combinator
+ * Return the list of names from the library that are hidden by this
+ * combinator.
*/
NodeList<SimpleIdentifier> get hiddenNames => _hiddenNames;
@@ -9813,23 +9097,19 @@
}
/**
- * The abstract class `Identifier` defines the behavior common to nodes that represent an
- * identifier.
+ * A node that represents an identifier.
*
- * <pre>
- * identifier ::=
- * [SimpleIdentifier]
- * | [PrefixedIdentifier]
- * </pre>
+ * > identifier ::=
+ * > [SimpleIdentifier]
+ * > | [PrefixedIdentifier]
*/
abstract class Identifier extends Expression {
/**
- * Return the best element available for this operator. If resolution was able to find a better
- * element based on type propagation, that element will be returned. Otherwise, the element found
- * using the result of static analysis will be returned. If resolution has not been performed,
- * then `null` will be returned.
- *
- * @return the best element available for this operator
+ * Return the best element available for this operator. If resolution was able
+ * to find a better element based on type propagation, that element will be
+ * returned. Otherwise, the element found using the result of static analysis
+ * will be returned. If resolution has not been performed, then `null` will be
+ * returned.
*/
Element get bestElement;
@@ -9838,49 +9118,38 @@
/**
* Return the lexical representation of the identifier.
- *
- * @return the lexical representation of the identifier
*/
String get name;
/**
- * Return the element associated with this identifier based on propagated type information, or
- * `null` if the AST structure has not been resolved or if this identifier could not be
- * resolved. One example of the latter case is an identifier that is not defined within the scope
- * in which it appears.
- *
- * @return the element associated with this identifier
+ * Return the element associated with this identifier based on propagated type
+ * information, or `null` if the AST structure has not been resolved or if
+ * this identifier could not be resolved. One example of the latter case is an
+ * identifier that is not defined within the scope in which it appears.
*/
Element get propagatedElement;
/**
- * Return the element associated with this identifier based on static type information, or
- * `null` if the AST structure has not been resolved or if this identifier could not be
- * resolved. One example of the latter case is an identifier that is not defined within the scope
- * in which it appears
- *
- * @return the element associated with the operator
+ * Return the element associated with this identifier based on static type
+ * information, or `null` if the AST structure has not been resolved or if
+ * this identifier could not be resolved. One example of the latter case is an
+ * identifier that is not defined within the scope in which it appears
*/
Element get staticElement;
/**
- * Return `true` if the given name is visible only within the library in which it is
- * declared.
- *
- * @param name the name being tested
- * @return `true` if the given name is private
+ * Return `true` if the given [name] is visible only within the library in
+ * which it is declared.
*/
static bool isPrivateName(String name) =>
StringUtilities.startsWithChar(name, 0x5F);
}
/**
- * Instances of the class `IfStatement` represent an if statement.
+ * An if statement.
*
- * <pre>
- * ifStatement ::=
- * 'if' '(' [Expression] ')' [Statement] ('else' [Statement])?
- * </pre>
+ * > ifStatement ::=
+ * > 'if' '(' [Expression] ')' [Statement] ('else' [Statement])?
*/
class IfStatement extends Statement {
/**
@@ -9909,26 +9178,20 @@
Statement _thenStatement;
/**
- * The token representing the 'else' keyword, or `null` if there is no else statement.
+ * The token representing the 'else' keyword, or `null` if there is no else
+ * statement.
*/
Token elseKeyword;
/**
- * The statement that is executed if the condition evaluates to `false`, or `null` if
- * there is no else statement.
+ * The statement that is executed if the condition evaluates to `false`, or
+ * `null` if there is no else statement.
*/
Statement _elseStatement;
/**
- * Initialize a newly created if statement.
- *
- * @param ifKeyword the token representing the 'if' keyword
- * @param leftParenthesis the left parenthesis
- * @param condition the condition used to determine which of the statements is executed next
- * @param rightParenthesis the right parenthesis
- * @param thenStatement the statement that is executed if the condition evaluates to `true`
- * @param elseKeyword the token representing the 'else' keyword
- * @param elseStatement the statement that is executed if the condition evaluates to `false`
+ * Initialize a newly created if statement. The [elseKeyword] and
+ * [elseStatement] can be `null` if there is no else clause.
*/
IfStatement(this.ifKeyword, this.leftParenthesis, Expression condition,
this.rightParenthesis, Statement thenStatement, this.elseKeyword,
@@ -9952,35 +9215,28 @@
..add(_elseStatement);
/**
- * Return the condition used to determine which of the statements is executed next.
- *
- * @return the condition used to determine which statement is executed next
+ * Return the condition used to determine which of the statements is executed
+ * next.
*/
Expression get condition => _condition;
/**
- * Set the condition used to determine which of the statements is executed next to the given
- * expression.
- *
- * @param expression the condition used to determine which statement is executed next
+ * Set the condition used to determine which of the statements is executed
+ * next to the given [expression].
*/
void set condition(Expression expression) {
_condition = becomeParentOf(expression);
}
/**
- * Return the statement that is executed if the condition evaluates to `false`, or
- * `null` if there is no else statement.
- *
- * @return the statement that is executed if the condition evaluates to `false`
+ * Return the statement that is executed if the condition evaluates to
+ * `false`, or `null` if there is no else statement.
*/
Statement get elseStatement => _elseStatement;
/**
- * Set the statement that is executed if the condition evaluates to `false` to the given
- * statement.
- *
- * @param statement the statement that is executed if the condition evaluates to `false`
+ * Set the statement that is executed if the condition evaluates to `false`
+ * to the given [statement].
*/
void set elseStatement(Statement statement) {
_elseStatement = becomeParentOf(statement);
@@ -9996,16 +9252,12 @@
/**
* Return the statement that is executed if the condition evaluates to `true`.
- *
- * @return the statement that is executed if the condition evaluates to `true`
*/
Statement get thenStatement => _thenStatement;
/**
- * Set the statement that is executed if the condition evaluates to `true` to the given
- * statement.
- *
- * @param statement the statement that is executed if the condition evaluates to `true`
+ * Set the statement that is executed if the condition evaluates to `true` to
+ * the given [statement].
*/
void set thenStatement(Statement statement) {
_thenStatement = becomeParentOf(statement);
@@ -10016,20 +9268,17 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_condition, visitor);
- safelyVisitChild(_thenStatement, visitor);
- safelyVisitChild(_elseStatement, visitor);
+ _safelyVisitChild(_condition, visitor);
+ _safelyVisitChild(_thenStatement, visitor);
+ _safelyVisitChild(_elseStatement, visitor);
}
}
/**
- * Instances of the class `ImplementsClause` represent the "implements" clause in an class
- * declaration.
+ * The "implements" clause in an class declaration.
*
- * <pre>
- * implementsClause ::=
- * 'implements' [TypeName] (',' [TypeName])*
- * </pre>
+ * > implementsClause ::=
+ * > 'implements' [TypeName] (',' [TypeName])*
*/
class ImplementsClause extends AstNode {
/**
@@ -10044,9 +9293,6 @@
/**
* Initialize a newly created implements clause.
- *
- * @param keyword the token representing the 'implements' keyword
- * @param interfaces the interfaces that are being implemented
*/
ImplementsClause(this.keyword, List<TypeName> interfaces) {
_interfaces = new NodeList<TypeName>(this, interfaces);
@@ -10068,8 +9314,6 @@
/**
* Return the list of the interfaces that are being implemented.
- *
- * @return the list of the interfaces that are being implemented
*/
NodeList<TypeName> get interfaces => _interfaces;
@@ -10083,13 +9327,11 @@
}
/**
- * Instances of the class `ImportDirective` represent an import directive.
+ * An import directive.
*
- * <pre>
- * importDirective ::=
- * [Annotation] 'import' [StringLiteral] ('as' identifier)? [Combinator]* ';'
- * | [Annotation] 'import' [StringLiteral] 'deferred' 'as' identifier [Combinator]* ';'
- * </pre>
+ * > importDirective ::=
+ * > [Annotation] 'import' [StringLiteral] ('as' identifier)? [Combinator]* ';'
+ * > | [Annotation] 'import' [StringLiteral] 'deferred' 'as' identifier [Combinator]* ';'
*/
class ImportDirective extends NamespaceDirective {
static Comparator<ImportDirective> COMPARATOR =
@@ -10187,33 +9429,30 @@
};
/**
- * The token representing the 'deferred' token, or `null` if the imported is not deferred.
+ * The token representing the 'deferred' token, or `null` if the imported is
+ * not deferred.
*/
Token deferredToken;
/**
- * The token representing the 'as' token, or `null` if the imported names are not prefixed.
+ * The token representing the 'as' token, or `null` if the imported names are
+ * not prefixed.
*/
Token asToken;
/**
- * The prefix to be used with the imported names, or `null` if the imported names are not
- * prefixed.
+ * The prefix to be used with the imported names, or `null` if the imported
+ * names are not prefixed.
*/
SimpleIdentifier _prefix;
/**
- * Initialize a newly created import directive.
- *
- * @param comment the documentation comment associated with this directive
- * @param metadata the annotations associated with the directive
- * @param keyword the token representing the 'import' keyword
- * @param libraryUri the URI of the library being imported
- * @param deferredToken the token representing the 'deferred' token
- * @param asToken the token representing the 'as' token
- * @param prefix the prefix to be used with the imported names
- * @param combinators the combinators used to control how names are imported
- * @param semicolon the semicolon terminating the directive
+ * Initialize a newly created import directive. Either or both of the
+ * [comment] and [metadata] can be `null` if the function does not have the
+ * corresponding attribute. The [deferredToken] can be `null` if the import is
+ * not deferred. The [asToken] and [prefix] can be `null` if the import does
+ * not specify a prefix. The list of [combinators] can be `null` if there are
+ * no combinators.
*/
ImportDirective(Comment comment, List<Annotation> metadata, Token keyword,
StringLiteral libraryUri, this.deferredToken, this.asToken,
@@ -10235,20 +9474,16 @@
ImportElement get element => super.element as ImportElement;
/**
- * Return the prefix to be used with the imported names, or `null` if the imported names are
- * not prefixed.
- *
- * @return the prefix to be used with the imported names
+ * Return the prefix to be used with the imported names, or `null` if the
+ * imported names are not prefixed.
*/
SimpleIdentifier get prefix => _prefix;
/**
- * Set the prefix to be used with the imported names to the given identifier.
- *
- * @param prefix the prefix to be used with the imported names
+ * Set the prefix to be used with the imported names to the given [identifier].
*/
- void set prefix(SimpleIdentifier prefix) {
- _prefix = becomeParentOf(prefix);
+ void set prefix(SimpleIdentifier identifier) {
+ _prefix = becomeParentOf(identifier);
}
@override
@@ -10266,15 +9501,15 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_prefix, visitor);
+ _safelyVisitChild(_prefix, visitor);
combinators.accept(visitor);
}
}
/**
- * Instances of the class `IncrementalAstCloner` implement an object that will clone any AST
- * structure that it visits. The cloner will clone the structure, replacing the specified ASTNode
- * with a new ASTNode, mapping the old token stream to a new token stream, and preserving resolution
+ * An object that will clone any AST structure that it visits. The cloner will
+ * clone the structure, replacing the specified ASTNode with a new ASTNode,
+ * mapping the old token stream to a new token stream, and preserving resolution
* results.
*/
class IncrementalAstCloner implements AstVisitor<AstNode> {
@@ -10294,12 +9529,9 @@
final TokenMap _tokenMap;
/**
- * Construct a new instance that will replace `oldNode` with `newNode` in the process
- * of cloning an existing AST structure.
- *
- * @param oldNode the node to be replaced
- * @param newNode the replacement node
- * @param tokenMap a mapping of old tokens to new tokens (not `null`)
+ * Construct a new instance that will replace the [oldNode] with the [newNode]
+ * in the process of cloning an existing AST structure. The [tokenMap] is a
+ * mapping of old tokens to new tokens.
*/
IncrementalAstCloner(this._oldNode, this._newNode, this._tokenMap);
@@ -11362,23 +10594,21 @@
}
/**
- * Instances of the class `IndexExpression` represent an index expression.
+ * An index expression.
*
- * <pre>
- * indexExpression ::=
- * [Expression] '[' [Expression] ']'
- * </pre>
+ * > indexExpression ::=
+ * > [Expression] '[' [Expression] ']'
*/
class IndexExpression extends Expression {
/**
- * The expression used to compute the object being indexed, or `null` if this index
- * expression is part of a cascade expression.
+ * The expression used to compute the object being indexed, or `null` if this
+ * index expression is part of a cascade expression.
*/
Expression _target;
/**
- * The period ("..") before a cascaded index expression, or `null` if this index expression
- * is not part of a cascade expression.
+ * The period ("..") before a cascaded index expression, or `null` if this
+ * index expression is not part of a cascade expression.
*/
Token period;
@@ -11398,33 +10628,29 @@
Token rightBracket;
/**
- * The element associated with the operator based on the static type of the target, or
- * `null` if the AST structure has not been resolved or if the operator could not be
- * resolved.
+ * The element associated with the operator based on the static type of the
+ * target, or `null` if the AST structure has not been resolved or if the
+ * operator could not be resolved.
*/
MethodElement staticElement;
/**
- * The element associated with the operator based on the propagated type of the target, or
- * `null` if the AST structure has not been resolved or if the operator could not be
- * resolved.
+ * The element associated with the operator based on the propagated type of
+ * the target, or `null` if the AST structure has not been resolved or if the
+ * operator could not be resolved.
*/
MethodElement propagatedElement;
/**
- * If this expression is both in a getter and setter context, the [AuxiliaryElements] will
- * be set to hold onto the static and propagated information. The auxiliary element will hold onto
- * the elements from the getter context.
+ * If this expression is both in a getter and setter context, the
+ * [AuxiliaryElements] will be set to hold onto the static and propagated
+ * information. The auxiliary element will hold onto the elements from the
+ * getter context.
*/
AuxiliaryElements auxiliaryElements = null;
/**
* Initialize a newly created index expression.
- *
- * @param period the period ("..") before a cascaded index expression
- * @param leftBracket the left square bracket
- * @param index the expression used to compute the index
- * @param rightBracket the right square bracket
*/
IndexExpression.forCascade(this.period, this.leftBracket, Expression index,
this.rightBracket) {
@@ -11433,11 +10659,6 @@
/**
* Initialize a newly created index expression.
- *
- * @param target the expression used to compute the object being indexed
- * @param leftBracket the left square bracket
- * @param index the expression used to compute the index
- * @param rightBracket the right square bracket
*/
IndexExpression.forTarget(Expression target, this.leftBracket,
Expression index, this.rightBracket) {
@@ -11454,12 +10675,11 @@
}
/**
- * Return the best element available for this operator. If resolution was able to find a better
- * element based on type propagation, that element will be returned. Otherwise, the element found
- * using the result of static analysis will be returned. If resolution has not been performed,
- * then `null` will be returned.
- *
- * @return the best element available for this operator
+ * Return the best element available for this operator. If resolution was able
+ * to find a better element based on type propagation, that element will be
+ * returned. Otherwise, the element found using the result of static analysis
+ * will be returned. If resolution has not been performed, then `null` will be
+ * returned.
*/
MethodElement get bestElement {
MethodElement element = propagatedElement;
@@ -11485,15 +10705,11 @@
/**
* Return the expression used to compute the index.
- *
- * @return the expression used to compute the index
*/
Expression get index => _index;
/**
- * Set the expression used to compute the index to the given expression.
- *
- * @param expression the expression used to compute the index
+ * Set the expression used to compute the index to the given [expression].
*/
void set index(Expression expression) {
_index = becomeParentOf(expression);
@@ -11503,11 +10719,9 @@
bool get isAssignable => true;
/**
- * Return `true` if this expression is cascaded. If it is, then the target of this
- * expression is not stored locally but is stored in the nearest ancestor that is a
- * [CascadeExpression].
- *
- * @return `true` if this expression is cascaded
+ * Return `true` if this expression is cascaded. If it is, then the target of
+ * this expression is not stored locally but is stored in the nearest ancestor
+ * that is a [CascadeExpression].
*/
bool get isCascaded => period != null;
@@ -11515,14 +10729,13 @@
int get precedence => 15;
/**
- * If the AST structure has been resolved, and the function being invoked is known based on
- * propagated type information, then return the parameter element representing the parameter to
- * which the value of the index expression will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on propagated type information, then return the parameter
+ * element representing the parameter to which the value of the index
+ * expression will be bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.propagatedParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the index
- * expression will be bound
+ * This method is only intended to be used by
+ * [Expression.propagatedParameterElement].
*/
ParameterElement get propagatedParameterElementForIndex {
if (propagatedElement == null) {
@@ -11536,13 +10749,10 @@
}
/**
- * Return the expression used to compute the object being indexed. If this index expression is not
- * part of a cascade expression, then this is the same as [getTarget]. If this index
- * expression is part of a cascade expression, then the target expression stored with the cascade
- * expression is returned.
- *
- * @return the expression used to compute the object being indexed
- * See [target].
+ * Return the expression used to compute the object being indexed. If this
+ * index expression is not part of a cascade expression, then this is the same
+ * as [target]. If this index expression is part of a cascade expression, then
+ * the target expression stored with the cascade expression is returned.
*/
Expression get realTarget {
if (isCascaded) {
@@ -11559,14 +10769,13 @@
}
/**
- * If the AST structure has been resolved, and the function being invoked is known based on static
- * type information, then return the parameter element representing the parameter to which the
- * value of the index expression will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on static type information, then return the parameter element
+ * representing the parameter to which the value of the index expression will
+ * be bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.staticParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the index
- * expression will be bound
+ * This method is only intended to be used by
+ * [Expression.staticParameterElement].
*/
ParameterElement get staticParameterElementForIndex {
if (staticElement == null) {
@@ -11580,18 +10789,17 @@
}
/**
- * Return the expression used to compute the object being indexed, or `null` if this index
- * expression is part of a cascade expression.
+ * Return the expression used to compute the object being indexed, or `null`
+ * if this index expression is part of a cascade expression.
*
- * @return the expression used to compute the object being indexed
- * See [realTarget].
+ * Use [realTarget] to get the target independent of whether this is part of a
+ * cascade expression.
*/
Expression get target => _target;
/**
- * Set the expression used to compute the object being indexed to the given expression.
- *
- * @param expression the expression used to compute the object being indexed
+ * Set the expression used to compute the object being indexed to the given
+ * [expression].
*/
void set target(Expression expression) {
_target = becomeParentOf(expression);
@@ -11601,13 +10809,13 @@
accept(AstVisitor visitor) => visitor.visitIndexExpression(this);
/**
- * Return `true` if this expression is computing a right-hand value.
+ * Return `true` if this expression is computing a right-hand value (that is,
+ * if this expression is in a context where the operator '[]' will be
+ * invoked).
*
- * Note that [inGetterContext] and [inSetterContext] are not opposites, nor are
- * they mutually exclusive. In other words, it is possible for both methods to return `true`
- * when invoked on the same node.
- *
- * @return `true` if this expression is in a context where the operator '[]' will be invoked
+ * Note that [inGetterContext] and [inSetterContext] are not opposites, nor
+ * are they mutually exclusive. In other words, it is possible for both
+ * methods to return `true` when invoked on the same node.
*/
bool inGetterContext() {
AstNode parent = this.parent;
@@ -11622,14 +10830,13 @@
}
/**
- * Return `true` if this expression is computing a left-hand value.
+ * Return `true` if this expression is computing a left-hand value (that is,
+ * if this expression is in a context where the operator '[]=' will be
+ * invoked).
*
- * Note that [inGetterContext] and [inSetterContext] are not opposites, nor are
- * they mutually exclusive. In other words, it is possible for both methods to return `true`
- * when invoked on the same node.
- *
- * @return `true` if this expression is in a context where the operator '[]=' will be
- * invoked
+ * Note that [inGetterContext] and [inSetterContext] are not opposites, nor
+ * are they mutually exclusive. In other words, it is possible for both
+ * methods to return `true` when invoked on the same node.
*/
bool inSetterContext() {
AstNode parent = this.parent;
@@ -11645,19 +10852,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_target, visitor);
- safelyVisitChild(_index, visitor);
+ _safelyVisitChild(_target, visitor);
+ _safelyVisitChild(_index, visitor);
}
}
/**
- * Instances of the class `InstanceCreationExpression` represent an instance creation
- * expression.
+ * An instance creation expression.
*
- * <pre>
- * newExpression ::=
- * ('new' | 'const') [TypeName] ('.' [SimpleIdentifier])? [ArgumentList]
- * </pre>
+ * > newExpression ::=
+ * > ('new' | 'const') [TypeName] ('.' [SimpleIdentifier])? [ArgumentList]
*/
class InstanceCreationExpression extends Expression {
/**
@@ -11676,8 +10880,9 @@
ArgumentList _argumentList;
/**
- * The element associated with the constructor based on static type information, or `null`
- * if the AST structure has not been resolved or if the constructor could not be resolved.
+ * The element associated with the constructor based on static type
+ * information, or `null` if the AST structure has not been resolved or if the
+ * constructor could not be resolved.
*/
ConstructorElement staticElement;
@@ -11688,10 +10893,6 @@
/**
* Initialize a newly created instance creation expression.
- *
- * @param keyword the keyword used to indicate how an object should be created
- * @param constructorName the name of the constructor to be invoked
- * @param argumentList the list of arguments to the constructor
*/
InstanceCreationExpression(this.keyword, ConstructorName constructorName,
ArgumentList argumentList) {
@@ -11701,15 +10902,11 @@
/**
* Return the list of arguments to the constructor.
- *
- * @return the list of arguments to the constructor
*/
ArgumentList get argumentList => _argumentList;
/**
- * Set the list of arguments to the constructor to the given list.
- *
- * @param argumentList the list of arguments to the constructor
+ * Set the list of arguments to the constructor to the given [argumentList].
*/
void set argumentList(ArgumentList argumentList) {
_argumentList = becomeParentOf(argumentList);
@@ -11726,27 +10923,22 @@
/**
* Return the name of the constructor to be invoked.
- *
- * @return the name of the constructor to be invoked
*/
ConstructorName get constructorName => _constructorName;
/**
- * Set the name of the constructor to be invoked to the given name.
- *
- * @param constructorName the name of the constructor to be invoked
+ * Set the name of the constructor to be invoked to the given [name].
*/
- void set constructorName(ConstructorName constructorName) {
- _constructorName = becomeParentOf(constructorName);
+ void set constructorName(ConstructorName name) {
+ _constructorName = becomeParentOf(name);
}
@override
Token get endToken => _argumentList.endToken;
/**
- * Return `true` if this creation expression is used to invoke a constant constructor.
- *
- * @return `true` if this creation expression is used to invoke a constant constructor
+ * Return `true` if this creation expression is used to invoke a constant
+ * constructor.
*/
bool get isConst =>
keyword is KeywordToken && (keyword as KeywordToken).keyword == Keyword.CONST;
@@ -11759,26 +10951,24 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_constructorName, visitor);
- safelyVisitChild(_argumentList, visitor);
+ _safelyVisitChild(_constructorName, visitor);
+ _safelyVisitChild(_argumentList, visitor);
}
}
/**
- * Instances of the class `IntegerLiteral` represent an integer literal expression.
+ * An integer literal expression.
*
- * <pre>
- * integerLiteral ::=
- * decimalIntegerLiteral
- * | hexidecimalIntegerLiteral
- *
- * decimalIntegerLiteral ::=
- * decimalDigit+
- *
- * hexidecimalIntegerLiteral ::=
- * '0x' hexidecimalDigit+
- * | '0X' hexidecimalDigit+
- * </pre>
+ * > integerLiteral ::=
+ * > decimalIntegerLiteral
+ * > | hexidecimalIntegerLiteral
+ * >
+ * > decimalIntegerLiteral ::=
+ * > decimalDigit+
+ * >
+ * > hexidecimalIntegerLiteral ::=
+ * > '0x' hexidecimalDigit+
+ * > | '0X' hexidecimalDigit+
*/
class IntegerLiteral extends Literal {
/**
@@ -11793,9 +10983,6 @@
/**
* Initialize a newly created integer literal.
- *
- * @param literal the token representing the literal
- * @param value the value of the literal
*/
IntegerLiteral(this.literal, this.value);
@@ -11821,32 +11008,27 @@
}
/**
- * The abstract class `InterpolationElement` defines the behavior common to elements within a
- * [StringInterpolation].
+ * A node within a [StringInterpolation].
*
- * <pre>
- * interpolationElement ::=
- * [InterpolationExpression]
- * | [InterpolationString]
- * </pre>
+ * > interpolationElement ::=
+ * > [InterpolationExpression]
+ * > | [InterpolationString]
*/
abstract class InterpolationElement extends AstNode {
}
/**
- * Instances of the class `InterpolationExpression` represent an expression embedded in a
- * string interpolation.
+ * An expression embedded in a string interpolation.
*
- * <pre>
- * interpolationExpression ::=
- * '$' [SimpleIdentifier]
- * | '$' '{' [Expression] '}'
- * </pre>
+ * > interpolationExpression ::=
+ * > '$' [SimpleIdentifier]
+ * > | '$' '{' [Expression] '}'
*/
class InterpolationExpression extends InterpolationElement {
/**
- * The token used to introduce the interpolation expression; either '$' if the expression is a
- * simple identifier or '${' if the expression is a full expression.
+ * The token used to introduce the interpolation expression; either '$' if the
+ * expression is a simple identifier or '${' if the expression is a full
+ * expression.
*/
Token leftBracket;
@@ -11856,16 +11038,13 @@
Expression _expression;
/**
- * The right curly bracket, or `null` if the expression is an identifier without brackets.
+ * The right curly bracket, or `null` if the expression is an identifier
+ * without brackets.
*/
Token rightBracket;
/**
* Initialize a newly created interpolation expression.
- *
- * @param leftBracket the left curly bracket
- * @param expression the expression to be evaluated for the value to be converted into a string
- * @param rightBracket the right curly bracket
*/
InterpolationExpression(this.leftBracket, Expression expression,
this.rightBracket) {
@@ -11890,17 +11069,14 @@
}
/**
- * Return the expression to be evaluated for the value to be converted into a string.
- *
- * @return the expression to be evaluated for the value to be converted into a string
+ * Return the expression to be evaluated for the value to be converted into a
+ * string.
*/
Expression get expression => _expression;
/**
- * Set the expression to be evaluated for the value to be converted into a string to the given
- * expression.
- *
- * @param expression the expression to be evaluated for the value to be converted into a string
+ * Set the expression to be evaluated for the value to be converted into a
+ * string to the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -11911,18 +11087,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * Instances of the class `InterpolationString` represent a non-empty substring of an
- * interpolated string.
+ * A non-empty substring of an interpolated string.
*
- * <pre>
- * interpolationString ::=
- * characters
- * </pre>
+ * > interpolationString ::=
+ * > characters
*/
class InterpolationString extends InterpolationElement {
/**
@@ -11936,10 +11109,8 @@
String _value;
/**
- * Initialize a newly created string of characters that are part of a string interpolation.
- *
- * @param the characters that will be added to the string
- * @param value the value of the literal
+ * Initialize a newly created string of characters that are part of a string
+ * interpolation.
*/
InterpolationString(this.contents, String value) {
_value = value;
@@ -11992,15 +11163,11 @@
/**
* Return the value of the literal.
- *
- * @return the value of the literal
*/
String get value => _value;
/**
- * Set the value of the literal to the given string.
- *
- * @param string the value of the literal
+ * Set the value of the literal to the given [string].
*/
void set value(String string) {
_value = string;
@@ -12015,12 +11182,10 @@
}
/**
- * Instances of the class `IsExpression` represent an is expression.
+ * An is expression.
*
- * <pre>
- * isExpression ::=
- * [Expression] 'is' '!'? [TypeName]
- * </pre>
+ * > isExpression ::=
+ * > [Expression] 'is' '!'? [TypeName]
*/
class IsExpression extends Expression {
/**
@@ -12044,12 +11209,8 @@
TypeName _type;
/**
- * Initialize a newly created is expression.
- *
- * @param expression the expression used to compute the value whose type is being tested
- * @param isOperator the is operator
- * @param notOperator the not operator, or `null` if the sense of the test is not negated
- * @param type the name of the type being tested for
+ * Initialize a newly created is expression. The [notOperator] can be `null`
+ * if the sense of the test is not negated.
*/
IsExpression(Expression expression, this.isOperator, this.notOperator,
TypeName type) {
@@ -12072,16 +11233,12 @@
/**
* Return the expression used to compute the value whose type is being tested.
- *
- * @return the expression used to compute the value whose type is being tested
*/
Expression get expression => _expression;
/**
- * Set the expression used to compute the value whose type is being tested to the given
- * expression.
- *
- * @param expression the expression used to compute the value whose type is being tested
+ * Set the expression used to compute the value whose type is being tested to
+ * the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -12092,15 +11249,11 @@
/**
* Return the name of the type being tested for.
- *
- * @return the name of the type being tested for
*/
TypeName get type => _type;
/**
- * Set the name of the type being tested for to the given name.
- *
- * @param name the name of the type being tested for
+ * Set the name of the type being tested for to the given [name].
*/
void set type(TypeName name) {
_type = becomeParentOf(name);
@@ -12111,18 +11264,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
- safelyVisitChild(_type, visitor);
+ _safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_type, visitor);
}
}
/**
- * Instances of the class `Label` represent a label.
+ * A label on either a [LabeledStatement] or a [NamedExpression].
*
- * <pre>
- * label ::=
- * [SimpleIdentifier] ':'
- * </pre>
+ * > label ::=
+ * > [SimpleIdentifier] ':'
*/
class Label extends AstNode {
/**
@@ -12137,9 +11288,6 @@
/**
* Initialize a newly created label.
- *
- * @param label the label being applied
- * @param colon the colon that separates the label from whatever follows
*/
Label(SimpleIdentifier label, this.colon) {
_label = becomeParentOf(label);
@@ -12161,15 +11309,11 @@
/**
* Return the label being associated with the statement.
- *
- * @return the label being associated with the statement
*/
SimpleIdentifier get label => _label;
/**
- * Set the label being associated with the statement to the given label.
- *
- * @param label the label being associated with the statement
+ * Set the label being associated with the statement to the given [label].
*/
void set label(SimpleIdentifier label) {
_label = becomeParentOf(label);
@@ -12180,18 +11324,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_label, visitor);
+ _safelyVisitChild(_label, visitor);
}
}
/**
- * Instances of the class `LabeledStatement` represent a statement that has a label associated
- * with them.
+ * A statement that has a label associated with them.
*
- * <pre>
- * labeledStatement ::=
- * [Label]+ [Statement]
- * </pre>
+ * > labeledStatement ::=
+ * > [Label]+ [Statement]
*/
class LabeledStatement extends Statement {
/**
@@ -12206,9 +11347,6 @@
/**
* Initialize a newly created labeled statement.
- *
- * @param labels the labels being associated with the statement
- * @param statement the statement with which the labels are being associated
*/
LabeledStatement(List<Label> labels, Statement statement) {
_labels = new NodeList<Label>(this, labels);
@@ -12236,22 +11374,17 @@
/**
* Return the labels being associated with the statement.
- *
- * @return the labels being associated with the statement
*/
NodeList<Label> get labels => _labels;
/**
* Return the statement with which the labels are being associated.
- *
- * @return the statement with which the labels are being associated
*/
Statement get statement => _statement;
/**
- * Set the statement with which the labels are being associated to the given statement.
- *
- * @param statement the statement with which the labels are being associated
+ * Set the statement with which the labels are being associated to the given
+ * [statement].
*/
void set statement(Statement statement) {
_statement = becomeParentOf(statement);
@@ -12266,17 +11399,15 @@
@override
void visitChildren(AstVisitor visitor) {
_labels.accept(visitor);
- safelyVisitChild(_statement, visitor);
+ _safelyVisitChild(_statement, visitor);
}
}
/**
- * Instances of the class `LibraryDirective` represent a library directive.
+ * A library directive.
*
- * <pre>
- * libraryDirective ::=
- * [Annotation] 'library' [Identifier] ';'
- * </pre>
+ * > libraryDirective ::=
+ * > [Annotation] 'library' [Identifier] ';'
*/
class LibraryDirective extends Directive {
/**
@@ -12295,13 +11426,9 @@
Token semicolon;
/**
- * Initialize a newly created library directive.
- *
- * @param comment the documentation comment associated with this directive
- * @param metadata the annotations associated with the directive
- * @param libraryToken the token representing the 'library' token
- * @param name the name of the library being defined
- * @param semicolon the semicolon terminating the directive
+ * Initialize a newly created library directive. Either or both of the
+ * [comment] and [metadata] can be `null` if the directive does not have the
+ * corresponding attribute.
*/
LibraryDirective(Comment comment, List<Annotation> metadata,
this.libraryToken, LibraryIdentifier name, this.semicolon)
@@ -12326,15 +11453,11 @@
/**
* Return the name of the library being defined.
- *
- * @return the name of the library being defined
*/
LibraryIdentifier get name => _name;
/**
- * Set the name of the library being defined to the given name.
- *
- * @param name the name of the library being defined
+ * Set the name of the library being defined to the given [name].
*/
void set name(LibraryIdentifier name) {
_name = becomeParentOf(name);
@@ -12346,17 +11469,15 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_name, visitor);
}
}
/**
- * Instances of the class `LibraryIdentifier` represent the identifier for a library.
+ * The identifier for a library.
*
- * <pre>
- * libraryIdentifier ::=
- * [SimpleIdentifier] ('.' [SimpleIdentifier])*
- * </pre>
+ * > libraryIdentifier ::=
+ * > [SimpleIdentifier] ('.' [SimpleIdentifier])*
*/
class LibraryIdentifier extends Identifier {
/**
@@ -12366,8 +11487,6 @@
/**
* Initialize a newly created prefixed identifier.
- *
- * @param components the components of the identifier
*/
LibraryIdentifier(List<SimpleIdentifier> components) {
_components = new NodeList<SimpleIdentifier>(this, components);
@@ -12387,8 +11506,6 @@
/**
* Return the components of the identifier.
- *
- * @return the components of the identifier
*/
NodeList<SimpleIdentifier> get components => _components;
@@ -12429,12 +11546,10 @@
}
/**
- * Instances of the class `ListLiteral` represent a list literal.
+ * A list literal.
*
- * <pre>
- * listLiteral ::=
- * 'const'? ('<' [TypeName] '>')? '[' ([Expression] ','?)? ']'
- * </pre>
+ * > listLiteral ::=
+ * > 'const'? ('<' [TypeName] '>')? '[' ([Expression] ','?)? ']'
*/
class ListLiteral extends TypedLiteral {
/**
@@ -12453,14 +11568,10 @@
Token rightBracket;
/**
- * Initialize a newly created list literal.
- *
- * @param constKeyword the token representing the 'const' keyword
- * @param typeArguments the type argument associated with this literal, or `null` if no type
- * arguments were declared
- * @param leftBracket the left square bracket
- * @param elements the expressions used to compute the elements of the list
- * @param rightBracket the right square bracket
+ * Initialize a newly created list literal. The [constKeyword] can be `null`
+ * if the literal is not a constant. The [typeArguments] can be `null` if no
+ * type arguments were declared. The list of [elements] can be `null` if the
+ * list is empty.
*/
ListLiteral(Token constKeyword, TypeArgumentList typeArguments,
this.leftBracket, List<Expression> elements, this.rightBracket)
@@ -12491,8 +11602,6 @@
/**
* Return the expressions used to compute the elements of the list.
- *
- * @return the expressions used to compute the elements of the list
*/
NodeList<Expression> get elements => _elements;
@@ -12510,19 +11619,16 @@
}
/**
- * The abstract class `Literal` defines the behavior common to nodes that represent a literal
- * expression.
+ * A node that represents a literal expression.
*
- * <pre>
- * literal ::=
- * [BooleanLiteral]
- * | [DoubleLiteral]
- * | [IntegerLiteral]
- * | [ListLiteral]
- * | [MapLiteral]
- * | [NullLiteral]
- * | [StringLiteral]
- * </pre>
+ * > literal ::=
+ * > [BooleanLiteral]
+ * > | [DoubleLiteral]
+ * > | [IntegerLiteral]
+ * > | [ListLiteral]
+ * > | [MapLiteral]
+ * > | [NullLiteral]
+ * > | [StringLiteral]
*/
abstract class Literal extends Expression {
@override
@@ -12530,12 +11636,11 @@
}
/**
- * Instances of the class `MapLiteral` represent a literal map.
+ * A literal map.
*
- * <pre>
- * mapLiteral ::=
- * 'const'? ('<' [TypeName] (',' [TypeName])* '>')? '{' ([MapLiteralEntry] (',' [MapLiteralEntry])* ','?)? '}'
- * </pre>
+ * > mapLiteral ::=
+ * > 'const'? ('<' [TypeName] (',' [TypeName])* '>')?
+ * > '{' ([MapLiteralEntry] (',' [MapLiteralEntry])* ','?)? '}'
*/
class MapLiteral extends TypedLiteral {
/**
@@ -12554,14 +11659,9 @@
Token rightBracket;
/**
- * Initialize a newly created map literal.
- *
- * @param constKeyword the token representing the 'const' keyword
- * @param typeArguments the type argument associated with this literal, or `null` if no type
- * arguments were declared
- * @param leftBracket the left curly bracket
- * @param entries the entries in the map
- * @param rightBracket the right curly bracket
+ * Initialize a newly created map literal. The [constKeyword] can be `null` if
+ * the literal is not a constant. The [typeArguments] can be `null` if no type
+ * arguments were declared. The [entries] can be `null` if the map is empty.
*/
MapLiteral(Token constKeyword, TypeArgumentList typeArguments,
this.leftBracket, List<MapLiteralEntry> entries, this.rightBracket)
@@ -12596,8 +11696,6 @@
/**
* Return the entries in the map.
- *
- * @return the entries in the map
*/
NodeList<MapLiteralEntry> get entries => _entries;
@@ -12612,13 +11710,10 @@
}
/**
- * Instances of the class `MapLiteralEntry` represent a single key/value pair in a map
- * literal.
+ * A single key/value pair in a map literal.
*
- * <pre>
- * mapLiteralEntry ::=
- * [Expression] ':' [Expression]
- * </pre>
+ * > mapLiteralEntry ::=
+ * > [Expression] ':' [Expression]
*/
class MapLiteralEntry extends AstNode {
/**
@@ -12638,10 +11733,6 @@
/**
* Initialize a newly created map literal entry.
- *
- * @param key the expression computing the key with which the value will be associated
- * @param separator the colon that separates the key from the value
- * @param value the expression computing the value that will be associated with the key
*/
MapLiteralEntry(Expression key, this.separator, Expression value) {
_key = becomeParentOf(key);
@@ -12664,34 +11755,28 @@
Token get endToken => _value.endToken;
/**
- * Return the expression computing the key with which the value will be associated.
- *
- * @return the expression computing the key with which the value will be associated
+ * Return the expression computing the key with which the value will be
+ * associated.
*/
Expression get key => _key;
/**
- * Set the expression computing the key with which the value will be associated to the given
- * string.
- *
- * @param string the expression computing the key with which the value will be associated
+ * Set the expression computing the key with which the value will be
+ * associated to the given [string].
*/
void set key(Expression string) {
_key = becomeParentOf(string);
}
/**
- * Return the expression computing the value that will be associated with the key.
- *
- * @return the expression computing the value that will be associated with the key
+ * Return the expression computing the value that will be associated with the
+ * key.
*/
Expression get value => _value;
/**
- * Set the expression computing the value that will be associated with the key to the given
- * expression.
- *
- * @param expression the expression computing the value that will be associated with the key
+ * Set the expression computing the value that will be associated with the key
+ * to the given [expression].
*/
void set value(Expression expression) {
_value = becomeParentOf(expression);
@@ -12702,36 +11787,35 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_key, visitor);
- safelyVisitChild(_value, visitor);
+ _safelyVisitChild(_key, visitor);
+ _safelyVisitChild(_value, visitor);
}
}
/**
- * Instances of the class `MethodDeclaration` represent a method declaration.
+ * A method declaration.
*
- * <pre>
- * methodDeclaration ::=
- * methodSignature [FunctionBody]
- *
- * methodSignature ::=
- * 'external'? ('abstract' | 'static')? [Type]? ('get' | 'set')? methodName
- * [FormalParameterList]
- *
- * methodName ::=
- * [SimpleIdentifier]
- * | 'operator' [SimpleIdentifier]
- * </pre>
+ * > methodDeclaration ::=
+ * > methodSignature [FunctionBody]
+ * >
+ * > methodSignature ::=
+ * > 'external'? ('abstract' | 'static')? [Type]? ('get' | 'set')?
+ * > methodName [FormalParameterList]
+ * >
+ * > methodName ::=
+ * > [SimpleIdentifier]
+ * > | 'operator' [SimpleIdentifier]
*/
class MethodDeclaration extends ClassMember {
/**
- * The token for the 'external' keyword, or `null` if the constructor is not external.
+ * The token for the 'external' keyword, or `null` if the constructor is not
+ * external.
*/
Token externalKeyword;
/**
- * The token representing the 'abstract' or 'static' keyword, or `null` if neither modifier
- * was specified.
+ * The token representing the 'abstract' or 'static' keyword, or `null` if
+ * neither modifier was specified.
*/
Token modifierKeyword;
@@ -12741,14 +11825,14 @@
TypeName _returnType;
/**
- * The token representing the 'get' or 'set' keyword, or `null` if this is a method
- * declaration rather than a property declaration.
+ * The token representing the 'get' or 'set' keyword, or `null` if this is a
+ * method declaration rather than a property declaration.
*/
Token propertyKeyword;
/**
- * The token representing the 'operator' keyword, or `null` if this method does not declare
- * an operator.
+ * The token representing the 'operator' keyword, or `null` if this method
+ * does not declare an operator.
*/
Token operatorKeyword;
@@ -12758,7 +11842,8 @@
SimpleIdentifier _name;
/**
- * The parameters associated with the method, or `null` if this method declares a getter.
+ * The parameters associated with the method, or `null` if this method
+ * declares a getter.
*/
FormalParameterList _parameters;
@@ -12768,19 +11853,15 @@
FunctionBody _body;
/**
- * Initialize a newly created method declaration.
- *
- * @param externalKeyword the token for the 'external' keyword
- * @param comment the documentation comment associated with this method
- * @param metadata the annotations associated with this method
- * @param modifierKeyword the token representing the 'abstract' or 'static' keyword
- * @param returnType the return type of the method
- * @param propertyKeyword the token representing the 'get' or 'set' keyword
- * @param operatorKeyword the token representing the 'operator' keyword
- * @param name the name of the method
- * @param parameters the parameters associated with the method, or `null` if this method
- * declares a getter
- * @param body the body of the method
+ * Initialize a newly created method declaration. Either or both of the
+ * [comment] and [metadata] can be `null` if the declaration does not have the
+ * corresponding attribute. The [externalKeyword] can be `null` if the method
+ * is not external. The [modifierKeyword] can be `null` if the method is
+ * neither abstract nor static. The [returnType] can be `null` if no return
+ * type was specified. The [propertyKeyword] can be `null` if the method is
+ * neither a getter or a setter. The [operatorKeyword] can be `null` if the
+ * method does not implement an operator. The [parameters] must be `null` if
+ * this method declares a getter.
*/
MethodDeclaration(Comment comment, List<Annotation> metadata,
this.externalKeyword, this.modifierKeyword, TypeName returnType,
@@ -12795,15 +11876,11 @@
/**
* Return the body of the method.
- *
- * @return the body of the method
*/
FunctionBody get body => _body;
/**
- * Set the body of the method to the given function body.
- *
- * @param functionBody the body of the method
+ * Set the body of the method to the given [functionBody].
*/
void set body(FunctionBody functionBody) {
_body = becomeParentOf(functionBody);
@@ -12821,12 +11898,11 @@
..add(_body);
/**
- * Return the element associated with this method, or `null` if the AST structure has not
- * been resolved. The element can either be a [MethodElement], if this represents the
- * declaration of a normal method, or a [PropertyAccessorElement] if this represents the
- * declaration of either a getter or a setter.
- *
- * @return the element associated with this method
+ * Return the element associated with this method, or `null` if the AST
+ * structure has not been resolved. The element can either be a
+ * [MethodElement], if this represents the declaration of a normal method, or
+ * a [PropertyAccessorElement] if this represents the declaration of either a
+ * getter or a setter.
*/
@override
ExecutableElement get element =>
@@ -12851,16 +11927,12 @@
/**
* Return `true` if this method is declared to be an abstract method.
- *
- * @return `true` if this method is declared to be an abstract method
*/
bool get isAbstract =>
externalKeyword == null && (_body is EmptyFunctionBody);
/**
* Return `true` if this method declares a getter.
- *
- * @return `true` if this method declares a getter
*/
bool get isGetter =>
propertyKeyword != null &&
@@ -12868,15 +11940,11 @@
/**
* Return `true` if this method declares an operator.
- *
- * @return `true` if this method declares an operator
*/
bool get isOperator => operatorKeyword != null;
/**
* Return `true` if this method declares a setter.
- *
- * @return `true` if this method declares a setter
*/
bool get isSetter =>
propertyKeyword != null &&
@@ -12884,8 +11952,6 @@
/**
* Return `true` if this method is declared to be a static method.
- *
- * @return `true` if this method is declared to be a static method
*/
bool get isStatic =>
modifierKeyword != null &&
@@ -12893,48 +11959,38 @@
/**
* Return the name of the method.
- *
- * @return the name of the method
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the method to the given identifier.
- *
- * @param identifier the name of the method
+ * Set the name of the method to the given [identifier].
*/
void set name(SimpleIdentifier identifier) {
_name = becomeParentOf(identifier);
}
/**
- * Return the parameters associated with the method, or `null` if this method declares a
- * getter.
- *
- * @return the parameters associated with the method
+ * Return the parameters associated with the method, or `null` if this method
+ * declares a getter.
*/
FormalParameterList get parameters => _parameters;
/**
- * Set the parameters associated with the method to the given list of parameters.
- *
- * @param parameters the parameters associated with the method
+ * Set the parameters associated with the method to the given list of
+ * [parameters].
*/
void set parameters(FormalParameterList parameters) {
_parameters = becomeParentOf(parameters);
}
/**
- * Return the return type of the method, or `null` if no return type was declared.
- *
- * @return the return type of the method
+ * Return the return type of the method, or `null` if no return type was
+ * declared.
*/
TypeName get returnType => _returnType;
/**
- * Set the return type of the method to the given type name.
- *
- * @param typeName the return type of the method
+ * Set the return type of the method to the given [typeName].
*/
void set returnType(TypeName typeName) {
_returnType = becomeParentOf(typeName);
@@ -12946,35 +12002,32 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_returnType, visitor);
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_parameters, visitor);
- safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_returnType, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_parameters, visitor);
+ _safelyVisitChild(_body, visitor);
}
}
/**
- * Instances of the class `MethodInvocation` represent the invocation of either a function or
- * a method. Invocations of functions resulting from evaluating an expression are represented by
- * [FunctionExpressionInvocation] nodes. Invocations of getters
- * and setters are represented by either [PrefixedIdentifier] or
- * [PropertyAccess] nodes.
+ * The invocation of either a function or a method. Invocations of functions
+ * resulting from evaluating an expression are represented by
+ * [FunctionExpressionInvocation] nodes. Invocations of getters and setters are
+ * represented by either [PrefixedIdentifier] or [PropertyAccess] nodes.
*
- * <pre>
- * methodInvoction ::=
- * ([Expression] '.')? [SimpleIdentifier] [ArgumentList]
- * </pre>
+ * > methodInvoction ::=
+ * > ([Expression] '.')? [SimpleIdentifier] [ArgumentList]
*/
class MethodInvocation extends Expression {
/**
- * The expression producing the object on which the method is defined, or `null` if there is
- * no target (that is, the target is implicitly `this`).
+ * The expression producing the object on which the method is defined, or
+ * `null` if there is no target (that is, the target is implicitly `this`).
*/
Expression _target;
/**
- * The period that separates the target from the method name, or `null` if there is no
- * target.
+ * The period that separates the target from the method name, or `null` if
+ * there is no target.
*/
Token period;
@@ -12989,12 +12042,8 @@
ArgumentList _argumentList;
/**
- * Initialize a newly created method invocation.
- *
- * @param target the expression producing the object on which the method is defined
- * @param period the period that separates the target from the method name
- * @param methodName the name of the method being invoked
- * @param argumentList the list of arguments to the method
+ * Initialize a newly created method invocation. The [target] and [period] can
+ * be `null` if there is no target.
*/
MethodInvocation(Expression target, this.period, SimpleIdentifier methodName,
ArgumentList argumentList) {
@@ -13005,15 +12054,11 @@
/**
* Return the list of arguments to the method.
- *
- * @return the list of arguments to the method
*/
ArgumentList get argumentList => _argumentList;
/**
- * Set the list of arguments to the method to the given list.
- *
- * @param argumentList the list of arguments to the method
+ * Set the list of arguments to the method to the given [argumentList].
*/
void set argumentList(ArgumentList argumentList) {
_argumentList = becomeParentOf(argumentList);
@@ -13040,26 +12085,20 @@
Token get endToken => _argumentList.endToken;
/**
- * Return `true` if this expression is cascaded. If it is, then the target of this
- * expression is not stored locally but is stored in the nearest ancestor that is a
- * [CascadeExpression].
- *
- * @return `true` if this expression is cascaded
+ * Return `true` if this expression is cascaded. If it is, then the target of
+ * this expression is not stored locally but is stored in the nearest ancestor
+ * that is a [CascadeExpression].
*/
bool get isCascaded =>
period != null && period.type == TokenType.PERIOD_PERIOD;
/**
* Return the name of the method being invoked.
- *
- * @return the name of the method being invoked
*/
SimpleIdentifier get methodName => _methodName;
/**
- * Set the name of the method being invoked to the given identifier.
- *
- * @param identifier the name of the method being invoked
+ * Set the name of the method being invoked to the given [identifier].
*/
void set methodName(SimpleIdentifier identifier) {
_methodName = becomeParentOf(identifier);
@@ -13069,13 +12108,10 @@
int get precedence => 15;
/**
- * Return the expression used to compute the receiver of the invocation. If this invocation is not
- * part of a cascade expression, then this is the same as [getTarget]. If this invocation
- * is part of a cascade expression, then the target stored with the cascade expression is
- * returned.
- *
- * @return the expression used to compute the receiver of the invocation
- * See [target].
+ * Return the expression used to compute the receiver of the invocation. If
+ * this invocation is not part of a cascade expression, then this is the same
+ * as [target]. If this invocation is part of a cascade expression, then the
+ * target stored with the cascade expression is returned.
*/
Expression get realTarget {
if (isCascaded) {
@@ -13092,19 +12128,18 @@
}
/**
- * Return the expression producing the object on which the method is defined, or `null` if
- * there is no target (that is, the target is implicitly `this`) or if this method
- * invocation is part of a cascade expression.
+ * Return the expression producing the object on which the method is defined,
+ * or `null` if there is no target (that is, the target is implicitly `this`)
+ * or if this method invocation is part of a cascade expression.
*
- * @return the expression producing the object on which the method is defined
- * See [realTarget].
+ * Use [realTarget] to get the target independent of whether this is part of a
+ * cascade expression.
*/
Expression get target => _target;
/**
- * Set the expression producing the object on which the method is defined to the given expression.
- *
- * @param expression the expression producing the object on which the method is defined
+ * Set the expression producing the object on which the method is defined to
+ * the given [expression].
*/
void set target(Expression expression) {
_target = becomeParentOf(expression);
@@ -13115,20 +12150,18 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_target, visitor);
- safelyVisitChild(_methodName, visitor);
- safelyVisitChild(_argumentList, visitor);
+ _safelyVisitChild(_target, visitor);
+ _safelyVisitChild(_methodName, visitor);
+ _safelyVisitChild(_argumentList, visitor);
}
}
/**
- * Instances of the class `NamedExpression` represent an expression that has a name associated
- * with it. They are used in method invocations when there are named parameters.
+ * An expression that has a name associated with it. They are used in method
+ * invocations when there are named parameters.
*
- * <pre>
- * namedExpression ::=
- * [Label] [Expression]
- * </pre>
+ * > namedExpression ::=
+ * > [Label] [Expression]
*/
class NamedExpression extends Expression {
/**
@@ -13142,10 +12175,7 @@
Expression _expression;
/**
- * Initialize a newly created named expression.
- *
- * @param name the name associated with the expression
- * @param expression the expression with which the name is associated
+ * Initialize a newly created named expression..
*/
NamedExpression(Label name, Expression expression) {
_name = becomeParentOf(name);
@@ -13161,11 +12191,9 @@
..add(_expression);
/**
- * Return the element representing the parameter being named by this expression, or `null`
- * if the AST structure has not been resolved or if there is no parameter with the same name as
- * this expression.
- *
- * @return the element representing the parameter being named by this expression
+ * Return the element representing the parameter being named by this
+ * expression, or `null` if the AST structure has not been resolved or if
+ * there is no parameter with the same name as this expression.
*/
ParameterElement get element {
Element element = _name.label.staticElement;
@@ -13180,15 +12208,12 @@
/**
* Return the expression with which the name is associated.
- *
- * @return the expression with which the name is associated
*/
Expression get expression => _expression;
/**
- * Set the expression with which the name is associated to the given expression.
- *
- * @param expression the expression with which the name is associated
+ * Set the expression with which the name is associated to the given
+ * [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -13196,15 +12221,11 @@
/**
* Return the name associated with the expression.
- *
- * @return the name associated with the expression
*/
Label get name => _name;
/**
- * Set the name associated with the expression to the given identifier.
- *
- * @param identifier the name associated with the expression
+ * Set the name associated with the expression to the given [identifier].
*/
void set name(Label identifier) {
_name = becomeParentOf(identifier);
@@ -13218,20 +12239,17 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * The abstract class `NamespaceDirective` defines the behavior common to nodes that represent
- * a directive that impacts the namespace of a library.
+ * A node that represents a directive that impacts the namespace of a library.
*
- * <pre>
- * directive ::=
- * [ExportDirective]
- * | [ImportDirective]
- * </pre>
+ * > directive ::=
+ * > [ExportDirective]
+ * > | [ImportDirective]
*/
abstract class NamespaceDirective extends UriBasedDirective {
/**
@@ -13250,14 +12268,10 @@
Token semicolon;
/**
- * Initialize a newly created namespace directive.
- *
- * @param comment the documentation comment associated with this directive
- * @param metadata the annotations associated with the directive
- * @param keyword the token representing the 'import' or 'export' keyword
- * @param libraryUri the URI of the library being imported or exported
- * @param combinators the combinators used to control which names are imported or exported
- * @param semicolon the semicolon terminating the directive
+ * Initialize a newly created namespace directive. Either or both of the
+ * [comment] and [metadata] can be `null` if the directive does not have the
+ * corresponding attribute. The list of [combinators] can be `null` if there
+ * are no combinators.
*/
NamespaceDirective(Comment comment, List<Annotation> metadata, this.keyword,
StringLiteral libraryUri, List<Combinator> combinators, this.semicolon)
@@ -13267,8 +12281,6 @@
/**
* Return the combinators used to control how names are imported or exported.
- *
- * @return the combinators used to control how names are imported or exported
*/
NodeList<Combinator> get combinators => _combinators;
@@ -13283,13 +12295,10 @@
}
/**
- * Instances of the class `NativeClause` represent the "native" clause in an class
- * declaration.
+ * The "native" clause in an class declaration.
*
- * <pre>
- * nativeClause ::=
- * 'native' [StringLiteral]
- * </pre>
+ * > nativeClause ::=
+ * > 'native' [StringLiteral]
*/
class NativeClause extends AstNode {
/**
@@ -13304,9 +12313,6 @@
/**
* Initialize a newly created native clause.
- *
- * @param keyword the token representing the 'native' keyword
- * @param name the name of the native object that implements the class.
*/
NativeClause(this.keyword, StringLiteral name) {
_name = becomeParentOf(name);
@@ -13328,15 +12334,12 @@
/**
* Return the name of the native object that implements the class.
- *
- * @return the name of the native object that implements the class
*/
StringLiteral get name => _name;
/**
- * Sets the name of the native object that implements the class.
- *
- * @param name the name of the native object that implements the class.
+ * Sets the name of the native object that implements the class to the given
+ * [name].
*/
void set name(StringLiteral name) {
_name = becomeParentOf(name);
@@ -13347,18 +12350,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_name, visitor);
}
}
/**
- * Instances of the class `NativeFunctionBody` represent a function body that consists of a
- * native keyword followed by a string literal.
+ * A function body that consists of a native keyword followed by a string
+ * literal.
*
- * <pre>
- * nativeFunctionBody ::=
- * 'native' [SimpleStringLiteral] ';'
- * </pre>
+ * > nativeFunctionBody ::=
+ * > 'native' [SimpleStringLiteral] ';'
*/
class NativeFunctionBody extends FunctionBody {
/**
@@ -13372,17 +12373,14 @@
StringLiteral _stringLiteral;
/**
- * The token representing the semicolon that marks the end of the function body.
+ * The token representing the semicolon that marks the end of the function
+ * body.
*/
Token semicolon;
/**
- * Initialize a newly created function body consisting of the 'native' token, a string literal,
- * and a semicolon.
- *
- * @param nativeToken the token representing 'native' that marks the start of the function body
- * @param stringLiteral the string literal
- * @param semicolon the token representing the semicolon that marks the end of the function body
+ * Initialize a newly created function body consisting of the 'native' token,
+ * a string literal, and a semicolon.
*/
NativeFunctionBody(this.nativeToken, StringLiteral stringLiteral,
this.semicolon) {
@@ -13406,15 +12404,12 @@
/**
* Return the string literal representing the string after the 'native' token.
- *
- * @return the string literal representing the string after the 'native' token
*/
StringLiteral get stringLiteral => _stringLiteral;
/**
- * Set the string literal representing the string after the 'native' token to the given string.
- *
- * @param stringLiteral the string literal representing the string after the 'native' token
+ * Set the string literal representing the string after the 'native' token to
+ * the given [stringLiteral].
*/
void set stringLiteral(StringLiteral stringLiteral) {
_stringLiteral = becomeParentOf(stringLiteral);
@@ -13425,13 +12420,12 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_stringLiteral, visitor);
+ _safelyVisitChild(_stringLiteral, visitor);
}
}
/**
- * Instances of the class `NodeList` represent a list of AST nodes that have a
- * common parent.
+ * A list of AST nodes that have a common parent.
*/
class NodeList<E extends AstNode> extends Object with ListMixin<E> {
/**
@@ -13564,10 +12558,10 @@
}
/**
- * Instances of the class `NodeLocator` locate the [AstNode] associated with a
- * source range, given the AST structure built from the source. More specifically, they will return
- * the [AstNode] with the shortest length whose source range completely encompasses
- * the specified range.
+ * An object used to locate the [AstNode] associated with a source range, given
+ * the AST structure built from the source. More specifically, they will return
+ * the [AstNode] with the shortest length whose source range completely
+ * encompasses the specified range.
*/
class NodeLocator extends UnifyingAstVisitor<Object> {
/**
@@ -13581,43 +12575,35 @@
int _endOffset = 0;
/**
- * The element that was found that corresponds to the given source range, or `null` if there
- * is no such element.
+ * The element that was found that corresponds to the given source range, or
+ * `null` if there is no such element.
*/
AstNode _foundNode;
/**
- * Initialize a newly created locator to locate one or more [AstNode] by locating
- * the node within an AST structure that corresponds to the given offset in the source.
- *
- * @param offset the offset used to identify the node
+ * Initialize a newly created locator to locate an [AstNode] by locating the
+ * node within an AST structure that corresponds to the given [offset] in the
+ * source.
*/
NodeLocator.con1(int offset) : this.con2(offset, offset);
/**
- * Initialize a newly created locator to locate one or more [AstNode] by locating
- * the node within an AST structure that corresponds to the given range of characters in the
- * source.
- *
- * @param start the start offset of the range used to identify the node
- * @param end the end offset of the range used to identify the node
+ * Initialize a newly created locator to locate an [AstNode] by locating the
+ * node within an AST structure that corresponds to the given range of
+ * characters (between the [startOffset] and [endOffset] in the source.
*/
NodeLocator.con2(this._startOffset, this._endOffset);
/**
- * Return the node that was found that corresponds to the given source range, or `null` if
- * there is no such node.
- *
- * @return the node that was found
+ * Return the node that was found that corresponds to the given source range
+ * or `null` if there is no such node.
*/
AstNode get foundNode => _foundNode;
/**
- * Search within the given AST node for an identifier representing a [DartElement] in the specified source range. Return the element that was found, or `null` if
- * no element was found.
- *
- * @param node the AST node within which to search
- * @return the element that was found
+ * Search within the given AST [node] for an identifier representing an
+ * element in the specified source range. Return the element that was found,
+ * or `null` if no element was found.
*/
AstNode searchWithin(AstNode node) {
if (node == null) {
@@ -13666,21 +12652,30 @@
}
/**
- * Instances of the class `NodeFoundException` are used to cancel visiting after a node has
- * been found.
+ * An exception used by [NodeLocator] to cancel visiting after a node has been
+ * found.
*/
class NodeLocator_NodeFoundException extends RuntimeException {
}
/**
- * Instances of the class `NodeReplacer` implement an object that will replace one child node
- * in an AST node with another node.
+ * An object that will replace one child node in an AST node with another node.
*/
class NodeReplacer implements AstVisitor<bool> {
+ /**
+ * The node being replaced.
+ */
final AstNode _oldNode;
+ /**
+ * The node that is replacing the old node.
+ */
final AstNode _newNode;
+ /**
+ * Initialize a newly created node locator to replace the [_oldNode] with the
+ * [_newNode].
+ */
NodeReplacer(this._oldNode, this._newNode);
@override
@@ -14803,13 +13798,12 @@
}
/**
- * Replace the old node with the new node in the AST structure containing the old node.
+ * Replace the [oldNode] with the [newNode] in the AST structure containing
+ * the old node. Return `true` if the replacement was successful.
*
- * @param oldNode
- * @param newNode
- * @return `true` if the replacement was successful
- * @throws IllegalArgumentException if either node is `null`, if the old node does not have
- * a parent node, or if the AST structure has been corrupted
+ * Throws an [IllegalArgumentException] if either node is `null`, if the old
+ * node does not have a parent node, or if the AST structure has been
+ * corrupted.
*/
static bool replace(AstNode oldNode, AstNode newNode) {
if (oldNode == null || newNode == null) {
@@ -14829,20 +13823,17 @@
}
/**
- * The abstract class `NormalFormalParameter` defines the behavior common to formal parameters
- * that are required (are not optional).
+ * A formal parameter that is required (is not optional).
*
- * <pre>
- * normalFormalParameter ::=
- * [FunctionTypedFormalParameter]
- * | [FieldFormalParameter]
- * | [SimpleFormalParameter]
- * </pre>
+ * > normalFormalParameter ::=
+ * > [FunctionTypedFormalParameter]
+ * > | [FieldFormalParameter]
+ * > | [SimpleFormalParameter]
*/
abstract class NormalFormalParameter extends FormalParameter {
/**
- * The documentation comment associated with this parameter, or `null` if this parameter
- * does not have a documentation comment associated with it.
+ * The documentation comment associated with this parameter, or `null` if this
+ * parameter does not have a documentation comment associated with it.
*/
Comment _comment;
@@ -14857,11 +13848,9 @@
SimpleIdentifier _identifier;
/**
- * Initialize a newly created formal parameter.
- *
- * @param comment the documentation comment associated with this parameter
- * @param metadata the annotations associated with this parameter
- * @param identifier the name of the parameter being declared
+ * Initialize a newly created formal parameter. Either or both of the
+ * [comment] and [metadata] can be `null` if the parameter does not have the
+ * corresponding attribute.
*/
NormalFormalParameter(Comment comment, List<Annotation> metadata,
SimpleIdentifier identifier) {
@@ -14871,17 +13860,14 @@
}
/**
- * Return the documentation comment associated with this parameter, or `null` if this
- * parameter does not have a documentation comment associated with it.
- *
- * @return the documentation comment associated with this parameter
+ * Return the documentation comment associated with this parameter, or `null`
+ * if this parameter does not have a documentation comment associated with it.
*/
Comment get documentationComment => _comment;
/**
- * Set the documentation comment associated with this parameter to the given comment
- *
- * @param comment the documentation comment to be associated with this parameter
+ * Set the documentation comment associated with this parameter to the given
+ * [comment].
*/
void set documentationComment(Comment comment) {
_comment = becomeParentOf(comment);
@@ -14891,9 +13877,7 @@
SimpleIdentifier get identifier => _identifier;
/**
- * Set the name of the parameter being declared to the given identifier.
- *
- * @param identifier the name of the parameter being declared
+ * Set the name of the parameter being declared to the given [identifier].
*/
void set identifier(SimpleIdentifier identifier) {
_identifier = becomeParentOf(identifier);
@@ -14910,15 +13894,11 @@
/**
* Return the annotations associated with this parameter.
- *
- * @return the annotations associated with this parameter
*/
NodeList<Annotation> get metadata => _metadata;
/**
- * Set the metadata associated with this node to the given metadata.
- *
- * @param metadata the metadata to be associated with this node
+ * Set the metadata associated with this node to the given [metadata].
*/
void set metadata(List<Annotation> metadata) {
_metadata.clear();
@@ -14926,11 +13906,8 @@
}
/**
- * Return an array containing the comment and annotations associated with this parameter, sorted
- * in lexical order.
- *
- * @return the comment and annotations associated with this parameter in the order in which they
- * appeared in the original source
+ * Return a list containing the comment and annotations associated with this
+ * parameter, sorted in lexical order.
*/
List<AstNode> get sortedCommentAndAnnotations {
return <AstNode>[]
@@ -14958,7 +13935,7 @@
// they often need to visit other nodes before visiting the identifier.
//
if (_commentIsBeforeAnnotations()) {
- safelyVisitChild(_comment, visitor);
+ _safelyVisitChild(_comment, visitor);
_metadata.accept(visitor);
} else {
for (AstNode child in sortedCommentAndAnnotations) {
@@ -14969,8 +13946,6 @@
/**
* Return `true` if the comment is lexically before any annotations.
- *
- * @return `true` if the comment is lexically before any annotations
*/
bool _commentIsBeforeAnnotations() {
if (_comment == null || _metadata.isEmpty) {
@@ -14982,12 +13957,10 @@
}
/**
- * Instances of the class `NullLiteral` represent a null literal expression.
+ * A null literal expression.
*
- * <pre>
- * nullLiteral ::=
- * 'null'
- * </pre>
+ * > nullLiteral ::=
+ * > 'null'
*/
class NullLiteral extends Literal {
/**
@@ -14997,8 +13970,6 @@
/**
* Initialize a newly created null literal.
- *
- * @param token the token representing the literal
*/
NullLiteral(this.literal);
@@ -15024,12 +13995,10 @@
}
/**
- * Instances of the class `ParenthesizedExpression` represent a parenthesized expression.
+ * A parenthesized expression.
*
- * <pre>
- * parenthesizedExpression ::=
- * '(' [Expression] ')'
- * </pre>
+ * > parenthesizedExpression ::=
+ * > '(' [Expression] ')'
*/
class ParenthesizedExpression extends Expression {
/**
@@ -15049,10 +14018,6 @@
/**
* Initialize a newly created parenthesized expression.
- *
- * @param leftParenthesis the left parenthesis
- * @param expression the expression within the parentheses
- * @param rightParenthesis the right parenthesis
*/
ParenthesizedExpression(this.leftParenthesis, Expression expression,
this.rightParenthesis) {
@@ -15073,15 +14038,11 @@
/**
* Return the expression within the parentheses.
- *
- * @return the expression within the parentheses
*/
Expression get expression => _expression;
/**
- * Set the expression within the parentheses to the given expression.
- *
- * @param expression the expression within the parentheses
+ * Set the expression within the parentheses to the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -15095,17 +14056,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * Instances of the class `PartDirective` represent a part directive.
+ * A part directive.
*
- * <pre>
- * partDirective ::=
- * [Annotation] 'part' [StringLiteral] ';'
- * </pre>
+ * > partDirective ::=
+ * > [Annotation] 'part' [StringLiteral] ';'
*/
class PartDirective extends UriBasedDirective {
/**
@@ -15119,13 +14078,9 @@
Token semicolon;
/**
- * Initialize a newly created part directive.
- *
- * @param comment the documentation comment associated with this directive
- * @param metadata the annotations associated with the directive
- * @param partToken the token representing the 'part' token
- * @param partUri the URI of the part being included
- * @param semicolon the semicolon terminating the directive
+ * Initialize a newly created part directive. Either or both of the [comment]
+ * and [metadata] can be `null` if the directive does not have the
+ * corresponding attribute.
*/
PartDirective(Comment comment, List<Annotation> metadata, this.partToken,
StringLiteral partUri, this.semicolon)
@@ -15157,12 +14112,10 @@
}
/**
- * Instances of the class `PartOfDirective` represent a part-of directive.
+ * A part-of directive.
*
- * <pre>
- * partOfDirective ::=
- * [Annotation] 'part' 'of' [Identifier] ';'
- * </pre>
+ * > partOfDirective ::=
+ * > [Annotation] 'part' 'of' [Identifier] ';'
*/
class PartOfDirective extends Directive {
/**
@@ -15186,14 +14139,9 @@
Token semicolon;
/**
- * Initialize a newly created part-of directive.
- *
- * @param comment the documentation comment associated with this directive
- * @param metadata the annotations associated with the directive
- * @param partToken the token representing the 'part' token
- * @param ofToken the token representing the 'of' token
- * @param libraryName the name of the library that the containing compilation unit is part of
- * @param semicolon the semicolon terminating the directive
+ * Initialize a newly created part-of directive. Either or both of the
+ * [comment] and [metadata] can be `null` if the directive does not have the
+ * corresponding attribute.
*/
PartOfDirective(Comment comment, List<Annotation> metadata, this.partToken,
this.ofToken, LibraryIdentifier libraryName, this.semicolon)
@@ -15218,16 +14166,14 @@
Token get keyword => partToken;
/**
- * Return the name of the library that the containing compilation unit is part of.
- *
- * @return the name of the library that the containing compilation unit is part of
+ * Return the name of the library that the containing compilation unit is part
+ * of.
*/
LibraryIdentifier get libraryName => _libraryName;
/**
- * Set the name of the library that the containing compilation unit is part of to the given name.
- *
- * @param libraryName the name of the library that the containing compilation unit is part of
+ * Set the name of the library that the containing compilation unit is part of
+ * to the given [libraryName].
*/
void set libraryName(LibraryIdentifier libraryName) {
_libraryName = becomeParentOf(libraryName);
@@ -15239,17 +14185,15 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_libraryName, visitor);
+ _safelyVisitChild(_libraryName, visitor);
}
}
/**
- * Instances of the class `PostfixExpression` represent a postfix unary expression.
+ * A postfix unary expression.
*
- * <pre>
- * postfixExpression ::=
- * [Expression] [Token]
- * </pre>
+ * > postfixExpression ::=
+ * > [Expression] [Token]
*/
class PostfixExpression extends Expression {
/**
@@ -15263,24 +14207,22 @@
Token operator;
/**
- * The element associated with this the operator based on the propagated type of the operand, or
- * `null` if the AST structure has not been resolved, if the operator is not user definable,
- * or if the operator could not be resolved.
+ * The element associated with this the operator based on the propagated type
+ * of the operand, or `null` if the AST structure has not been resolved, if
+ * the operator is not user definable, or if the operator could not be
+ * resolved.
*/
MethodElement propagatedElement;
/**
- * The element associated with the operator based on the static type of the operand, or
- * `null` if the AST structure has not been resolved, if the operator is not user definable,
- * or if the operator could not be resolved.
+ * The element associated with the operator based on the static type of the
+ * operand, or `null` if the AST structure has not been resolved, if the
+ * operator is not user definable, or if the operator could not be resolved.
*/
MethodElement staticElement;
/**
* Initialize a newly created postfix expression.
- *
- * @param operand the expression computing the operand for the operator
- * @param operator the postfix operator being applied to the operand
*/
PostfixExpression(Expression operand, this.operator) {
_operand = becomeParentOf(operand);
@@ -15290,12 +14232,11 @@
Token get beginToken => _operand.beginToken;
/**
- * Return the best element available for this operator. If resolution was able to find a better
- * element based on type propagation, that element will be returned. Otherwise, the element found
- * using the result of static analysis will be returned. If resolution has not been performed,
- * then `null` will be returned.
- *
- * @return the best element available for this operator
+ * Return the best element available for this operator. If resolution was able
+ * to find a better element based on type propagation, that element will be
+ * returned. Otherwise, the element found using the result of static analysis
+ * will be returned. If resolution has not been performed, then `null` will be
+ * returned.
*/
MethodElement get bestElement {
MethodElement element = propagatedElement;
@@ -15318,15 +14259,12 @@
/**
* Return the expression computing the operand for the operator.
- *
- * @return the expression computing the operand for the operator
*/
Expression get operand => _operand;
/**
- * Set the expression computing the operand for the operator to the given expression.
- *
- * @param expression the expression computing the operand for the operator
+ * Set the expression computing the operand for the operator to the given
+ * [expression].
*/
void set operand(Expression expression) {
_operand = becomeParentOf(expression);
@@ -15336,14 +14274,13 @@
int get precedence => 15;
/**
- * If the AST structure has been resolved, and the function being invoked is known based on
- * propagated type information, then return the parameter element representing the parameter to
- * which the value of the operand will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on propagated type information, then return the parameter
+ * element representing the parameter to which the value of the operand will
+ * be bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.propagatedParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the right
- * operand will be bound
+ * This method is only intended to be used by
+ * [Expression.propagatedParameterElement].
*/
ParameterElement get propagatedParameterElementForOperand {
if (propagatedElement == null) {
@@ -15357,14 +14294,13 @@
}
/**
- * If the AST structure has been resolved, and the function being invoked is known based on static
- * type information, then return the parameter element representing the parameter to which the
- * value of the operand will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on static type information, then return the parameter element
+ * representing the parameter to which the value of the operand will be bound.
+ * Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.staticParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the right
- * operand will be bound
+ * This method is only intended to be used by
+ * [Expression.staticParameterElement].
*/
ParameterElement get staticParameterElementForOperand {
if (staticElement == null) {
@@ -15382,19 +14318,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_operand, visitor);
+ _safelyVisitChild(_operand, visitor);
}
}
/**
- * Instances of the class `PrefixedIdentifier` represent either an identifier that is prefixed
- * or an access to an object property where the target of the property access is a simple
- * identifier.
+ * An identifier that is prefixed or an access to an object property where the
+ * target of the property access is a simple identifier.
*
- * <pre>
- * prefixedIdentifier ::=
- * [SimpleIdentifier] '.' [SimpleIdentifier]
- * </pre>
+ * > prefixedIdentifier ::=
+ * > [SimpleIdentifier] '.' [SimpleIdentifier]
*/
class PrefixedIdentifier extends Identifier {
/**
@@ -15414,10 +14347,6 @@
/**
* Initialize a newly created prefixed identifier.
- *
- * @param prefix the identifier being prefixed
- * @param period the period used to separate the prefix from the identifier
- * @param identifier the prefix associated with the library in which the identifier is defined
*/
PrefixedIdentifier(SimpleIdentifier prefix, this.period,
SimpleIdentifier identifier) {
@@ -15447,27 +14376,22 @@
/**
* Return the identifier being prefixed.
- *
- * @return the identifier being prefixed
*/
SimpleIdentifier get identifier => _identifier;
/**
- * Set the identifier being prefixed to the given identifier.
- *
- * @param identifier the identifier being prefixed
+ * Set the identifier being prefixed to the given [identifier].
*/
void set identifier(SimpleIdentifier identifier) {
_identifier = becomeParentOf(identifier);
}
/**
- * Return `true` if this type is a deferred type.
+ * Return `true` if this type is a deferred type. If the AST structure has not
+ * been resolved, then return `false`.
*
- * 15.1 Static Types: A type <i>T</i> is deferred iff it is of the form </i>p.T</i> where <i>p</i>
- * is a deferred prefix.
- *
- * @return `true` if this type is a deferred type
+ * 15.1 Static Types: A type <i>T</i> is deferred iff it is of the form
+ * </i>p.T</i> where <i>p</i> is a deferred prefix.
*/
bool get isDeferred {
Element element = _prefix.staticElement;
@@ -15490,17 +14414,14 @@
int get precedence => 15;
/**
- * Return the prefix associated with the library in which the identifier is defined.
- *
- * @return the prefix associated with the library in which the identifier is defined
+ * Return the prefix associated with the library in which the identifier is
+ * defined.
*/
SimpleIdentifier get prefix => _prefix;
/**
- * Set the prefix associated with the library in which the identifier is defined to the given
- * identifier.
- *
- * @param identifier the prefix associated with the library in which the identifier is defined
+ * Set the prefix associated with the library in which the identifier is
+ * defined to the given [identifier].
*/
void set prefix(SimpleIdentifier identifier) {
_prefix = becomeParentOf(identifier);
@@ -15527,18 +14448,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_prefix, visitor);
- safelyVisitChild(_identifier, visitor);
+ _safelyVisitChild(_prefix, visitor);
+ _safelyVisitChild(_identifier, visitor);
}
}
/**
- * Instances of the class `PrefixExpression` represent a prefix unary expression.
+ * A prefix unary expression.
*
- * <pre>
- * prefixExpression ::=
- * [Token] [Expression]
- * </pre>
+ * > prefixExpression ::=
+ * > [Token] [Expression]
*/
class PrefixExpression extends Expression {
/**
@@ -15552,24 +14471,21 @@
Expression _operand;
/**
- * The element associated with the operator based on the static type of the operand, or
- * `null` if the AST structure has not been resolved, if the operator is not user definable,
- * or if the operator could not be resolved.
+ * The element associated with the operator based on the static type of the
+ * operand, or `null` if the AST structure has not been resolved, if the
+ * operator is not user definable, or if the operator could not be resolved.
*/
MethodElement staticElement;
/**
- * The element associated with the operator based on the propagated type of the operand, or
- * `null` if the AST structure has not been resolved, if the operator is not user definable,
- * or if the operator could not be resolved.
+ * The element associated with the operator based on the propagated type of
+ * the operand, or `null` if the AST structure has not been resolved, if the
+ * operator is not user definable, or if the operator could not be resolved.
*/
MethodElement propagatedElement;
/**
* Initialize a newly created prefix expression.
- *
- * @param operator the prefix operator being applied to the operand
- * @param operand the expression computing the operand for the operator
*/
PrefixExpression(this.operator, Expression operand) {
_operand = becomeParentOf(operand);
@@ -15579,12 +14495,11 @@
Token get beginToken => operator;
/**
- * Return the best element available for this operator. If resolution was able to find a better
- * element based on type propagation, that element will be returned. Otherwise, the element found
- * using the result of static analysis will be returned. If resolution has not been performed,
- * then `null` will be returned.
- *
- * @return the best element available for this operator
+ * Return the best element available for this operator. If resolution was able
+ * to find a better element based on type propagation, that element will be
+ * returned. Otherwise, the element found using the result of static analysis
+ * will be returned. If resolution has not been performed, then `null` will be
+ * returned.
*/
MethodElement get bestElement {
MethodElement element = propagatedElement;
@@ -15604,15 +14519,12 @@
/**
* Return the expression computing the operand for the operator.
- *
- * @return the expression computing the operand for the operator
*/
Expression get operand => _operand;
/**
- * Set the expression computing the operand for the operator to the given expression.
- *
- * @param expression the expression computing the operand for the operator
+ * Set the expression computing the operand for the operator to the given
+ * [expression].
*/
void set operand(Expression expression) {
_operand = becomeParentOf(expression);
@@ -15622,14 +14534,13 @@
int get precedence => 14;
/**
- * If the AST structure has been resolved, and the function being invoked is known based on
- * propagated type information, then return the parameter element representing the parameter to
- * which the value of the operand will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on propagated type information, then return the parameter
+ * element representing the parameter to which the value of the operand will
+ * be bound. Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.propagatedParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the right
- * operand will be bound
+ * This method is only intended to be used by
+ * [Expression.propagatedParameterElement].
*/
ParameterElement get propagatedParameterElementForOperand {
if (propagatedElement == null) {
@@ -15643,14 +14554,13 @@
}
/**
- * If the AST structure has been resolved, and the function being invoked is known based on static
- * type information, then return the parameter element representing the parameter to which the
- * value of the operand will be bound. Otherwise, return `null`.
+ * If the AST structure has been resolved, and the function being invoked is
+ * known based on static type information, then return the parameter element
+ * representing the parameter to which the value of the operand will be bound.
+ * Otherwise, return `null`.
*
- * This method is only intended to be used by [Expression.staticParameterElement].
- *
- * @return the parameter element representing the parameter to which the value of the right
- * operand will be bound
+ * This method is only intended to be used by
+ * [Expression.staticParameterElement].
*/
ParameterElement get staticParameterElementForOperand {
if (staticElement == null) {
@@ -15668,21 +14578,19 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_operand, visitor);
+ _safelyVisitChild(_operand, visitor);
}
}
/**
- * Instances of the class `PropertyAccess` represent the access of a property of an object.
+ * The access of a property of an object.
*
- * Note, however, that accesses to properties of objects can also be represented as
- * [PrefixedIdentifier] nodes in cases where the target is also a simple
+ * Note, however, that accesses to properties of objects can also be represented
+ * as [PrefixedIdentifier] nodes in cases where the target is also a simple
* identifier.
*
- * <pre>
- * propertyAccess ::=
- * [Expression] '.' [SimpleIdentifier]
- * </pre>
+ * > propertyAccess ::=
+ * > [Expression] '.' [SimpleIdentifier]
*/
class PropertyAccess extends Expression {
/**
@@ -15702,10 +14610,6 @@
/**
* Initialize a newly created property access expression.
- *
- * @param target the expression computing the object defining the property being accessed
- * @param operator the property access operator
- * @param propertyName the name of the property being accessed
*/
PropertyAccess(Expression target, this.operator,
SimpleIdentifier propertyName) {
@@ -15734,11 +14638,9 @@
bool get isAssignable => true;
/**
- * Return `true` if this expression is cascaded. If it is, then the target of this
- * expression is not stored locally but is stored in the nearest ancestor that is a
- * [CascadeExpression].
- *
- * @return `true` if this expression is cascaded
+ * Return `true` if this expression is cascaded. If it is, then the target of
+ * this expression is not stored locally but is stored in the nearest ancestor
+ * that is a [CascadeExpression].
*/
bool get isCascaded =>
operator != null && operator.type == TokenType.PERIOD_PERIOD;
@@ -15748,28 +14650,21 @@
/**
* Return the name of the property being accessed.
- *
- * @return the name of the property being accessed
*/
SimpleIdentifier get propertyName => _propertyName;
/**
- * Set the name of the property being accessed to the given identifier.
- *
- * @param identifier the name of the property being accessed
+ * Set the name of the property being accessed to the given [identifier].
*/
void set propertyName(SimpleIdentifier identifier) {
_propertyName = becomeParentOf(identifier);
}
/**
- * Return the expression used to compute the receiver of the invocation. If this invocation is not
- * part of a cascade expression, then this is the same as [getTarget]. If this invocation
- * is part of a cascade expression, then the target stored with the cascade expression is
- * returned.
- *
- * @return the expression used to compute the receiver of the invocation
- * See [target].
+ * Return the expression used to compute the receiver of the invocation. If
+ * this invocation is not part of a cascade expression, then this is the same
+ * as [target]. If this invocation is part of a cascade expression, then the
+ * target stored with the cascade expression is returned.
*/
Expression get realTarget {
if (isCascaded) {
@@ -15786,19 +14681,17 @@
}
/**
- * Return the expression computing the object defining the property being accessed, or
- * `null` if this property access is part of a cascade expression.
+ * Return the expression computing the object defining the property being
+ * accessed, or `null` if this property access is part of a cascade expression.
*
- * @return the expression computing the object defining the property being accessed
- * See [realTarget].
+ * Use [realTarget] to get the target independent of whether this is part of a
+ * cascade expression.
*/
Expression get target => _target;
/**
- * Set the expression computing the object defining the property being accessed to the given
- * expression.
- *
- * @param expression the expression computing the object defining the property being accessed
+ * Set the expression computing the object defining the property being
+ * accessed to the given [expression].
*/
void set target(Expression expression) {
_target = becomeParentOf(expression);
@@ -15809,19 +14702,20 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_target, visitor);
- safelyVisitChild(_propertyName, visitor);
+ _safelyVisitChild(_target, visitor);
+ _safelyVisitChild(_propertyName, visitor);
}
}
/**
- * Instances of the class `RecursiveAstVisitor` implement an AST visitor that will recursively
- * visit all of the nodes in an AST structure. For example, using an instance of this class to visit
- * a [Block] will also cause all of the statements in the block to be visited.
+ * An AST visitor that will recursively visit all of the nodes in an AST
+ * structure. For example, using an instance of this class to visit a [Block]
+ * will also cause all of the statements in the block to be visited.
*
- * Subclasses that override a visit method must either invoke the overridden visit method or must
- * explicitly ask the visited node to visit its children. Failure to do so will cause the children
- * of the visited node to not be visited.
+ * Subclasses that override a visit method must either invoke the overridden
+ * visit method or must explicitly ask the visited node to visit its children.
+ * Failure to do so will cause the children of the visited node to not be
+ * visited.
*/
class RecursiveAstVisitor<R> implements AstVisitor<R> {
@override
@@ -16463,13 +15357,11 @@
}
/**
- * Instances of the class `RedirectingConstructorInvocation` represent the invocation of a
- * another constructor in the same class from within a constructor's initialization list.
+ * The invocation of a constructor in the same class from within a constructor's
+ * initialization list.
*
- * <pre>
- * redirectingConstructorInvocation ::=
- * 'this' ('.' identifier)? arguments
- * </pre>
+ * > redirectingConstructorInvocation ::=
+ * > 'this' ('.' identifier)? arguments
*/
class RedirectingConstructorInvocation extends ConstructorInitializer {
/**
@@ -16478,14 +15370,14 @@
Token keyword;
/**
- * The token for the period before the name of the constructor that is being invoked, or
- * `null` if the unnamed constructor is being invoked.
+ * The token for the period before the name of the constructor that is being
+ * invoked, or `null` if the unnamed constructor is being invoked.
*/
Token period;
/**
- * The name of the constructor that is being invoked, or `null` if the unnamed constructor
- * is being invoked.
+ * The name of the constructor that is being invoked, or `null` if the unnamed
+ * constructor is being invoked.
*/
SimpleIdentifier _constructorName;
@@ -16495,19 +15387,16 @@
ArgumentList _argumentList;
/**
- * The element associated with the constructor based on static type information, or `null`
- * if the AST structure has not been resolved or if the constructor could not be resolved.
+ * The element associated with the constructor based on static type
+ * information, or `null` if the AST structure has not been resolved or if the
+ * constructor could not be resolved.
*/
ConstructorElement staticElement;
/**
- * Initialize a newly created redirecting invocation to invoke the constructor with the given name
- * with the given arguments.
- *
- * @param keyword the token for the 'this' keyword
- * @param period the token for the period before the name of the constructor that is being invoked
- * @param constructorName the name of the constructor that is being invoked
- * @param argumentList the list of arguments to the constructor
+ * Initialize a newly created redirecting invocation to invoke the constructor
+ * with the given name with the given arguments. The [constructorName] can be
+ * `null` if the constructor being invoked is the unnamed constructor.
*/
RedirectingConstructorInvocation(this.keyword, this.period,
SimpleIdentifier constructorName, ArgumentList argumentList) {
@@ -16517,15 +15406,11 @@
/**
* Return the list of arguments to the constructor.
- *
- * @return the list of arguments to the constructor
*/
ArgumentList get argumentList => _argumentList;
/**
- * Set the list of arguments to the constructor to the given list.
- *
- * @param argumentList the list of arguments to the constructor
+ * Set the list of arguments to the constructor to the given [argumentList].
*/
void set argumentList(ArgumentList argumentList) {
_argumentList = becomeParentOf(argumentList);
@@ -16542,17 +15427,14 @@
..add(_argumentList);
/**
- * Return the name of the constructor that is being invoked, or `null` if the unnamed
- * constructor is being invoked.
- *
- * @return the name of the constructor that is being invoked
+ * Return the name of the constructor that is being invoked, or `null` if the
+ * unnamed constructor is being invoked.
*/
SimpleIdentifier get constructorName => _constructorName;
/**
- * Set the name of the constructor that is being invoked to the given identifier.
- *
- * @param identifier the name of the constructor that is being invoked
+ * Set the name of the constructor that is being invoked to the given
+ * [identifier].
*/
void set constructorName(SimpleIdentifier identifier) {
_constructorName = becomeParentOf(identifier);
@@ -16567,18 +15449,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_constructorName, visitor);
- safelyVisitChild(_argumentList, visitor);
+ _safelyVisitChild(_constructorName, visitor);
+ _safelyVisitChild(_argumentList, visitor);
}
}
/**
- * Instances of the class `RethrowExpression` represent a rethrow expression.
+ * A rethrow expression.
*
- * <pre>
- * rethrowExpression ::=
- * 'rethrow'
- * </pre>
+ * > rethrowExpression ::=
+ * > 'rethrow'
*/
class RethrowExpression extends Expression {
/**
@@ -16588,8 +15468,6 @@
/**
* Initialize a newly created rethrow expression.
- *
- * @param keyword the token representing the 'rethrow' keyword
*/
RethrowExpression(this.keyword);
@@ -16618,12 +15496,10 @@
}
/**
- * Instances of the class `ReturnStatement` represent a return statement.
+ * A return statement.
*
- * <pre>
- * returnStatement ::=
- * 'return' [Expression]? ';'
- * </pre>
+ * > returnStatement ::=
+ * > 'return' [Expression]? ';'
*/
class ReturnStatement extends Statement {
/**
@@ -16632,8 +15508,8 @@
Token keyword;
/**
- * The expression computing the value to be returned, or `null` if no explicit value was
- * provided.
+ * The expression computing the value to be returned, or `null` if no explicit
+ * value was provided.
*/
Expression _expression;
@@ -16643,11 +15519,8 @@
Token semicolon;
/**
- * Initialize a newly created return statement.
- *
- * @param keyword the token representing the 'return' keyword
- * @param expression the expression computing the value to be returned
- * @param semicolon the semicolon terminating the statement
+ * Initialize a newly created return statement. The [expression] can be `null`
+ * if no explicit value was provided.
*/
ReturnStatement(this.keyword, Expression expression, this.semicolon) {
_expression = becomeParentOf(expression);
@@ -16666,17 +15539,14 @@
Token get endToken => semicolon;
/**
- * Return the expression computing the value to be returned, or `null` if no explicit value
- * was provided.
- *
- * @return the expression computing the value to be returned
+ * Return the expression computing the value to be returned, or `null` if no
+ * explicit value was provided.
*/
Expression get expression => _expression;
/**
- * Set the expression computing the value to be returned to the given expression.
- *
- * @param expression the expression computing the value to be returned
+ * Set the expression computing the value to be returned to the given
+ * [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -16687,17 +15557,18 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * Traverse the AST from initial child node to successive parents, building a collection of local
- * variable and parameter names visible to the initial child node. In case of name shadowing, the
- * first name seen is the most specific one so names are not redefined.
+ * Traverse the AST from initial child node to successive parents, building a
+ * collection of local variable and parameter names visible to the initial child
+ * node. In case of name shadowing, the first name seen is the most specific one
+ * so names are not redefined.
*
- * Completion test code coverage is 95%. The two basic blocks that are not executed cannot be
- * executed. They are included for future reference.
+ * Completion test code coverage is 95%. The two basic blocks that are not
+ * executed cannot be executed. They are included for future reference.
*/
class ScopedNameFinder extends GeneralizingAstVisitor<Object> {
Declaration _declarationNode;
@@ -16841,27 +15712,26 @@
}
}
- void _addVariables(NodeList<VariableDeclaration> vars) {
- for (VariableDeclaration var2 in vars) {
- _addToScope(var2.name);
+ void _addVariables(NodeList<VariableDeclaration> variables) {
+ for (VariableDeclaration variable in variables) {
+ _addToScope(variable.name);
}
}
/**
- * Some statements define names that are visible downstream. There aren't many of these.
- *
- * @param statements the list of statements to check for name definitions
+ * Check the given list of [statements] for any that come before the immediate
+ * child and that define a name that would be visible to the immediate child.
*/
void _checkStatements(List<Statement> statements) {
- for (Statement stmt in statements) {
- if (identical(stmt, _immediateChild)) {
+ for (Statement statement in statements) {
+ if (identical(statement, _immediateChild)) {
return;
}
- if (stmt is VariableDeclarationStatement) {
- _addVariables(stmt.variables.variables);
- } else if (stmt is FunctionDeclarationStatement &&
+ if (statement is VariableDeclarationStatement) {
+ _addVariables(statement.variables.variables);
+ } else if (statement is FunctionDeclarationStatement &&
!_referenceIsWithinLocalFunction) {
- _addToScope(stmt.functionDeclaration.name);
+ _addToScope(statement.functionDeclaration.name);
}
}
}
@@ -16877,13 +15747,10 @@
}
/**
- * Instances of the class `ScriptTag` represent the script tag that can optionally occur at
- * the beginning of a compilation unit.
+ * A script tag that can optionally occur at the beginning of a compilation unit.
*
- * <pre>
- * scriptTag ::=
- * '#!' (~NEWLINE)* NEWLINE
- * </pre>
+ * > scriptTag ::=
+ * > '#!' (~NEWLINE)* NEWLINE
*/
class ScriptTag extends AstNode {
/**
@@ -16893,8 +15760,6 @@
/**
* Initialize a newly created script tag.
- *
- * @param scriptTag the token representing this script tag
*/
ScriptTag(this.scriptTag);
@@ -16920,13 +15785,10 @@
}
/**
- * Instances of the class `ShowCombinator` represent a combinator that restricts the names
- * being imported to those in a given list.
+ * A combinator that restricts the names being imported to those in a given list.
*
- * <pre>
- * showCombinator ::=
- * 'show' [SimpleIdentifier] (',' [SimpleIdentifier])*
- * </pre>
+ * > showCombinator ::=
+ * > 'show' [SimpleIdentifier] (',' [SimpleIdentifier])*
*/
class ShowCombinator extends Combinator {
/**
@@ -16936,9 +15798,6 @@
/**
* Initialize a newly created import show combinator.
- *
- * @param keyword the comma introducing the combinator
- * @param shownNames the list of names from the library that are made visible by this combinator
*/
ShowCombinator(Token keyword, List<SimpleIdentifier> shownNames)
: super(keyword) {
@@ -16957,9 +15816,8 @@
Token get endToken => _shownNames.endToken;
/**
- * Return the list of names from the library that are made visible by this combinator.
- *
- * @return the list of names from the library that are made visible by this combinator
+ * Return the list of names from the library that are made visible by this
+ * combinator.
*/
NodeList<SimpleIdentifier> get shownNames => _shownNames;
@@ -16973,9 +15831,9 @@
}
/**
- * Instances of the class `SimpleAstVisitor` implement an AST visitor that will do nothing
- * when visiting an AST node. It is intended to be a superclass for classes that use the visitor
- * pattern primarily as a dispatch mechanism (and hence don't need to recursively visit a whole
+ * An AST visitor that will do nothing when visiting an AST node. It is intended
+ * to be a superclass for classes that use the visitor pattern primarily as a
+ * dispatch mechanism (and hence don't need to recursively visit a whole
* structure) and that only need to visit a small number of node types.
*/
class SimpleAstVisitor<R> implements AstVisitor<R> {
@@ -17305,34 +16163,29 @@
}
/**
- * Instances of the class `SimpleFormalParameter` represent a simple formal parameter.
+ * A simple formal parameter.
*
- * <pre>
- * simpleFormalParameter ::=
- * ('final' [TypeName] | 'var' | [TypeName])? [SimpleIdentifier]
- * </pre>
+ * > simpleFormalParameter ::=
+ * > ('final' [TypeName] | 'var' | [TypeName])? [SimpleIdentifier]
*/
class SimpleFormalParameter extends NormalFormalParameter {
/**
- * The token representing either the 'final', 'const' or 'var' keyword, or `null` if no
- * keyword was used.
+ * The token representing either the 'final', 'const' or 'var' keyword, or
+ * `null` if no keyword was used.
*/
Token keyword;
/**
- * The name of the declared type of the parameter, or `null` if the parameter does not have
- * a declared type.
+ * The name of the declared type of the parameter, or `null` if the parameter
+ * does not have a declared type.
*/
TypeName _type;
/**
- * Initialize a newly created formal parameter.
- *
- * @param comment the documentation comment associated with this parameter
- * @param metadata the annotations associated with this parameter
- * @param keyword the token representing either the 'final', 'const' or 'var' keyword
- * @param type the name of the declared type of the parameter
- * @param identifier the name of the parameter being declared
+ * Initialize a newly created formal parameter. Either or both of the
+ * [comment] and [metadata] can be `null` if the parameter does not have the
+ * corresponding attribute. The [keyword] can be `null` if a type was
+ * specified. The [type] must be `null` if the keyword is 'var'.
*/
SimpleFormalParameter(Comment comment, List<Annotation> metadata,
this.keyword, TypeName type, SimpleIdentifier identifier)
@@ -17374,17 +16227,13 @@
(keyword is KeywordToken) && (keyword as KeywordToken).keyword == Keyword.FINAL;
/**
- * Return the name of the declared type of the parameter, or `null` if the parameter does
- * not have a declared type.
- *
- * @return the name of the declared type of the parameter
+ * Return the name of the declared type of the parameter, or `null` if the
+ * parameter does not have a declared type.
*/
TypeName get type => _type;
/**
- * Set the name of the declared type of the parameter to the given type name.
- *
- * @param typeName the name of the declared type of the parameter
+ * Set the name of the declared type of the parameter to the given [typeName].
*/
void set type(TypeName typeName) {
_type = becomeParentOf(typeName);
@@ -17396,22 +16245,20 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_type, visitor);
- safelyVisitChild(identifier, visitor);
+ _safelyVisitChild(_type, visitor);
+ _safelyVisitChild(identifier, visitor);
}
}
/**
- * Instances of the class `SimpleIdentifier` represent a simple identifier.
+ * A simple identifier.
*
- * <pre>
- * simpleIdentifier ::=
- * initialCharacter internalCharacter*
- *
- * initialCharacter ::= '_' | '$' | letter
- *
- * internalCharacter ::= '_' | '$' | letter | digit
- * </pre>
+ * > simpleIdentifier ::=
+ * > initialCharacter internalCharacter*
+ * >
+ * > initialCharacter ::= '_' | '$' | letter
+ * >
+ * > internalCharacter ::= '_' | '$' | letter | digit
*/
class SimpleIdentifier extends Identifier {
/**
@@ -17420,29 +16267,29 @@
Token token;
/**
- * The element associated with this identifier based on static type information, or `null`
- * if the AST structure has not been resolved or if this identifier could not be resolved.
+ * The element associated with this identifier based on static type
+ * information, or `null` if the AST structure has not been resolved or if
+ * this identifier could not be resolved.
*/
Element _staticElement;
/**
- * The element associated with this identifier based on propagated type information, or
- * `null` if the AST structure has not been resolved or if this identifier could not be
- * resolved.
+ * The element associated with this identifier based on propagated type
+ * information, or `null` if the AST structure has not been resolved or if
+ * this identifier could not be resolved.
*/
Element _propagatedElement;
/**
- * If this expression is both in a getter and setter context, the [AuxiliaryElements] will
- * be set to hold onto the static and propagated information. The auxiliary element will hold onto
- * the elements from the getter context.
+ * If this expression is both in a getter and setter context, the
+ * [AuxiliaryElements] will be set to hold onto the static and propagated
+ * information. The auxiliary element will hold onto the elements from the
+ * getter context.
*/
AuxiliaryElements auxiliaryElements = null;
/**
* Initialize a newly created identifier.
- *
- * @param token the token representing the identifier
*/
SimpleIdentifier(this.token);
@@ -17467,11 +16314,8 @@
Token get endToken => token;
/**
- * Returns `true` if this identifier is the "name" part of a prefixed identifier or a method
- * invocation.
- *
- * @return `true` if this identifier is the "name" part of a prefixed identifier or a method
- * invocation
+ * Returns `true` if this identifier is the "name" part of a prefixed
+ * identifier or a method invocation.
*/
bool get isQualified {
AstNode parent = this.parent;
@@ -17502,10 +16346,8 @@
Element get propagatedElement => _propagatedElement;
/**
- * Set the element associated with this identifier based on propagated type information to the
- * given element.
- *
- * @param element the element to be associated with this identifier
+ * Set the element associated with this identifier based on propagated type
+ * information to the given [element].
*/
void set propagatedElement(Element element) {
_propagatedElement = _validateElement(element);
@@ -17515,10 +16357,8 @@
Element get staticElement => _staticElement;
/**
- * Set the element associated with this identifier based on static type information to the given
- * element.
- *
- * @param element the element to be associated with this identifier
+ * Set the element associated with this identifier based on static type
+ * information to the given [element].
*/
void set staticElement(Element element) {
_staticElement = _validateElement(element);
@@ -17528,9 +16368,8 @@
accept(AstVisitor visitor) => visitor.visitSimpleIdentifier(this);
/**
- * Return `true` if this identifier is the name being declared in a declaration.
- *
- * @return `true` if this identifier is the name being declared in a declaration
+ * Return `true` if this identifier is the name being declared in a
+ * declaration.
*/
bool inDeclarationContext() {
AstNode parent = this.parent;
@@ -17575,11 +16414,9 @@
/**
* Return `true` if this expression is computing a right-hand value.
*
- * Note that [inGetterContext] and [inSetterContext] are not opposites, nor are
- * they mutually exclusive. In other words, it is possible for both methods to return `true`
- * when invoked on the same node.
- *
- * @return `true` if this expression is in a context where a getter will be invoked
+ * Note that [inGetterContext] and [inSetterContext] are not opposites, nor
+ * are they mutually exclusive. In other words, it is possible for both
+ * methods to return `true` when invoked on the same node.
*/
bool inGetterContext() {
AstNode parent = this.parent;
@@ -17624,11 +16461,9 @@
/**
* Return `true` if this expression is computing a left-hand value.
*
- * Note that [inGetterContext] and [inSetterContext] are not opposites, nor are
- * they mutually exclusive. In other words, it is possible for both methods to return `true`
- * when invoked on the same node.
- *
- * @return `true` if this expression is in a context where a setter will be invoked
+ * Note that [inGetterContext] and [inSetterContext] are not opposites, nor
+ * are they mutually exclusive. In other words, it is possible for both
+ * methods to return `true` when invoked on the same node.
*/
bool inSetterContext() {
AstNode parent = this.parent;
@@ -17669,13 +16504,13 @@
}
/**
- * Return the given element if it is valid, or report the problem and return `null` if it is
- * not appropriate.
+ * Return the given element if it is valid, or report the problem and return
+ * `null` if it is not appropriate.
*
- * @param parent the parent of the element, used for reporting when there is a problem
- * @param isValid `true` if the element is appropriate
- * @param element the element to be associated with this identifier
- * @return the element to be associated with this identifier
+ * The [parent] is the parent of the element, used for reporting when there is
+ * a problem.
+ * The [isValid] is `true` if the element is appropriate.
+ * The [element] is the element to be associated with this identifier.
*/
Element _returnOrReportElement(AstNode parent, bool isValid,
Element element) {
@@ -17689,11 +16524,8 @@
}
/**
- * Return the given element if it is an appropriate element based on the parent of this
- * identifier, or `null` if it is not appropriate.
- *
- * @param element the element to be associated with this identifier
- * @return the element to be associated with this identifier
+ * Return the given [element] if it is an appropriate element based on the
+ * parent of this identifier, or `null` if it is not appropriate.
*/
Element _validateElement(Element element) {
if (element == null) {
@@ -17747,29 +16579,26 @@
}
/**
- * Instances of the class `SimpleStringLiteral` represent a string literal expression that
- * does not contain any interpolations.
+ * A string literal expression that does not contain any interpolations.
*
- * <pre>
- * simpleStringLiteral ::=
- * rawStringLiteral
- * | basicStringLiteral
- *
- * rawStringLiteral ::=
- * 'r' basicStringLiteral
- *
- * simpleStringLiteral ::=
- * multiLineStringLiteral
- * | singleLineStringLiteral
- *
- * multiLineStringLiteral ::=
- * "'''" characters "'''"
- * | '"""' characters '"""'
- *
- * singleLineStringLiteral ::=
- * "'" characters "'"
- * '"' characters '"'
- * </pre>
+ * > simpleStringLiteral ::=
+ * > rawStringLiteral
+ * > | basicStringLiteral
+ * >
+ * > rawStringLiteral ::=
+ * > 'r' basicStringLiteral
+ * >
+ * > simpleStringLiteral ::=
+ * > multiLineStringLiteral
+ * > | singleLineStringLiteral
+ * >
+ * > multiLineStringLiteral ::=
+ * > "'''" characters "'''"
+ * > | '"""' characters '"""'
+ * >
+ * > singleLineStringLiteral ::=
+ * > "'" characters "'"
+ * > | '"' characters '"'
*/
class SimpleStringLiteral extends SingleStringLiteral {
/**
@@ -17789,9 +16618,6 @@
/**
* Initialize a newly created simple string literal.
- *
- * @param literal the token representing the literal
- * @param value the value of the literal
*/
SimpleStringLiteral(this.literal, String value) {
_value = StringUtilities.intern(value);
@@ -17862,15 +16688,11 @@
/**
* Return the value of the literal.
- *
- * @return the value of the literal
*/
String get value => _value;
/**
- * Set the value of the literal to the given string.
- *
- * @param string the value of the literal
+ * Set the value of the literal to the given [string].
*/
void set value(String string) {
_value = StringUtilities.intern(_value);
@@ -17891,14 +16713,11 @@
}
/**
- * Instances of the class [SingleStringLiteral] represent a single string
- * literal expression.
+ * A single string literal expression.
*
- * <pre>
- * singleStringLiteral ::=
- * [SimpleStringLiteral]
- * | [StringInterpolation]
- * </pre>
+ * > singleStringLiteral ::=
+ * > [SimpleStringLiteral]
+ * > | [StringInterpolation]
*/
abstract class SingleStringLiteral extends StringLiteral {
/**
@@ -17929,26 +16748,23 @@
}
/**
- * Instances of the class `Statement` defines the behavior common to nodes that represent a
- * statement.
+ * A node that represents a statement.
*
- * <pre>
- * statement ::=
- * [Block]
- * | [VariableDeclarationStatement]
- * | [ForStatement]
- * | [ForEachStatement]
- * | [WhileStatement]
- * | [DoStatement]
- * | [SwitchStatement]
- * | [IfStatement]
- * | [TryStatement]
- * | [BreakStatement]
- * | [ContinueStatement]
- * | [ReturnStatement]
- * | [ExpressionStatement]
- * | [FunctionDeclarationStatement]
- * </pre>
+ * > statement ::=
+ * > [Block]
+ * > | [VariableDeclarationStatement]
+ * > | [ForStatement]
+ * > | [ForEachStatement]
+ * > | [WhileStatement]
+ * > | [DoStatement]
+ * > | [SwitchStatement]
+ * > | [IfStatement]
+ * > | [TryStatement]
+ * > | [BreakStatement]
+ * > | [ContinueStatement]
+ * > | [ReturnStatement]
+ * > | [ExpressionStatement]
+ * > | [FunctionDeclarationStatement]
*/
abstract class Statement extends AstNode {
/**
@@ -17959,13 +16775,11 @@
}
/**
- * Instances of the class `StringInterpolation` represent a string interpolation literal.
+ * A string interpolation literal.
*
- * <pre>
- * stringInterpolation ::=
- * ''' [InterpolationElement]* '''
- * | '"' [InterpolationElement]* '"'
- * </pre>
+ * > stringInterpolation ::=
+ * > ''' [InterpolationElement]* '''
+ * > | '"' [InterpolationElement]* '"'
*/
class StringInterpolation extends SingleStringLiteral {
/**
@@ -17975,8 +16789,6 @@
/**
* Initialize a newly created string interpolation expression.
- *
- * @param elements the elements that will be composed to produce the resulting string
*/
StringInterpolation(List<InterpolationElement> elements) {
_elements = new NodeList<InterpolationElement>(this, elements);
@@ -18002,8 +16814,6 @@
/**
* Return the elements that will be composed to produce the resulting string.
- *
- * @return the elements that will be composed to produce the resulting string
*/
NodeList<InterpolationElement> get elements => _elements;
@@ -18046,14 +16856,12 @@
}
/**
- * Instances of the class `StringLiteral` represent a string literal expression.
+ * A string literal expression.
*
- * <pre>
- * stringLiteral ::=
- * [SimpleStringLiteral]
- * | [AdjacentStrings]
- * | [StringInterpolation]
- * </pre>
+ * > stringLiteral ::=
+ * > [SimpleStringLiteral]
+ * > | [AdjacentStrings]
+ * > | [StringInterpolation]
*/
abstract class StringLiteral extends Literal {
/**
@@ -18079,13 +16887,11 @@
}
/**
- * Instances of the class `SuperConstructorInvocation` represent the invocation of a
- * superclass' constructor from within a constructor's initialization list.
+ * The invocation of a superclass' constructor from within a constructor's
+ * initialization list.
*
- * <pre>
- * superInvocation ::=
- * 'super' ('.' [SimpleIdentifier])? [ArgumentList]
- * </pre>
+ * > superInvocation ::=
+ * > 'super' ('.' [SimpleIdentifier])? [ArgumentList]
*/
class SuperConstructorInvocation extends ConstructorInitializer {
/**
@@ -18094,14 +16900,14 @@
Token keyword;
/**
- * The token for the period before the name of the constructor that is being invoked, or
- * `null` if the unnamed constructor is being invoked.
+ * The token for the period before the name of the constructor that is being
+ * invoked, or `null` if the unnamed constructor is being invoked.
*/
Token period;
/**
- * The name of the constructor that is being invoked, or `null` if the unnamed constructor
- * is being invoked.
+ * The name of the constructor that is being invoked, or `null` if the unnamed
+ * constructor is being invoked.
*/
SimpleIdentifier _constructorName;
@@ -18111,19 +16917,17 @@
ArgumentList _argumentList;
/**
- * The element associated with the constructor based on static type information, or `null`
- * if the AST structure has not been resolved or if the constructor could not be resolved.
+ * The element associated with the constructor based on static type
+ * information, or `null` if the AST structure has not been resolved or if the
+ * constructor could not be resolved.
*/
ConstructorElement staticElement;
/**
- * Initialize a newly created super invocation to invoke the inherited constructor with the given
- * name with the given arguments.
- *
- * @param keyword the token for the 'super' keyword
- * @param period the token for the period before the name of the constructor that is being invoked
- * @param constructorName the name of the constructor that is being invoked
- * @param argumentList the list of arguments to the constructor
+ * Initialize a newly created super invocation to invoke the inherited
+ * constructor with the given name with the given arguments. The [period] and
+ * [constructorName] can be `null` if the constructor being invoked is the
+ * unnamed constructor.
*/
SuperConstructorInvocation(this.keyword, this.period,
SimpleIdentifier constructorName, ArgumentList argumentList) {
@@ -18133,15 +16937,11 @@
/**
* Return the list of arguments to the constructor.
- *
- * @return the list of arguments to the constructor
*/
ArgumentList get argumentList => _argumentList;
/**
- * Set the list of arguments to the constructor to the given list.
- *
- * @param argumentList the list of arguments to the constructor
+ * Set the list of arguments to the constructor to the given [argumentList].
*/
void set argumentList(ArgumentList argumentList) {
_argumentList = becomeParentOf(argumentList);
@@ -18158,17 +16958,14 @@
..add(_argumentList);
/**
- * Return the name of the constructor that is being invoked, or `null` if the unnamed
- * constructor is being invoked.
- *
- * @return the name of the constructor that is being invoked
+ * Return the name of the constructor that is being invoked, or `null` if the
+ * unnamed constructor is being invoked.
*/
SimpleIdentifier get constructorName => _constructorName;
/**
- * Set the name of the constructor that is being invoked to the given identifier.
- *
- * @param identifier the name of the constructor that is being invoked
+ * Set the name of the constructor that is being invoked to the given
+ * [identifier].
*/
void set constructorName(SimpleIdentifier identifier) {
_constructorName = becomeParentOf(identifier);
@@ -18182,18 +16979,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_constructorName, visitor);
- safelyVisitChild(_argumentList, visitor);
+ _safelyVisitChild(_constructorName, visitor);
+ _safelyVisitChild(_argumentList, visitor);
}
}
/**
- * Instances of the class `SuperExpression` represent a super expression.
+ * A super expression.
*
- * <pre>
- * superExpression ::=
- * 'super'
- * </pre>
+ * > superExpression ::=
+ * > 'super'
*/
class SuperExpression extends Expression {
/**
@@ -18203,8 +16998,6 @@
/**
* Initialize a newly created super expression.
- *
- * @param keyword the token representing the keyword
*/
SuperExpression(this.keyword);
@@ -18233,12 +17026,10 @@
}
/**
- * Instances of the class `SwitchCase` represent the case in a switch statement.
+ * A case in a switch statement.
*
- * <pre>
- * switchCase ::=
- * [SimpleIdentifier]* 'case' [Expression] ':' [Statement]*
- * </pre>
+ * > switchCase ::=
+ * > [SimpleIdentifier]* 'case' [Expression] ':' [Statement]*
*/
class SwitchCase extends SwitchMember {
/**
@@ -18247,13 +17038,8 @@
Expression _expression;
/**
- * Initialize a newly created switch case.
- *
- * @param labels the labels associated with the switch member
- * @param keyword the token representing the 'case' or 'default' keyword
- * @param expression the expression controlling whether the statements will be executed
- * @param colon the colon separating the keyword or the expression from the statements
- * @param statements the statements that will be executed if this switch member is selected
+ * Initialize a newly created switch case. The list of [labels] can be `null`
+ * if there are no labels.
*/
SwitchCase(List<Label> labels, Token keyword, Expression expression,
Token colon, List<Statement> statements)
@@ -18271,15 +17057,12 @@
/**
* Return the expression controlling whether the statements will be executed.
- *
- * @return the expression controlling whether the statements will be executed
*/
Expression get expression => _expression;
/**
- * Set the expression controlling whether the statements will be executed to the given expression.
- *
- * @param expression the expression controlling whether the statements will be executed
+ * Set the expression controlling whether the statements will be executed to
+ * the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -18291,27 +17074,21 @@
@override
void visitChildren(AstVisitor visitor) {
labels.accept(visitor);
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
statements.accept(visitor);
}
}
/**
- * Instances of the class `SwitchDefault` represent the default case in a switch statement.
+ * The default case in a switch statement.
*
- * <pre>
- * switchDefault ::=
- * [SimpleIdentifier]* 'default' ':' [Statement]*
- * </pre>
+ * > switchDefault ::=
+ * > [SimpleIdentifier]* 'default' ':' [Statement]*
*/
class SwitchDefault extends SwitchMember {
/**
- * Initialize a newly created switch default.
- *
- * @param labels the labels associated with the switch member
- * @param keyword the token representing the 'case' or 'default' keyword
- * @param colon the colon separating the keyword or the expression from the statements
- * @param statements the statements that will be executed if this switch member is selected
+ * Initialize a newly created switch default. The list of [labels] can be
+ * `null` if there are no labels.
*/
SwitchDefault(List<Label> labels, Token keyword, Token colon,
List<Statement> statements)
@@ -18338,14 +17115,11 @@
}
/**
- * The abstract class `SwitchMember` defines the behavior common to objects representing
- * elements within a switch statement.
+ * An element within a switch statement.
*
- * <pre>
- * switchMember ::=
- * switchCase
- * | switchDefault
- * </pre>
+ * > switchMember ::=
+ * > switchCase
+ * > | switchDefault
*/
abstract class SwitchMember extends AstNode {
/**
@@ -18369,12 +17143,8 @@
NodeList<Statement> _statements;
/**
- * Initialize a newly created switch member.
- *
- * @param labels the labels associated with the switch member
- * @param keyword the token representing the 'case' or 'default' keyword
- * @param colon the colon separating the keyword or the expression from the statements
- * @param statements the statements that will be executed if this switch member is selected
+ * Initialize a newly created switch member. The list of [labels] can be
+ * `null` if there are no labels.
*/
SwitchMember(List<Label> labels, this.keyword, this.colon,
List<Statement> statements) {
@@ -18400,26 +17170,21 @@
/**
* Return the labels associated with the switch member.
- *
- * @return the labels associated with the switch member
*/
NodeList<Label> get labels => _labels;
/**
- * Return the statements that will be executed if this switch member is selected.
- *
- * @return the statements that will be executed if this switch member is selected
+ * Return the statements that will be executed if this switch member is
+ * selected.
*/
NodeList<Statement> get statements => _statements;
}
/**
- * Instances of the class `SwitchStatement` represent a switch statement.
+ * A switch statement.
*
- * <pre>
- * switchStatement ::=
- * 'switch' '(' [Expression] ')' '{' [SwitchCase]* [SwitchDefault]? '}'
- * </pre>
+ * > switchStatement ::=
+ * > 'switch' '(' [Expression] ')' '{' [SwitchCase]* [SwitchDefault]? '}'
*/
class SwitchStatement extends Statement {
/**
@@ -18433,7 +17198,8 @@
Token leftParenthesis;
/**
- * The expression used to determine which of the switch members will be selected.
+ * The expression used to determine which of the switch members will be
+ * selected.
*/
Expression _expression;
@@ -18458,15 +17224,8 @@
Token rightBracket;
/**
- * Initialize a newly created switch statement.
- *
- * @param keyword the token representing the 'switch' keyword
- * @param leftParenthesis the left parenthesis
- * @param expression the expression used to determine which of the switch members will be selected
- * @param rightParenthesis the right parenthesis
- * @param leftBracket the left curly bracket
- * @param members the switch members that can be selected by the expression
- * @param rightBracket the right curly bracket
+ * Initialize a newly created switch statement. The list of [members] can be
+ * `null` if there are no switch members.
*/
SwitchStatement(this.keyword, this.leftParenthesis, Expression expression,
this.rightParenthesis, this.leftBracket, List<SwitchMember> members,
@@ -18492,17 +17251,14 @@
Token get endToken => rightBracket;
/**
- * Return the expression used to determine which of the switch members will be selected.
- *
- * @return the expression used to determine which of the switch members will be selected
+ * Return the expression used to determine which of the switch members will be
+ * selected.
*/
Expression get expression => _expression;
/**
- * Set the expression used to determine which of the switch members will be selected to the given
- * expression.
- *
- * @param expression the expression used to determine which of the switch members will be selected
+ * Set the expression used to determine which of the switch members will be
+ * selected to the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -18510,8 +17266,6 @@
/**
* Return the switch members that can be selected by the expression.
- *
- * @return the switch members that can be selected by the expression
*/
NodeList<SwitchMember> get members => _members;
@@ -18520,18 +17274,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
_members.accept(visitor);
}
}
/**
- * Instances of the class `SymbolLiteral` represent a symbol literal expression.
+ * A symbol literal expression.
*
- * <pre>
- * symbolLiteral ::=
- * '#' (operator | (identifier ('.' identifier)*))
- * </pre>
+ * > symbolLiteral ::=
+ * > '#' (operator | (identifier ('.' identifier)*))
*/
class SymbolLiteral extends Literal {
/**
@@ -18546,9 +17298,6 @@
/**
* Initialize a newly created symbol literal.
- *
- * @param poundSign the token introducing the literal
- * @param components the components of the literal
*/
SymbolLiteral(this.poundSign, this.components);
@@ -18577,12 +17326,10 @@
}
/**
- * Instances of the class `ThisExpression` represent a this expression.
+ * A this expression.
*
- * <pre>
- * thisExpression ::=
- * 'this'
- * </pre>
+ * > thisExpression ::=
+ * > 'this'
*/
class ThisExpression extends Expression {
/**
@@ -18592,8 +17339,6 @@
/**
* Initialize a newly created this expression.
- *
- * @param keyword the token representing the keyword
*/
ThisExpression(this.keyword);
@@ -18622,12 +17367,10 @@
}
/**
- * Instances of the class `ThrowExpression` represent a throw expression.
+ * A throw expression.
*
- * <pre>
- * throwExpression ::=
- * 'throw' [Expression]
- * </pre>
+ * > throwExpression ::=
+ * > 'throw' [Expression]
*/
class ThrowExpression extends Expression {
/**
@@ -18642,9 +17385,6 @@
/**
* Initialize a newly created throw expression.
- *
- * @param keyword the token representing the 'throw' keyword
- * @param expression the expression computing the exception to be thrown
*/
ThrowExpression(this.keyword, Expression expression) {
_expression = becomeParentOf(expression);
@@ -18668,15 +17408,12 @@
/**
* Return the expression computing the exception to be thrown.
- *
- * @return the expression computing the exception to be thrown
*/
Expression get expression => _expression;
/**
- * Set the expression computing the exception to be thrown to the given expression.
- *
- * @param expression the expression computing the exception to be thrown
+ * Set the expression computing the exception to be thrown to the given
+ * [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -18690,19 +17427,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
/**
- * Instances of the class `TopLevelVariableDeclaration` represent the declaration of one or
- * more top-level variables of the same type.
+ * The declaration of one or more top-level variables of the same type.
*
- * <pre>
- * topLevelVariableDeclaration ::=
- * ('final' | 'const') type? staticFinalDeclarationList ';'
- * | variableDeclaration ';'
- * </pre>
+ * > topLevelVariableDeclaration ::=
+ * > ('final' | 'const') type? staticFinalDeclarationList ';'
+ * > | variableDeclaration ';'
*/
class TopLevelVariableDeclaration extends CompilationUnitMember {
/**
@@ -18716,12 +17450,9 @@
Token semicolon;
/**
- * Initialize a newly created top-level variable declaration.
- *
- * @param comment the documentation comment associated with this variable
- * @param metadata the annotations associated with this variable
- * @param variableList the top-level variables being declared
- * @param semicolon the semicolon terminating the declaration
+ * Initialize a newly created top-level variable declaration. Either or both
+ * of the [comment] and [metadata] can be `null` if the variable does not have
+ * the corresponding attribute.
*/
TopLevelVariableDeclaration(Comment comment, List<Annotation> metadata,
VariableDeclarationList variableList, this.semicolon)
@@ -18745,18 +17476,15 @@
/**
* Return the top-level variables being declared.
- *
- * @return the top-level variables being declared
*/
VariableDeclarationList get variables => _variableList;
/**
- * Set the top-level variables being declared to the given list of variables.
- *
- * @param variableList the top-level variables being declared
+ * Set the top-level variables being declared to the given list of
+ * [variables].
*/
- void set variables(VariableDeclarationList variableList) {
- _variableList = becomeParentOf(variableList);
+ void set variables(VariableDeclarationList variables) {
+ _variableList = becomeParentOf(variables);
}
@override
@@ -18765,13 +17493,13 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_variableList, visitor);
+ _safelyVisitChild(_variableList, visitor);
}
}
/**
- * Instances of the class `ToSourceVisitor` write a source representation of a visited AST
- * node (and all of it's children) to a writer.
+ * A visitor used to write a source representation of a visited AST node (and
+ * all of it's children) to a writer.
*/
class ToSourceVisitor implements AstVisitor<Object> {
/**
@@ -18780,10 +17508,8 @@
final PrintWriter _writer;
/**
- * Initialize a newly created visitor to write source code representing the visited nodes to the
- * given writer.
- *
- * @param writer the writer to which the source is to be written
+ * Initialize a newly created visitor to write source code representing the
+ * visited nodes to the given [writer].
*/
ToSourceVisitor(this._writer);
@@ -19765,10 +18491,8 @@
}
/**
- * Visit the given function body, printing the prefix before if given body is not empty.
- *
- * @param prefix the prefix to be printed if there is a node to visit
- * @param body the function body to be visited
+ * Visit the given function [body], printing the [prefix] before if the body
+ * is not empty.
*/
void _visitFunctionWithPrefix(String prefix, FunctionBody body) {
if (body is! EmptyFunctionBody) {
@@ -19778,9 +18502,7 @@
}
/**
- * Safely visit the given node.
- *
- * @param node the node to be visited
+ * Safely visit the given [node].
*/
void _visitNode(AstNode node) {
if (node != null) {
@@ -19789,20 +18511,14 @@
}
/**
- * Print a list of nodes without any separation.
- *
- * @param nodes the nodes to be printed
- * @param separator the separator to be printed between adjacent nodes
+ * Print a list of [nodes] without any separation.
*/
void _visitNodeList(NodeList<AstNode> nodes) {
_visitNodeListWithSeparator(nodes, "");
}
/**
- * Print a list of nodes, separated by the given separator.
- *
- * @param nodes the nodes to be printed
- * @param separator the separator to be printed between adjacent nodes
+ * Print a list of [nodes], separated by the given [separator].
*/
void _visitNodeListWithSeparator(NodeList<AstNode> nodes, String separator) {
if (nodes != null) {
@@ -19817,11 +18533,8 @@
}
/**
- * Print a list of nodes, separated by the given separator.
- *
- * @param prefix the prefix to be printed if the list is not empty
- * @param nodes the nodes to be printed
- * @param separator the separator to be printed between adjacent nodes
+ * Print a list of [nodes], prefixed by the given [prefix] if the list is not
+ * empty, and separated by the given [separator].
*/
void _visitNodeListWithSeparatorAndPrefix(String prefix,
NodeList<AstNode> nodes, String separator) {
@@ -19840,11 +18553,8 @@
}
/**
- * Print a list of nodes, separated by the given separator.
- *
- * @param nodes the nodes to be printed
- * @param separator the separator to be printed between adjacent nodes
- * @param suffix the suffix to be printed if the list is not empty
+ * Print a list of [nodes], separated by the given [separator], followed by
+ * the given [suffix] if the list is not empty.
*/
void _visitNodeListWithSeparatorAndSuffix(NodeList<AstNode> nodes,
String separator, String suffix) {
@@ -19863,10 +18573,8 @@
}
/**
- * Safely visit the given node, printing the prefix before the node if it is non-`null`.
- *
- * @param prefix the prefix to be printed if there is a node to visit
- * @param node the node to be visited
+ * Safely visit the given [node], printing the [prefix] before the node if it
+ * is non-`null`.
*/
void _visitNodeWithPrefix(String prefix, AstNode node) {
if (node != null) {
@@ -19876,10 +18584,8 @@
}
/**
- * Safely visit the given node, printing the suffix after the node if it is non-`null`.
- *
- * @param suffix the suffix to be printed if there is a node to visit
- * @param node the node to be visited
+ * Safely visit the given [node], printing the [suffix] after the node if it
+ * is non-`null`.
*/
void _visitNodeWithSuffix(AstNode node, String suffix) {
if (node != null) {
@@ -19889,10 +18595,8 @@
}
/**
- * Safely visit the given node, printing the suffix after the node if it is non-`null`.
- *
- * @param suffix the suffix to be printed if there is a node to visit
- * @param node the node to be visited
+ * Safely visit the given [token], printing the [suffix] after the token if it
+ * is non-`null`.
*/
void _visitTokenWithSuffix(Token token, String suffix) {
if (token != null) {
@@ -19903,15 +18607,13 @@
}
/**
- * Instances of the class `TryStatement` represent a try statement.
+ * A try statement.
*
- * <pre>
- * tryStatement ::=
- * 'try' [Block] ([CatchClause]+ finallyClause? | finallyClause)
- *
- * finallyClause ::=
- * 'finally' [Block]
- * </pre>
+ * > tryStatement ::=
+ * > 'try' [Block] ([CatchClause]+ finallyClause? | finallyClause)
+ * >
+ * > finallyClause ::=
+ * > 'finally' [Block]
*/
class TryStatement extends Statement {
/**
@@ -19930,25 +18632,21 @@
NodeList<CatchClause> _catchClauses;
/**
- * The token representing the 'finally' keyword, or `null` if the statement does not contain
- * a finally clause.
+ * The token representing the 'finally' keyword, or `null` if the statement
+ * does not contain a finally clause.
*/
Token finallyKeyword;
/**
- * The finally block contained in the try statement, or `null` if the statement does not
- * contain a finally clause.
+ * The finally block contained in the try statement, or `null` if the
+ * statement does not contain a finally clause.
*/
Block _finallyBlock;
/**
- * Initialize a newly created try statement.
- *
- * @param tryKeyword the token representing the 'try' keyword
- * @param body the body of the statement
- * @param catchClauses the catch clauses contained in the try statement
- * @param finallyKeyword the token representing the 'finally' keyword
- * @param finallyBlock the finally block contained in the try statement
+ * Initialize a newly created try statement. The list of [catchClauses] can be
+ * `null` if there are no catch clauses. The [finallyKeyword] and
+ * [finallyBlock] can be `null` if there is no finally clause.
*/
TryStatement(this.tryKeyword, Block body, List<CatchClause> catchClauses,
this.finallyKeyword, Block finallyBlock) {
@@ -19962,15 +18660,11 @@
/**
* Return the body of the statement.
- *
- * @return the body of the statement
*/
Block get body => _body;
/**
- * Set the body of the statement to the given block.
- *
- * @param block the body of the statement
+ * Set the body of the statement to the given [block].
*/
void set body(Block block) {
_body = becomeParentOf(block);
@@ -19978,8 +18672,6 @@
/**
* Return the catch clauses contained in the try statement.
- *
- * @return the catch clauses contained in the try statement
*/
NodeList<CatchClause> get catchClauses => _catchClauses;
@@ -20004,17 +18696,13 @@
}
/**
- * Return the finally block contained in the try statement, or `null` if the statement does
- * not contain a finally clause.
- *
- * @return the finally block contained in the try statement
+ * Return the finally block contained in the try statement, or `null` if the
+ * statement does not contain a finally clause.
*/
Block get finallyBlock => _finallyBlock;
/**
- * Set the finally block contained in the try statement to the given block.
- *
- * @param block the finally block contained in the try statement
+ * Set the finally block contained in the try statement to the given [block].
*/
void set finallyBlock(Block block) {
_finallyBlock = becomeParentOf(block);
@@ -20025,23 +18713,21 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_body, visitor);
_catchClauses.accept(visitor);
- safelyVisitChild(_finallyBlock, visitor);
+ _safelyVisitChild(_finallyBlock, visitor);
}
}
/**
- * The abstract class `TypeAlias` defines the behavior common to declarations of type aliases.
+ * The declaration of a type alias.
*
- * <pre>
- * typeAlias ::=
- * 'typedef' typeAliasBody
- *
- * typeAliasBody ::=
- * classTypeAlias
- * | functionTypeAlias
- * </pre>
+ * > typeAlias ::=
+ * > 'typedef' typeAliasBody
+ * >
+ * > typeAliasBody ::=
+ * > classTypeAlias
+ * > | functionTypeAlias
*/
abstract class TypeAlias extends CompilationUnitMember {
/**
@@ -20055,12 +18741,9 @@
Token semicolon;
/**
- * Initialize a newly created type alias.
- *
- * @param comment the documentation comment associated with this type alias
- * @param metadata the annotations associated with this type alias
- * @param keyword the token representing the 'typedef' keyword
- * @param semicolon the semicolon terminating the declaration
+ * Initialize a newly created type alias. Either or both of the [comment] and
+ * [metadata] can be `null` if the declaration does not have the corresponding
+ * attribute.
*/
TypeAlias(Comment comment, List<Annotation> metadata, this.keyword,
this.semicolon)
@@ -20074,12 +18757,10 @@
}
/**
- * Instances of the class `TypeArgumentList` represent a list of type arguments.
+ * A list of type arguments.
*
- * <pre>
- * typeArguments ::=
- * '<' typeName (',' typeName)* '>'
- * </pre>
+ * > typeArguments ::=
+ * > '<' typeName (',' typeName)* '>'
*/
class TypeArgumentList extends AstNode {
/**
@@ -20099,10 +18780,6 @@
/**
* Initialize a newly created list of type arguments.
- *
- * @param leftBracket the left bracket
- * @param arguments the type arguments associated with the type
- * @param rightBracket the right bracket
*/
TypeArgumentList(this.leftBracket, List<TypeName> arguments,
this.rightBracket) {
@@ -20111,8 +18788,6 @@
/**
* Return the type arguments associated with the type.
- *
- * @return the type arguments associated with the type
*/
NodeList<TypeName> get arguments => _arguments;
@@ -20141,50 +18816,43 @@
}
/**
- * The abstract class `TypedLiteral` defines the behavior common to literals that have a type
- * associated with them.
+ * A literal that has a type associated with it.
*
- * <pre>
- * listLiteral ::=
- * [ListLiteral]
- * | [MapLiteral]
- * </pre>
+ * > typedLiteral ::=
+ * > [ListLiteral]
+ * > | [MapLiteral]
*/
abstract class TypedLiteral extends Literal {
/**
- * The token representing the 'const' keyword, or `null` if the literal is not a constant.
+ * The token representing the 'const' keyword, or `null` if the literal is not
+ * a constant.
*/
Token constKeyword;
/**
- * The type argument associated with this literal, or `null` if no type arguments were
- * declared.
+ * The type argument associated with this literal, or `null` if no type
+ * arguments were declared.
*/
TypeArgumentList _typeArguments;
/**
- * Initialize a newly created typed literal.
- *
- * @param constKeyword the token representing the 'const' keyword
- * @param typeArguments the type argument associated with this literal, or `null` if no type
- * arguments were declared
+ * Initialize a newly created typed literal. The [constKeyword] can be `null`\
+ * if the literal is not a constant. The [typeArguments] can be `null` if no
+ * type arguments were declared.
*/
TypedLiteral(this.constKeyword, TypeArgumentList typeArguments) {
_typeArguments = becomeParentOf(typeArguments);
}
/**
- * Return the type argument associated with this literal, or `null` if no type arguments
- * were declared.
- *
- * @return the type argument associated with this literal
+ * Return the type argument associated with this literal, or `null` if no type
+ * arguments were declared.
*/
TypeArgumentList get typeArguments => _typeArguments;
/**
- * Set the type argument associated with this literal to the given arguments.
- *
- * @param typeArguments the type argument associated with this literal
+ * Set the type argument associated with this literal to the given
+ * [typeArguments].
*/
void set typeArguments(TypeArgumentList typeArguments) {
_typeArguments = becomeParentOf(typeArguments);
@@ -20196,18 +18864,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_typeArguments, visitor);
+ _safelyVisitChild(_typeArguments, visitor);
}
}
/**
- * Instances of the class `TypeName` represent the name of a type, which can optionally
- * include type arguments.
+ * The name of a type, which can optionally include type arguments.
*
- * <pre>
- * typeName ::=
- * [Identifier] typeArguments?
- * </pre>
+ * > typeName ::=
+ * > [Identifier] typeArguments?
*/
class TypeName extends AstNode {
/**
@@ -20216,7 +18881,8 @@
Identifier _name;
/**
- * The type arguments associated with the type, or `null` if there are no type arguments.
+ * The type arguments associated with the type, or `null` if there are no type
+ * arguments.
*/
TypeArgumentList _typeArguments;
@@ -20226,11 +18892,8 @@
DartType type;
/**
- * Initialize a newly created type name.
- *
- * @param name the name of the type
- * @param typeArguments the type arguments associated with the type, or `null` if there are
- * no type arguments
+ * Initialize a newly created type name. The [typeArguments] can be `null` if
+ * there are no type arguments.
*/
TypeName(Identifier name, TypeArgumentList typeArguments) {
_name = becomeParentOf(name);
@@ -20256,10 +18919,8 @@
/**
* Return `true` if this type is a deferred type.
*
- * 15.1 Static Types: A type <i>T</i> is deferred iff it is of the form </i>p.T</i> where <i>p</i>
- * is a deferred prefix.
- *
- * @return `true` if this type is a deferred type
+ * 15.1 Static Types: A type <i>T</i> is deferred iff it is of the form
+ * </i>p.T</i> where <i>p</i> is a deferred prefix.
*/
bool get isDeferred {
Identifier identifier = name;
@@ -20274,32 +18935,25 @@
/**
* Return the name of the type.
- *
- * @return the name of the type
*/
Identifier get name => _name;
/**
- * Set the name of the type to the given identifier.
- *
- * @param identifier the name of the type
+ * Set the name of the type to the given [identifier].
*/
void set name(Identifier identifier) {
_name = becomeParentOf(identifier);
}
/**
- * Return the type arguments associated with the type, or `null` if there are no type
- * arguments.
- *
- * @return the type arguments associated with the type
+ * Return the type arguments associated with the type, or `null` if there are
+ * no type arguments.
*/
TypeArgumentList get typeArguments => _typeArguments;
/**
- * Set the type arguments associated with the type to the given type arguments.
- *
- * @param typeArguments the type arguments associated with the type
+ * Set the type arguments associated with the type to the given
+ * [typeArguments].
*/
void set typeArguments(TypeArgumentList typeArguments) {
_typeArguments = becomeParentOf(typeArguments);
@@ -20310,18 +18964,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_typeArguments, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_typeArguments, visitor);
}
}
/**
- * Instances of the class `TypeParameter` represent a type parameter.
+ * A type parameter.
*
- * <pre>
- * typeParameter ::=
- * [SimpleIdentifier] ('extends' [TypeName])?
- * </pre>
+ * > typeParameter ::=
+ * > [SimpleIdentifier] ('extends' [TypeName])?
*/
class TypeParameter extends Declaration {
/**
@@ -20330,25 +18982,22 @@
SimpleIdentifier _name;
/**
- * The token representing the 'extends' keyword, or `null` if there was no explicit upper
- * bound.
+ * The token representing the 'extends' keyword, or `null` if there is no
+ * explicit upper bound.
*/
Token keyword;
/**
- * The name of the upper bound for legal arguments, or `null` if there was no explicit upper
- * bound.
+ * The name of the upper bound for legal arguments, or `null` if there is no
+ * explicit upper bound.
*/
TypeName _bound;
/**
- * Initialize a newly created type parameter.
- *
- * @param comment the documentation comment associated with the type parameter
- * @param metadata the annotations associated with the type parameter
- * @param name the name of the type parameter
- * @param keyword the token representing the 'extends' keyword
- * @param bound the name of the upper bound for legal arguments
+ * Initialize a newly created type parameter. Either or both of the [comment]
+ * and [metadata] can be `null` if the parameter does not have the
+ * corresponding attribute. The [keyword] and [bound] can be `null` if the
+ * parameter does not have an upper bound.
*/
TypeParameter(Comment comment, List<Annotation> metadata,
SimpleIdentifier name, this.keyword, TypeName bound)
@@ -20358,17 +19007,14 @@
}
/**
- * Return the name of the upper bound for legal arguments, or `null` if there was no
- * explicit upper bound.
- *
- * @return the name of the upper bound for legal arguments
+ * Return the name of the upper bound for legal arguments, or `null` if there
+ * is no explicit upper bound.
*/
TypeName get bound => _bound;
/**
- * Set the name of the upper bound for legal arguments to the given type name.
- *
- * @param typeName the name of the upper bound for legal arguments
+ * Set the name of the upper bound for legal arguments to the given
+ * [typeName].
*/
void set bound(TypeName typeName) {
_bound = becomeParentOf(typeName);
@@ -20397,15 +19043,11 @@
/**
* Return the name of the type parameter.
- *
- * @return the name of the type parameter
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the type parameter to the given identifier.
- *
- * @param identifier the name of the type parameter
+ * Set the name of the type parameter to the given [identifier].
*/
void set name(SimpleIdentifier identifier) {
_name = becomeParentOf(identifier);
@@ -20417,18 +19059,16 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_bound, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_bound, visitor);
}
}
/**
- * Instances of the class `TypeParameterList` represent type parameters within a declaration.
+ * Type parameters within a declaration.
*
- * <pre>
- * typeParameterList ::=
- * '<' [TypeParameter] (',' [TypeParameter])* '>'
- * </pre>
+ * > typeParameterList ::=
+ * > '<' [TypeParameter] (',' [TypeParameter])* '>'
*/
class TypeParameterList extends AstNode {
/**
@@ -20448,10 +19088,6 @@
/**
* Initialize a newly created list of type parameters.
- *
- * @param leftBracket the left angle bracket
- * @param typeParameters the type parameters in the list
- * @param rightBracket the right angle bracket
*/
TypeParameterList(this.leftBracket, List<TypeParameter> typeParameters,
this.rightBracket) {
@@ -20472,8 +19108,6 @@
/**
* Return the type parameters for the type.
- *
- * @return the type parameters for the type
*/
NodeList<TypeParameter> get typeParameters => _typeParameters;
@@ -20487,14 +19121,14 @@
}
/**
- * Instances of the class `UnifyingAstVisitor` implement an AST visitor that will recursively
- * visit all of the nodes in an AST structure (like instances of the class
- * [RecursiveAstVisitor]). In addition, every node will also be visited by using a single
- * unified [visitNode] method.
+ * An AST visitor that will recursively visit all of the nodes in an AST
+ * structure (like instances of the class [RecursiveAstVisitor]). In addition,
+ * every node will also be visited by using a single unified [visitNode] method.
*
- * Subclasses that override a visit method must either invoke the overridden visit method or
- * explicitly invoke the more general [visitNode] method. Failure to do so will
- * cause the children of the visited node to not be visited.
+ * Subclasses that override a visit method must either invoke the overridden
+ * visit method or explicitly invoke the more general [visitNode] method.
+ * Failure to do so will cause the children of the visited node to not be
+ * visited.
*/
class UnifyingAstVisitor<R> implements AstVisitor<R> {
@override
@@ -20836,19 +19470,17 @@
}
/**
- * The abstract class `UriBasedDirective` defines the behavior common to nodes that represent
- * a directive that references a URI.
+ * A directive that references a URI.
*
- * <pre>
- * uriBasedDirective ::=
- * [ExportDirective]
- * | [ImportDirective]
- * | [PartDirective]
- * </pre>
+ * > uriBasedDirective ::=
+ * > [ExportDirective]
+ * > | [ImportDirective]
+ * > | [PartDirective]
*/
abstract class UriBasedDirective extends Directive {
/**
- * The prefix of a URI using the `dart-ext` scheme to reference a native code library.
+ * The prefix of a URI using the `dart-ext` scheme to reference a native code
+ * library.
*/
static String _DART_EXT_SCHEME = "dart-ext:";
@@ -20868,11 +19500,9 @@
Source source;
/**
- * Initialize a newly create URI-based directive.
- *
- * @param comment the documentation comment associated with this directive
- * @param metadata the annotations associated with the directive
- * @param uri the URI referenced by this directive
+ * Initialize a newly create URI-based directive. Either or both of the
+ * [comment] and [metadata] can be `null` if the directive does not have the
+ * corresponding attribute.
*/
UriBasedDirective(Comment comment, List<Annotation> metadata,
StringLiteral uri)
@@ -20882,33 +19512,27 @@
/**
* Return the URI referenced by this directive.
- *
- * @return the URI referenced by this directive
*/
StringLiteral get uri => _uri;
/**
- * Set the URI referenced by this directive to the given URI.
- *
- * @param uri the URI referenced by this directive
+ * Set the URI referenced by this directive to the given [uri].
*/
void set uri(StringLiteral uri) {
_uri = becomeParentOf(uri);
}
/**
- * Return the element associated with the URI of this directive, or `null` if the AST
- * structure has not been resolved or if the URI could not be resolved. Examples of the latter
- * case include a directive that contains an invalid URL or a URL that does not exist.
- *
- * @return the element associated with this directive
+ * Return the element associated with the URI of this directive, or `null` if
+ * the AST structure has not been resolved or if the URI could not be
+ * resolved. Examples of the latter case include a directive that contains an
+ * invalid URL or a URL that does not exist.
*/
Element get uriElement;
/**
- * Validate the given directive, but do not check for existence.
- *
- * @return a code indicating the problem if there is one, or `null` no problem
+ * Validate this directive, but do not check for existence. Return a code
+ * indicating the problem if there is one, or `null` no problem
*/
UriValidationCode validate() {
StringLiteral uriLiteral = uri;
@@ -20933,7 +19557,7 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_uri, visitor);
+ _safelyVisitChild(_uri, visitor);
}
}
@@ -20965,14 +19589,11 @@
}
/**
- * Instances of the class `VariableDeclaration` represent an identifier that has an initial
- * value associated with it. Instances of this class are always children of the class
- * [VariableDeclarationList].
+ * An identifier that has an initial value associated with it. Instances of this
+ * class are always children of the class [VariableDeclarationList].
*
- * <pre>
- * variableDeclaration ::=
- * [SimpleIdentifier] ('=' [Expression])?
- * </pre>
+ * > variableDeclaration ::=
+ * > [SimpleIdentifier] ('=' [Expression])?
*/
class VariableDeclaration extends Declaration {
/**
@@ -20981,25 +19602,22 @@
SimpleIdentifier _name;
/**
- * The equal sign separating the variable name from the initial value, or `null` if the
- * initial value was not specified.
+ * The equal sign separating the variable name from the initial value, or
+ * `null` if the initial value was not specified.
*/
Token equals;
/**
- * The expression used to compute the initial value for the variable, or `null` if the
- * initial value was not specified.
+ * The expression used to compute the initial value for the variable, or
+ * `null` if the initial value was not specified.
*/
Expression _initializer;
/**
- * Initialize a newly created variable declaration.
- *
- * @param comment the documentation comment associated with this declaration
- * @param metadata the annotations associated with this member
- * @param name the name of the variable being declared
- * @param equals the equal sign separating the variable name from the initial value
- * @param initializer the expression used to compute the initial value for the variable
+ * Initialize a newly created variable declaration. Either or both of the
+ * [comment] and [metadata] can be `null` if the declaration does not have the
+ * corresponding attribute. The [equals] and [initializer] can be `null` if
+ * there is no initializer.
*/
VariableDeclaration(Comment comment, List<Annotation> metadata,
SimpleIdentifier name, this.equals, Expression initializer)
@@ -21015,8 +19633,9 @@
..add(_initializer);
/**
- * This overridden implementation of getDocumentationComment() looks in the grandparent node for
- * dartdoc comments if no documentation is specifically available on the node.
+ * This overridden implementation of getDocumentationComment() looks in the
+ * grandparent node for dartdoc comments if no documentation is specifically
+ * available on the node.
*/
@override
Comment get documentationComment {
@@ -21048,26 +19667,21 @@
Token get firstTokenAfterCommentAndMetadata => _name.beginToken;
/**
- * Return the expression used to compute the initial value for the variable, or `null` if
- * the initial value was not specified.
- *
- * @return the expression used to compute the initial value for the variable
+ * Return the expression used to compute the initial value for the variable,
+ * or `null` if the initial value was not specified.
*/
Expression get initializer => _initializer;
/**
- * Set the expression used to compute the initial value for the variable to the given expression.
- *
- * @param initializer the expression used to compute the initial value for the variable
+ * Set the expression used to compute the initial value for the variable to
+ * the given [expression].
*/
- void set initializer(Expression initializer) {
- _initializer = becomeParentOf(initializer);
+ void set initializer(Expression expression) {
+ _initializer = becomeParentOf(expression);
}
/**
* Return `true` if this variable was declared with the 'const' modifier.
- *
- * @return `true` if this variable was declared with the 'const' modifier
*/
bool get isConst {
AstNode parent = this.parent;
@@ -21075,11 +19689,9 @@
}
/**
- * Return `true` if this variable was declared with the 'final' modifier. Variables that are
- * declared with the 'const' modifier will return `false` even though they are implicitly
- * final.
- *
- * @return `true` if this variable was declared with the 'final' modifier
+ * Return `true` if this variable was declared with the 'final' modifier.
+ * Variables that are declared with the 'const' modifier will return `false`
+ * even though they are implicitly final.
*/
bool get isFinal {
AstNode parent = this.parent;
@@ -21088,18 +19700,14 @@
/**
* Return the name of the variable being declared.
- *
- * @return the name of the variable being declared
*/
SimpleIdentifier get name => _name;
/**
- * Set the name of the variable being declared to the given identifier.
- *
- * @param name the name of the variable being declared
+ * Set the name of the variable being declared to the given [identifier].
*/
- void set name(SimpleIdentifier name) {
- _name = becomeParentOf(name);
+ void set name(SimpleIdentifier identifier) {
+ _name = becomeParentOf(identifier);
}
@override
@@ -21108,30 +19716,27 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_name, visitor);
- safelyVisitChild(_initializer, visitor);
+ _safelyVisitChild(_name, visitor);
+ _safelyVisitChild(_initializer, visitor);
}
}
/**
- * Instances of the class `VariableDeclarationList` represent the declaration of one or more
- * variables of the same type.
+ * The declaration of one or more variables of the same type.
*
- * <pre>
- * variableDeclarationList ::=
- * finalConstVarOrType [VariableDeclaration] (',' [VariableDeclaration])*
- *
- * finalConstVarOrType ::=
- * | 'final' [TypeName]?
- * | 'const' [TypeName]?
- * | 'var'
- * | [TypeName]
- * </pre>
+ * > variableDeclarationList ::=
+ * > finalConstVarOrType [VariableDeclaration] (',' [VariableDeclaration])*
+ * >
+ * > finalConstVarOrType ::=
+ * > | 'final' [TypeName]?
+ * > | 'const' [TypeName]?
+ * > | 'var'
+ * > | [TypeName]
*/
class VariableDeclarationList extends AnnotatedNode {
/**
- * The token representing the 'final', 'const' or 'var' keyword, or `null` if no keyword was
- * included.
+ * The token representing the 'final', 'const' or 'var' keyword, or `null` if
+ * no keyword was included.
*/
Token keyword;
@@ -21146,13 +19751,10 @@
NodeList<VariableDeclaration> _variables;
/**
- * Initialize a newly created variable declaration list.
- *
- * @param comment the documentation comment associated with this declaration list
- * @param metadata the annotations associated with this declaration list
- * @param keyword the token representing the 'final', 'const' or 'var' keyword
- * @param type the type of the variables being declared
- * @param variables a list containing the individual variables being declared
+ * Initialize a newly created variable declaration list. Either or both of the
+ * [comment] and [metadata] can be `null` if the variable list does not have
+ * the corresponding attribute. The [keyword] can be `null` if a type was
+ * specified. The [type] must be `null` if the keyword is 'var'.
*/
VariableDeclarationList(Comment comment, List<Annotation> metadata,
this.keyword, TypeName type, List<VariableDeclaration> variables)
@@ -21184,34 +19786,29 @@
}
/**
- * Return `true` if the variables in this list were declared with the 'const' modifier.
- *
- * @return `true` if the variables in this list were declared with the 'const' modifier
+ * Return `true` if the variables in this list were declared with the 'const'
+ * modifier.
*/
bool get isConst =>
keyword is KeywordToken && (keyword as KeywordToken).keyword == Keyword.CONST;
/**
- * Return `true` if the variables in this list were declared with the 'final' modifier.
- * Variables that are declared with the 'const' modifier will return `false` even though
- * they are implicitly final.
- *
- * @return `true` if the variables in this list were declared with the 'final' modifier
+ * Return `true` if the variables in this list were declared with the 'final'
+ * modifier. Variables that are declared with the 'const' modifier will return
+ * `false` even though they are implicitly final. (In other words, this is a
+ * syntactic check rather than a semantic check.)
*/
bool get isFinal =>
keyword is KeywordToken && (keyword as KeywordToken).keyword == Keyword.FINAL;
/**
- * Return the type of the variables being declared, or `null` if no type was provided.
- *
- * @return the type of the variables being declared
+ * Return the type of the variables being declared, or `null` if no type was
+ * provided.
*/
TypeName get type => _type;
/**
- * Set the type of the variables being declared to the given type name.
- *
- * @param typeName the type of the variables being declared
+ * Set the type of the variables being declared to the given [typeName].
*/
void set type(TypeName typeName) {
_type = becomeParentOf(typeName);
@@ -21219,8 +19816,6 @@
/**
* Return a list containing the individual variables being declared.
- *
- * @return a list containing the individual variables being declared
*/
NodeList<VariableDeclaration> get variables => _variables;
@@ -21230,19 +19825,17 @@
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
- safelyVisitChild(_type, visitor);
+ _safelyVisitChild(_type, visitor);
_variables.accept(visitor);
}
}
/**
- * Instances of the class `VariableDeclarationStatement` represent a list of variables that
- * are being declared in a context where a statement is required.
+ * A list of variables that are being declared in a context where a statement is
+ * required.
*
- * <pre>
- * variableDeclarationStatement ::=
- * [VariableDeclarationList] ';'
- * </pre>
+ * > variableDeclarationStatement ::=
+ * > [VariableDeclarationList] ';'
*/
class VariableDeclarationStatement extends Statement {
/**
@@ -21257,9 +19850,6 @@
/**
* Initialize a newly created variable declaration statement.
- *
- * @param variableList the fields being declared
- * @param semicolon the semicolon terminating the statement
*/
VariableDeclarationStatement(VariableDeclarationList variableList,
this.semicolon) {
@@ -21279,18 +19869,14 @@
/**
* Return the variables being declared.
- *
- * @return the variables being declared
*/
VariableDeclarationList get variables => _variableList;
/**
- * Set the variables being declared to the given list of variables.
- *
- * @param variableList the variables being declared
+ * Set the variables being declared to the given list of [variables].
*/
- void set variables(VariableDeclarationList variableList) {
- _variableList = becomeParentOf(variableList);
+ void set variables(VariableDeclarationList variables) {
+ _variableList = becomeParentOf(variables);
}
@override
@@ -21298,17 +19884,15 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_variableList, visitor);
+ _safelyVisitChild(_variableList, visitor);
}
}
/**
- * Instances of the class `WhileStatement` represent a while statement.
+ * A while statement.
*
- * <pre>
- * whileStatement ::=
- * 'while' '(' [Expression] ')' [Statement]
- * </pre>
+ * > whileStatement ::=
+ * > 'while' '(' [Expression] ')' [Statement]
*/
class WhileStatement extends Statement {
/**
@@ -21338,12 +19922,6 @@
/**
* Initialize a newly created while statement.
- *
- * @param keyword the token representing the 'while' keyword
- * @param leftParenthesis the left parenthesis
- * @param condition the expression used to determine whether to execute the body of the loop
- * @param rightParenthesis the right parenthesis
- * @param body the body of the loop
*/
WhileStatement(this.keyword, this.leftParenthesis, Expression condition,
this.rightParenthesis, Statement body) {
@@ -21356,15 +19934,11 @@
/**
* Return the body of the loop.
- *
- * @return the body of the loop
*/
Statement get body => _body;
/**
- * Set the body of the loop to the given statement.
- *
- * @param statement the body of the loop
+ * Set the body of the loop to the given [statement].
*/
void set body(Statement statement) {
_body = becomeParentOf(statement);
@@ -21379,17 +19953,14 @@
..add(_body);
/**
- * Return the expression used to determine whether to execute the body of the loop.
- *
- * @return the expression used to determine whether to execute the body of the loop
+ * Return the expression used to determine whether to execute the body of the
+ * loop.
*/
Expression get condition => _condition;
/**
- * Set the expression used to determine whether to execute the body of the loop to the given
- * expression.
- *
- * @param expression the expression used to determine whether to execute the body of the loop
+ * Set the expression used to determine whether to execute the body of the
+ * loop to the given [expression].
*/
void set condition(Expression expression) {
_condition = becomeParentOf(expression);
@@ -21403,18 +19974,16 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_condition, visitor);
- safelyVisitChild(_body, visitor);
+ _safelyVisitChild(_condition, visitor);
+ _safelyVisitChild(_body, visitor);
}
}
/**
- * Instances of the class `WithClause` represent the with clause in a class declaration.
+ * The with clause in a class declaration.
*
- * <pre>
- * withClause ::=
- * 'with' [TypeName] (',' [TypeName])*
- * </pre>
+ * > withClause ::=
+ * > 'with' [TypeName] (',' [TypeName])*
*/
class WithClause extends AstNode {
/**
@@ -21429,9 +19998,6 @@
/**
* Initialize a newly created with clause.
- *
- * @param withKeyword the token representing the 'with' keyword
- * @param mixinTypes the names of the mixins that were specified
*/
WithClause(this.withKeyword, List<TypeName> mixinTypes) {
_mixinTypes = new NodeList<TypeName>(this, mixinTypes);
@@ -21452,19 +20018,17 @@
Token get endToken => _mixinTypes.endToken;
/**
- * Set the token representing the 'with' keyword to the given token.
+ * Set the token representing the 'with' keyword to the given [token].
*
- * @param withKeyword the token representing the 'with' keyword
+ * Deprecated: Use withKeyword instead.
*/
@deprecated
- void set mixinKeyword(Token withKeyword) {
- this.withKeyword = withKeyword;
+ void set mixinKeyword(Token token) {
+ this.withKeyword = token;
}
/**
* Return the names of the mixins that were specified.
- *
- * @return the names of the mixins that were specified
*/
NodeList<TypeName> get mixinTypes => _mixinTypes;
@@ -21478,7 +20042,10 @@
}
/**
- * Instances of the class `YieldStatement` implement a yield statement.
+ * A yield statement.
+ *
+ * > yieldStatement ::=
+ * > 'yield' '*'? [Expression] ‘;’
*/
class YieldStatement extends Statement {
/**
@@ -21502,12 +20069,8 @@
Token semicolon;
/**
- * Initialize a newly created yield expression.
- *
- * @param yieldKeyword the 'yield' keyword
- * @param star the star following the 'yield' keyword
- * @param expression the expression whose value will be yielded
- * @param semicolon the semicolon following the expression
+ * Initialize a newly created yield expression. The [star] can be `null` if no
+ * star was provided.
*/
YieldStatement(this.yieldKeyword, this.star, Expression expression,
this.semicolon) {
@@ -21542,15 +20105,11 @@
/**
* Return the expression whose value will be yielded.
- *
- * @return the expression whose value will be yielded
*/
Expression get expression => _expression;
/**
- * Set the expression whose value will be yielded to the given expression.
- *
- * @param expression the expression whose value will be yielded
+ * Set the expression whose value will be yielded to the given [expression].
*/
void set expression(Expression expression) {
_expression = becomeParentOf(expression);
@@ -21561,6 +20120,6 @@
@override
void visitChildren(AstVisitor visitor) {
- safelyVisitChild(_expression, visitor);
+ _safelyVisitChild(_expression, visitor);
}
}
diff --git a/pkg/analyzer/lib/src/generated/constant.dart b/pkg/analyzer/lib/src/generated/constant.dart
index b756a9d..dfa60c1 100644
--- a/pkg/analyzer/lib/src/generated/constant.dart
+++ b/pkg/analyzer/lib/src/generated/constant.dart
@@ -9,12 +9,13 @@
import 'dart:collection';
+import 'package:analyzer/src/generated/utilities_general.dart';
+
import 'ast.dart';
import 'element.dart';
import 'engine.dart' show AnalysisEngine, RecordingErrorListener;
import 'error.dart';
import 'java_core.dart';
-import 'java_engine.dart' show ObjectUtilities;
import 'resolver.dart' show TypeProvider;
import 'scanner.dart' show Token, TokenType;
import 'source.dart' show Source;
@@ -1265,6 +1266,19 @@
void beforeGetEvaluationResult(AstNode node) {
}
+ /**
+ * Return `true` if the given [element] represents the `length` getter in
+ * class [String].
+ */
+ bool isStringLength(Element element) {
+ if (element is PropertyAccessorElement) {
+ if (element.isGetter && element.name == 'length') {
+ return element.enclosingElement == _typeProvider.stringType.element;
+ }
+ }
+ return false;
+ }
+
@override
DartObjectImpl visitAdjacentStrings(AdjacentStrings node) {
DartObjectImpl result = null;
@@ -1547,13 +1561,15 @@
@override
DartObjectImpl visitPrefixedIdentifier(PrefixedIdentifier node) {
- // TODO(brianwilkerson) Uncomment the lines below when the new constant
- // support can be added.
- // Element element = node.getStaticElement();
- // if (isStringLength(element)) {
- // EvaluationResultImpl target = node.getPrefix().accept(this);
- // return target.stringLength(typeProvider, node);
- // }
+ // String.length
+ {
+ Element element = node.staticElement;
+ if (isStringLength(element)) {
+ DartObjectImpl prefixResult = node.prefix.accept(this);
+ return prefixResult.stringLength(_typeProvider);
+ }
+ }
+ // importPrefix.CONST
SimpleIdentifier prefixNode = node.prefix;
Element prefixElement = prefixNode.staticElement;
if (prefixElement is! PrefixElement) {
@@ -1593,12 +1609,10 @@
@override
DartObjectImpl visitPropertyAccess(PropertyAccess node) {
Element element = node.propertyName.staticElement;
- // TODO(brianwilkerson) Uncomment the lines below when the new constant
- // support can be added.
- // if (isStringLength(element)) {
- // EvaluationResultImpl target = node.getRealTarget().accept(this);
- // return target.stringLength(typeProvider, node);
- // }
+ if (isStringLength(element)) {
+ DartObjectImpl prefixResult = node.realTarget.accept(this);
+ return prefixResult.stringLength(_typeProvider);
+ }
return _getConstantValue(node, element);
}
@@ -2210,8 +2224,7 @@
bool get hasExactValue => _state.hasExactValue;
@override
- int get hashCode =>
- ObjectUtilities.combineHashCodes(type.hashCode, _state.hashCode);
+ int get hashCode => JenkinsSmiHash.hash2(type.hashCode, _state.hashCode);
@override
int get intValue {
@@ -3582,6 +3595,25 @@
}
return BoolState.from(this == rightOperand);
}
+
+ @override
+ String toString() {
+ StringBuffer buffer = new StringBuffer();
+ List<String> fieldNames = _fieldMap.keys.toList();
+ fieldNames.sort();
+ bool first = true;
+ for (String fieldName in fieldNames) {
+ if (first) {
+ first = false;
+ } else {
+ buffer.write('; ');
+ }
+ buffer.write(fieldName);
+ buffer.write(' = ');
+ buffer.write(_fieldMap[fieldName]);
+ }
+ return buffer.toString();
+ }
}
/**
@@ -3646,11 +3678,9 @@
* @throws EvaluationException if the operator is not appropriate for an object of this kind
*/
InstanceState add(InstanceState rightOperand) {
- // TODO(brianwilkerson) Uncomment the code below when the new constant
- // support can be added.
-// if (this instanceof StringState || rightOperand instanceof StringState) {
-// return concatenate(rightOperand);
-// }
+ if (this is StringState && rightOperand is StringState) {
+ return concatenate(rightOperand);
+ }
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(CompileTimeErrorCode.INVALID_CONSTANT);
@@ -4595,6 +4625,23 @@
}
return BoolState.from(this == rightOperand);
}
+
+ @override
+ String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.write('[');
+ bool first = true;
+ _elements.forEach((DartObjectImpl element) {
+ if (first) {
+ first = false;
+ } else {
+ buffer.write(', ');
+ }
+ buffer.write(element);
+ });
+ buffer.write(']');
+ return buffer.toString();
+ }
}
/**
@@ -4688,6 +4735,25 @@
}
return BoolState.from(this == rightOperand);
}
+
+ @override
+ String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.write('{');
+ bool first = true;
+ _entries.forEach((DartObjectImpl key, DartObjectImpl value) {
+ if (first) {
+ first = false;
+ } else {
+ buffer.write(', ');
+ }
+ buffer.write(key);
+ buffer.write(' = ');
+ buffer.write(value);
+ });
+ buffer.write('}');
+ return buffer.toString();
+ }
}
/**
diff --git a/pkg/analyzer/lib/src/generated/element.dart b/pkg/analyzer/lib/src/generated/element.dart
index ebfbcac..bcd681f 100644
--- a/pkg/analyzer/lib/src/generated/element.dart
+++ b/pkg/analyzer/lib/src/generated/element.dart
@@ -9,6 +9,8 @@
import 'dart:collection';
+import 'package:analyzer/src/generated/utilities_general.dart';
+
import 'ast.dart';
import 'constant.dart' show EvaluationResultImpl;
import 'engine.dart' show AnalysisContext, AnalysisEngine, AnalysisException;
@@ -1498,9 +1500,7 @@
@override
bool operator ==(Object object) =>
- object != null &&
- runtimeType == object.runtimeType &&
- source == (object as CompilationUnitElementImpl).source;
+ object is CompilationUnitElementImpl && source == object.source;
@override
accept(ElementVisitor visitor) => visitor.visitCompilationUnitElement(this);
@@ -1677,6 +1677,12 @@
bool get isFactory;
/**
+ * Return the offset of the character immediately following the last character
+ * of this constructor's name, or `null` if not named.
+ */
+ int get nameEnd;
+
+ /**
* Return the resolved [ConstructorDeclaration] node that declares this
* [ConstructorElement] .
*
@@ -1689,6 +1695,12 @@
ConstructorDeclaration get node;
/**
+ * Return the offset of the `.` before this constructor name, or `null` if
+ * not named.
+ */
+ int get periodOffset;
+
+ /**
* Return the constructor to which this constructor is redirecting, or `null` if this
* constructor does not redirect to another constructor or if the library containing this
* constructor has not yet been resolved.
@@ -1722,6 +1734,17 @@
List<ConstructorInitializer> constantInitializers;
/**
+ * The offset of the `.` before this constructor name or `null` if not named.
+ */
+ int periodOffset;
+
+ /**
+ * Return the offset of the character immediately following the last character
+ * of this constructor's name, or `null` if not named.
+ */
+ int nameEnd;
+
+ /**
* Initialize a newly created constructor element to have the given name.
*
* @param name the name of this element
@@ -1852,9 +1875,15 @@
bool get isFactory => baseElement.isFactory;
@override
+ int get nameEnd => baseElement.nameEnd;
+
+ @override
ConstructorDeclaration get node => baseElement.node;
@override
+ int get periodOffset => baseElement.periodOffset;
+
+ @override
ConstructorElement get redirectedConstructor =>
from(baseElement.redirectedConstructor, definingType);
@@ -3281,22 +3310,29 @@
*/
class ElementPair {
/**
- * The first [Element]
+ * The first [Element].
*/
final Element _first;
/**
- * The second [Element]
+ * The second [Element].
*/
final Element _second;
/**
+ * A cached copy of the calculated hashCode for this element.
+ */
+ int _cachedHashCode;
+
+ /**
* The sole constructor for this class, taking two [Element]s.
*
* @param first the first element
* @param second the second element
*/
- ElementPair(this._first, this._second);
+ ElementPair(this._first, this._second) {
+ _cachedHashCode = JenkinsSmiHash.hash2(_first.hashCode, _second.hashCode);
+ }
/**
* Return the first element.
@@ -3306,8 +3342,9 @@
Element get firstElt => _first;
@override
- int get hashCode =>
- ObjectUtilities.combineHashCodes(_first.hashCode, _second.hashCode);
+ int get hashCode {
+ return _cachedHashCode;
+ }
/**
* Return the second element
@@ -3321,11 +3358,9 @@
if (identical(object, this)) {
return true;
}
- if (object is ElementPair) {
- ElementPair elementPair = object;
- return (_first == elementPair._first) && (_second == elementPair._second);
- }
- return false;
+ return object is ElementPair &&
+ _first == object._first &&
+ _second == object._second;
}
}
@@ -4800,32 +4835,6 @@
int get hashCode => internalHashCode(<DartType>[]);
@override
- int internalHashCode(List<DartType> visitedTypes) {
- if (element == null) {
- return 0;
- } else if (visitedTypes.contains(this)) {
- return 3;
- }
- visitedTypes.add(this);
- // Reference the arrays of parameters
- List<DartType> normalParameterTypes = this.normalParameterTypes;
- List<DartType> optionalParameterTypes = this.optionalParameterTypes;
- Iterable<DartType> namedParameterTypes = this.namedParameterTypes.values;
- // Generate the hashCode
- int code = (returnType as TypeImpl).internalHashCode(visitedTypes);
- for (int i = 0; i < normalParameterTypes.length; i++) {
- code = (code << 1) + (normalParameterTypes[i] as TypeImpl).internalHashCode(visitedTypes);
- }
- for (int i = 0; i < optionalParameterTypes.length; i++) {
- code = (code << 1) + (optionalParameterTypes[i] as TypeImpl).internalHashCode(visitedTypes);
- }
- for (DartType type in namedParameterTypes) {
- code = (code << 1) + (type as TypeImpl).internalHashCode(visitedTypes);
- }
- return code;
- }
-
- @override
Map<String, DartType> get namedParameterTypes {
LinkedHashMap<String, DartType> namedParameterTypes =
new LinkedHashMap<String, DartType>();
@@ -5049,6 +5058,34 @@
}
@override
+ int internalHashCode(List<DartType> visitedTypes) {
+ if (element == null) {
+ return 0;
+ } else if (visitedTypes.contains(this)) {
+ return 3;
+ }
+ visitedTypes.add(this);
+ // Reference the arrays of parameters
+ List<DartType> normalParameterTypes = this.normalParameterTypes;
+ List<DartType> optionalParameterTypes = this.optionalParameterTypes;
+ Iterable<DartType> namedParameterTypes = this.namedParameterTypes.values;
+ // Generate the hashCode
+ int code = (returnType as TypeImpl).internalHashCode(visitedTypes);
+ for (int i = 0; i < normalParameterTypes.length; i++) {
+ code = (code << 1) +
+ (normalParameterTypes[i] as TypeImpl).internalHashCode(visitedTypes);
+ }
+ for (int i = 0; i < optionalParameterTypes.length; i++) {
+ code = (code << 1) +
+ (optionalParameterTypes[i] as TypeImpl).internalHashCode(visitedTypes);
+ }
+ for (DartType type in namedParameterTypes) {
+ code = (code << 1) + (type as TypeImpl).internalHashCode(visitedTypes);
+ }
+ return code;
+ }
+
+ @override
bool internalIsMoreSpecificThan(DartType type, bool withDynamic,
Set<TypeImpl_TypePair> visitedTypePairs) {
// trivial base cases
@@ -5654,11 +5691,7 @@
if (identical(object, this)) {
return true;
}
- if (object == null) {
- return false;
- }
- return runtimeType == object.runtimeType &&
- source == (object as HtmlElementImpl).source;
+ return object is HtmlElementImpl && source == object.source;
}
@override
@@ -6272,9 +6305,6 @@
}
@override
- int internalHashCode(List<DartType> visitedTypes) => hashCode;
-
- @override
List<InterfaceType> get interfaces {
ClassElement classElement = element;
List<InterfaceType> interfaces = classElement.interfaces;
@@ -6460,6 +6490,9 @@
}
@override
+ int internalHashCode(List<DartType> visitedTypes) => hashCode;
+
+ @override
bool internalIsMoreSpecificThan(DartType type, bool withDynamic,
Set<TypeImpl_TypePair> visitedTypePairs) {
//
@@ -7594,10 +7627,8 @@
@override
bool operator ==(Object object) =>
- object != null &&
- runtimeType == object.runtimeType &&
- _definingCompilationUnit ==
- (object as LibraryElementImpl).definingCompilationUnit;
+ object is LibraryElementImpl &&
+ _definingCompilationUnit == object.definingCompilationUnit;
@override
accept(ElementVisitor visitor) => visitor.visitLibraryElement(this);
@@ -9288,8 +9319,7 @@
}
@override
- int get hashCode =>
- ObjectUtilities.combineHashCodes(super.hashCode, isGetter ? 1 : 2);
+ int get hashCode => JenkinsSmiHash.hash2(super.hashCode, isGetter ? 1 : 2);
@override
String get identifier {
@@ -10619,9 +10649,6 @@
int get hashCode => _types.hashCode;
@override
- int internalHashCode(List<DartType> visitedTypes) => hashCode;
-
- @override
bool operator ==(Object other) {
if (other == null || other is! UnionType) {
return false;
@@ -10652,6 +10679,9 @@
this == object;
@override
+ int internalHashCode(List<DartType> visitedTypes) => hashCode;
+
+ @override
bool internalIsMoreSpecificThan(DartType type, bool withDynamic,
Set<TypeImpl_TypePair> visitedTypePairs) {
// What version of subtyping do we want? See discussion below in
@@ -11130,9 +11160,6 @@
int get hashCode => 2;
@override
- int internalHashCode(List<DartType> visitedTypes) => hashCode;
-
- @override
bool get isVoid => true;
@override
@@ -11143,6 +11170,9 @@
identical(object, this);
@override
+ int internalHashCode(List<DartType> visitedTypes) => hashCode;
+
+ @override
bool internalIsMoreSpecificThan(DartType type, bool withDynamic,
Set<TypeImpl_TypePair> visitedTypePairs) =>
isSubtypeOf(type);
diff --git a/pkg/analyzer/lib/src/generated/element_handle.dart b/pkg/analyzer/lib/src/generated/element_handle.dart
index d732ff4..01abf05 100644
--- a/pkg/analyzer/lib/src/generated/element_handle.dart
+++ b/pkg/analyzer/lib/src/generated/element_handle.dart
@@ -260,9 +260,15 @@
ElementKind get kind => ElementKind.CONSTRUCTOR;
@override
+ int get nameEnd => actualElement.nameEnd;
+
+ @override
ConstructorDeclaration get node => actualElement.node;
@override
+ int get periodOffset => actualElement.periodOffset;
+
+ @override
ConstructorElement get redirectedConstructor =>
actualElement.redirectedConstructor;
}
@@ -581,13 +587,13 @@
ClassElement get enclosingElement => actualElement.enclosingElement;
@override
+ bool get isEnumConstant => actualElement.isEnumConstant;
+
+ @override
bool get isStatic => actualElement.isStatic;
@override
ElementKind get kind => ElementKind.FIELD;
-
- @override
- bool get isEnumConstant => actualElement.isEnumConstant;
}
/**
diff --git a/pkg/analyzer/lib/src/generated/element_resolver.dart b/pkg/analyzer/lib/src/generated/element_resolver.dart
index 9ecb232..833406f 100644
--- a/pkg/analyzer/lib/src/generated/element_resolver.dart
+++ b/pkg/analyzer/lib/src/generated/element_resolver.dart
@@ -2493,22 +2493,22 @@
}
/**
- * Given an invocation of the form 'C.x()' where 'C' is a class, find and return the element 'x'
- * in 'C'.
- *
- * @param classElement the class element
- * @param nameNode the member name node
+ * Given that we are accessing a property of the given [classElement] with
+ * the given [propertyName], return the element that represents the property.
*/
Element _resolveElement(ClassElementImpl classElement,
- SimpleIdentifier nameNode) {
- String name = nameNode.name;
- Element element = classElement.getMethod(name);
- if (element == null && nameNode.inSetterContext()) {
+ SimpleIdentifier propertyName) {
+ String name = propertyName.name;
+ Element element = null;
+ if (propertyName.inSetterContext()) {
element = classElement.getSetter(name);
}
- if (element == null && nameNode.inGetterContext()) {
+ if (element == null) {
element = classElement.getGetter(name);
}
+ if (element == null) {
+ element = classElement.getMethod(name);
+ }
if (element != null && element.isAccessibleIn(_definingLibrary)) {
return element;
}
diff --git a/pkg/analyzer/lib/src/generated/engine.dart b/pkg/analyzer/lib/src/generated/engine.dart
index 9898b75..7ca2b2a 100644
--- a/pkg/analyzer/lib/src/generated/engine.dart
+++ b/pkg/analyzer/lib/src/generated/engine.dart
@@ -1066,6 +1066,12 @@
*/
CompilationUnit incrementalResolutionValidation_lastUnit;
+ /** A factory to override how [ResolverVisitor] is created. */
+ ResolverVisitorFactory resolverVisitorFactory;
+
+ /** A factory to override how [TypeResolverVisitor] is created. */
+ TypeResolverVisitorFactory typeResolverVisitorFactory;
+
/**
* Initialize a newly created analysis context.
*/
@@ -1537,11 +1543,8 @@
//
// Then determine which cached results are no longer valid.
//
- bool addedDartSource = false;
for (Source source in changeSet.addedSources) {
- if (_sourceAvailable(source)) {
- addedDartSource = true;
- }
+ _sourceAvailable(source);
}
for (Source source in changeSet.changedSources) {
if (_contentCache.getContents(source) != null) {
@@ -1570,36 +1573,6 @@
for (Source source in removedSources) {
_sourceRemoved(source);
}
- if (addedDartSource) {
- // TODO(brianwilkerson) This is hugely inefficient, but we need to
- // re-analyze any libraries that might have been referencing the
- // not-yet-existing source that was just added. Longer term we need to
- // keep track of which libraries are referencing non-existing sources and
- // only re-analyze those libraries.
-// logInformation("Added Dart sources, invalidating all resolution information");
- List<Source> sourcesToInvalidate = new List<Source>();
- MapIterator<Source, SourceEntry> iterator = _cache.iterator();
- while (iterator.moveNext()) {
- Source source = iterator.key;
- SourceEntry sourceEntry = iterator.value;
- if (!source.isInSystemLibrary &&
- (sourceEntry is DartEntry || sourceEntry is HtmlEntry)) {
- sourcesToInvalidate.add(source);
- }
- }
- int count = sourcesToInvalidate.length;
- for (int i = 0; i < count; i++) {
- Source source = sourcesToInvalidate[i];
- SourceEntry entry = _getReadableSourceEntry(source);
- if (entry is DartEntry) {
- entry.invalidateParseInformation();
- _workManager.add(source, _computePriority(entry));
- } else if (entry is HtmlEntry) {
- entry.invalidateParseInformation();
- _workManager.add(source, SourcePriority.HTML);
- }
- }
- }
_onSourcesChangedController.add(new SourcesChangedEvent(changeSet));
}
@@ -2315,71 +2288,74 @@
if (_TRACE_PERFORM_TASK) {
print("----------------------------------------");
}
- int getStart = JavaSystem.currentTimeMillis();
- AnalysisTask task = nextAnalysisTask;
- int getEnd = JavaSystem.currentTimeMillis();
- if (task == null && _validateCacheConsistency()) {
- task = nextAnalysisTask;
- }
- if (task == null) {
- _validateLastIncrementalResolutionResult();
- if (_performAnalysisTaskStopwatch != null) {
- AnalysisEngine.instance.instrumentationService.logPerformance(
- AnalysisPerformanceKind.FULL,
- _performAnalysisTaskStopwatch,
- 'context_id=$_id');
- _performAnalysisTaskStopwatch = null;
+ return PerformanceStatistics.performAnaysis.makeCurrentWhile(() {
+ int getStart = JavaSystem.currentTimeMillis();
+ AnalysisTask task =
+ PerformanceStatistics.nextTask.makeCurrentWhile(() => nextAnalysisTask);
+ int getEnd = JavaSystem.currentTimeMillis();
+ if (task == null && _validateCacheConsistency()) {
+ task = nextAnalysisTask;
+ }
+ if (task == null) {
+ _validateLastIncrementalResolutionResult();
+ if (_performAnalysisTaskStopwatch != null) {
+ AnalysisEngine.instance.instrumentationService.logPerformance(
+ AnalysisPerformanceKind.FULL,
+ _performAnalysisTaskStopwatch,
+ 'context_id=$_id');
+ _performAnalysisTaskStopwatch = null;
+ }
+ return new AnalysisResult(
+ _getChangeNotices(true),
+ getEnd - getStart,
+ null,
+ -1);
+ }
+ if (_performAnalysisTaskStopwatch == null) {
+ _performAnalysisTaskStopwatch = new Stopwatch()..start();
+ }
+ String taskDescription = task.toString();
+ _notifyAboutToPerformTask(taskDescription);
+ if (_TRACE_PERFORM_TASK) {
+ print(taskDescription);
+ }
+ int performStart = JavaSystem.currentTimeMillis();
+ try {
+ task.perform(_resultRecorder);
+ } on ObsoleteSourceAnalysisException catch (exception, stackTrace) {
+ AnalysisEngine.instance.logger.logInformation(
+ "Could not perform analysis task: $taskDescription",
+ new CaughtException(exception, stackTrace));
+ } on AnalysisException catch (exception, stackTrace) {
+ if (exception.cause is! JavaIOException) {
+ AnalysisEngine.instance.logger.logError(
+ "Internal error while performing the task: $task",
+ new CaughtException(exception, stackTrace));
+ }
+ }
+ int performEnd = JavaSystem.currentTimeMillis();
+ List<ChangeNotice> notices = _getChangeNotices(false);
+ int noticeCount = notices.length;
+ for (int i = 0; i < noticeCount; i++) {
+ ChangeNotice notice = notices[i];
+ Source source = notice.source;
+ // TODO(brianwilkerson) Figure out whether the compilation unit is
+ // always resolved, or whether we need to decide whether to invoke the
+ // "parsed" or "resolved" method. This might be better done when
+ // recording task results in order to reduce the chance of errors.
+// if (notice.getCompilationUnit() != null) {
+// notifyResolvedDart(source, notice.getCompilationUnit());
+// } else if (notice.getHtmlUnit() != null) {
+// notifyResolvedHtml(source, notice.getHtmlUnit());
+// }
+ _notifyErrors(source, notice.errors, notice.lineInfo);
}
return new AnalysisResult(
- _getChangeNotices(true),
+ notices,
getEnd - getStart,
- null,
- -1);
- }
- if (_performAnalysisTaskStopwatch == null) {
- _performAnalysisTaskStopwatch = new Stopwatch()..start();
- }
- String taskDescription = task.toString();
- _notifyAboutToPerformTask(taskDescription);
- if (_TRACE_PERFORM_TASK) {
- print(taskDescription);
- }
- int performStart = JavaSystem.currentTimeMillis();
- try {
- task.perform(_resultRecorder);
- } on ObsoleteSourceAnalysisException catch (exception, stackTrace) {
- AnalysisEngine.instance.logger.logInformation(
- "Could not perform analysis task: $taskDescription",
- new CaughtException(exception, stackTrace));
- } on AnalysisException catch (exception, stackTrace) {
- if (exception.cause is! JavaIOException) {
- AnalysisEngine.instance.logger.logError(
- "Internal error while performing the task: $task",
- new CaughtException(exception, stackTrace));
- }
- }
- int performEnd = JavaSystem.currentTimeMillis();
- List<ChangeNotice> notices = _getChangeNotices(false);
- int noticeCount = notices.length;
- for (int i = 0; i < noticeCount; i++) {
- ChangeNotice notice = notices[i];
- Source source = notice.source;
- // TODO(brianwilkerson) Figure out whether the compilation unit is always
- // resolved, or whether we need to decide whether to invoke the "parsed"
- // or "resolved" method. This might be better done when recording task
- // results in order to reduce the chance of errors.
- // if (notice.getCompilationUnit() != null) {
- // notifyResolvedDart(source, notice.getCompilationUnit());
- // } else if (notice.getHtmlUnit() != null) {
- // notifyResolvedHtml(source, notice.getHtmlUnit());
- // }
- _notifyErrors(source, notice.errors, notice.lineInfo);
- }
- return new AnalysisResult(
- notices,
- getEnd - getStart,
- task.runtimeType.toString(),
- performEnd - performStart);
+ task.runtimeType.toString(),
+ performEnd - performStart);
+ });
}
@override
@@ -3335,10 +3311,6 @@
return new AnalysisContextImpl_TaskData(null, false);
}
LibraryElement libraryElement = libraryEntry.getValue(DartEntry.ELEMENT);
- unitEntry.setStateInLibrary(
- DartEntry.VERIFICATION_ERRORS,
- librarySource,
- CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new GenerateDartErrorsTask(this, unitSource, unit, libraryElement),
false);
@@ -3379,10 +3351,6 @@
return _createResolveDartLibraryTask(librarySource, libraryEntry);
}
}
- dartEntry.setStateInLibrary(
- DartEntry.HINTS,
- librarySource,
- CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new GenerateDartHintsTask(this, units, libraryElement),
false);
@@ -3423,10 +3391,6 @@
return _createResolveDartLibraryTask(librarySource, libraryEntry);
}
}
- dartEntry.setStateInLibrary(
- DartEntry.LINTS,
- librarySource,
- CacheState.IN_PROCESS);
//TODO(pquitslund): revisit if we need all units or whether one will do
return new AnalysisContextImpl_TaskData(
new GenerateDartLintsTask(this, units, libraryElement),
@@ -3442,7 +3406,6 @@
*/
AnalysisContextImpl_TaskData _createGetContentTask(Source source,
SourceEntry sourceEntry) {
- sourceEntry.setState(SourceEntry.CONTENT, CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new GetContentTask(this, source),
false);
@@ -3459,7 +3422,6 @@
}
Token tokenStream = dartEntry.getValue(DartEntry.TOKEN_STREAM);
dartEntry.setState(DartEntry.TOKEN_STREAM, CacheState.FLUSHED);
- dartEntry.setState(DartEntry.PARSE_ERRORS, CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new ParseDartTask(
this,
@@ -3479,7 +3441,6 @@
}
String content = htmlEntry.getValue(SourceEntry.CONTENT);
htmlEntry.setState(SourceEntry.CONTENT, CacheState.FLUSHED);
- htmlEntry.setState(HtmlEntry.PARSE_ERRORS, CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new ParseHtmlTask(this, source, content),
false);
@@ -3497,7 +3458,9 @@
try {
AnalysisContextImpl_CycleBuilder builder =
new AnalysisContextImpl_CycleBuilder(this);
- builder.computeCycleContaining(source);
+ PerformanceStatistics.cycles.makeCurrentWhile(() {
+ builder.computeCycleContaining(source);
+ });
AnalysisContextImpl_TaskData taskData = builder.taskData;
if (taskData != null) {
return taskData;
@@ -3528,7 +3491,6 @@
if (htmlEntry.getState(HtmlEntry.PARSED_UNIT) != CacheState.VALID) {
return _createParseHtmlTask(source, htmlEntry);
}
- htmlEntry.setState(HtmlEntry.RESOLVED_UNIT, CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new ResolveHtmlTask(
this,
@@ -3553,7 +3515,6 @@
}
String content = dartEntry.getValue(SourceEntry.CONTENT);
dartEntry.setState(SourceEntry.CONTENT, CacheState.FLUSHED);
- dartEntry.setState(DartEntry.SCAN_ERRORS, CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new ScanDartTask(this, source, content),
false);
@@ -3994,7 +3955,6 @@
if (elementState == CacheState.INVALID ||
(isPriority && elementState == CacheState.FLUSHED)) {
// return createResolveDartLibraryTask(librarySource, (DartEntry) libraryEntry);
- libraryEntry.setState(DartEntry.ELEMENT, CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new ResolveDartLibraryTask(this, source, librarySource),
false);
@@ -4016,10 +3976,6 @@
// }
// Possibly replace with:
// return createResolveDartLibraryTask(librarySource, (DartEntry) libraryEntry);
- dartEntry.setStateInLibrary(
- DartEntry.RESOLVED_UNIT,
- librarySource,
- CacheState.IN_PROCESS);
return new AnalysisContextImpl_TaskData(
new ResolveDartLibraryTask(this, source, librarySource),
false);
@@ -4441,27 +4397,46 @@
}
/**
- * Record the results produced by performing a [task] and return the cache
- * entry associated with the results.
+ * Given that the given [source] (with the corresponding [sourceEntry]) has
+ * been invalidated, invalidate all of the libraries that depend on it.
*/
- DartEntry _recordBuildUnitElementTask(BuildUnitElementTask task) {
- Source source = task.source;
- Source library = task.library;
- DartEntry dartEntry = _cache.get(source);
- CaughtException thrownException = task.exception;
- if (thrownException != null) {
- dartEntry.recordBuildElementErrorInLibrary(library, thrownException);
- throw new AnalysisException('<rethrow>', thrownException);
+ void _propagateInvalidation(Source source, SourceEntry sourceEntry) {
+ if (sourceEntry is HtmlEntry) {
+ HtmlEntry htmlEntry = sourceEntry;
+ htmlEntry.modificationTime = getModificationStamp(source);
+ htmlEntry.invalidateAllInformation();
+ _cache.removedAst(source);
+ _workManager.add(source, SourcePriority.HTML);
+ } else if (sourceEntry is DartEntry) {
+ List<Source> containingLibraries = getLibrariesContaining(source);
+ List<Source> dependentLibraries = getLibrariesDependingOn(source);
+ HashSet<Source> librariesToInvalidate = new HashSet<Source>();
+ for (Source containingLibrary in containingLibraries) {
+ _computeAllLibrariesDependingOn(
+ containingLibrary,
+ librariesToInvalidate);
+ }
+ for (Source dependentLibrary in dependentLibraries) {
+ _computeAllLibrariesDependingOn(
+ dependentLibrary,
+ librariesToInvalidate);
+ }
+ for (Source library in librariesToInvalidate) {
+ _invalidateLibraryResolution(library);
+ }
+ DartEntry dartEntry = _cache.get(source);
+ _removeFromParts(source, dartEntry);
+ dartEntry.modificationTime = getModificationStamp(source);
+ dartEntry.invalidateAllInformation();
+ _cache.removedAst(source);
+ _workManager.add(source, SourcePriority.UNKNOWN);
}
- dartEntry.setValueInLibrary(DartEntry.BUILT_UNIT, library, task.unit);
- dartEntry.setValueInLibrary(
- DartEntry.BUILT_ELEMENT,
- library,
- task.unitElement);
- ChangeNoticeImpl notice = _getNotice(source);
- LineInfo lineInfo = dartEntry.getValue(SourceEntry.LINE_INFO);
- notice.setErrors(dartEntry.allErrors, lineInfo);
- return dartEntry;
+ // reset unit in the notification, it is out of date now
+ ChangeNoticeImpl notice = _pendingNotices[source];
+ if (notice != null) {
+ notice.resolvedDartUnit = null;
+ notice.resolvedHtmlUnit = null;
+ }
}
// /**
@@ -4543,6 +4518,30 @@
// }
/**
+ * Record the results produced by performing a [task] and return the cache
+ * entry associated with the results.
+ */
+ DartEntry _recordBuildUnitElementTask(BuildUnitElementTask task) {
+ Source source = task.source;
+ Source library = task.library;
+ DartEntry dartEntry = _cache.get(source);
+ CaughtException thrownException = task.exception;
+ if (thrownException != null) {
+ dartEntry.recordBuildElementErrorInLibrary(library, thrownException);
+ throw new AnalysisException('<rethrow>', thrownException);
+ }
+ dartEntry.setValueInLibrary(DartEntry.BUILT_UNIT, library, task.unit);
+ dartEntry.setValueInLibrary(
+ DartEntry.BUILT_ELEMENT,
+ library,
+ task.unitElement);
+ ChangeNoticeImpl notice = _getNotice(source);
+ LineInfo lineInfo = dartEntry.getValue(SourceEntry.LINE_INFO);
+ notice.setErrors(dartEntry.allErrors, lineInfo);
+ return dartEntry;
+ }
+
+ /**
* Given a cache entry and a library element, record the library element and other information
* gleaned from the element in the cache entry.
*
@@ -4948,20 +4947,18 @@
}
/**
- * Create an entry for the newly added source. Return `true` if the new source is a Dart
- * file.
+ * Create an entry for the newly added [source] and invalidate any sources
+ * that referenced the source before it existed.
*
- * <b>Note:</b> This method must only be invoked while we are synchronized on [cacheLock].
- *
- * @param source the source that has been added
- * @return `true` if the new source is a Dart file
+ * <b>Note:</b> This method must only be invoked while we are synchronized on
+ * [cacheLock].
*/
- bool _sourceAvailable(Source source) {
+ void _sourceAvailable(Source source) {
SourceEntry sourceEntry = _cache.get(source);
if (sourceEntry == null) {
sourceEntry = _createSourceEntry(source, true);
} else {
- _sourceChanged(source);
+ _propagateInvalidation(source, sourceEntry);
sourceEntry = _cache.get(source);
}
if (sourceEntry is HtmlEntry) {
@@ -4969,13 +4966,14 @@
} else if (sourceEntry is DartEntry) {
_workManager.add(source, _computePriority(sourceEntry as DartEntry));
}
- return sourceEntry is DartEntry;
}
/**
- * <b>Note:</b> This method must only be invoked while we are synchronized on [cacheLock].
+ * Invalidate the [source] that was changed and any sources that referenced
+ * the source before it existed.
*
- * @param source the source that has been changed
+ * <b>Note:</b> This method must only be invoked while we are synchronized on
+ * [cacheLock].
*/
void _sourceChanged(Source source) {
SourceEntry sourceEntry = _cache.get(source);
@@ -4986,36 +4984,7 @@
// to invalidate it again.
return;
}
- if (sourceEntry is HtmlEntry) {
- HtmlEntry htmlEntry = sourceEntry;
- htmlEntry.modificationTime = getModificationStamp(source);
- htmlEntry.invalidateAllInformation();
- _cache.removedAst(source);
- _workManager.add(source, SourcePriority.HTML);
- } else if (sourceEntry is DartEntry) {
- List<Source> containingLibraries = getLibrariesContaining(source);
- HashSet<Source> librariesToInvalidate = new HashSet<Source>();
- for (Source containingLibrary in containingLibraries) {
- _computeAllLibrariesDependingOn(
- containingLibrary,
- librariesToInvalidate);
- }
- for (Source library in librariesToInvalidate) {
- _invalidateLibraryResolution(library);
- }
- DartEntry dartEntry = _cache.get(source);
- _removeFromParts(source, dartEntry);
- dartEntry.modificationTime = getModificationStamp(source);
- dartEntry.invalidateAllInformation();
- _cache.removedAst(source);
- _workManager.add(source, SourcePriority.UNKNOWN);
- }
- // reset unit in the notification, it is out of date now
- ChangeNoticeImpl notice = _pendingNotices[source];
- if (notice != null) {
- notice.resolvedDartUnit = null;
- notice.resolvedHtmlUnit = null;
- }
+ _propagateInvalidation(source, sourceEntry);
}
/**
@@ -5083,64 +5052,66 @@
* TODO(scheglov) A hackish, limited incremental resolution implementation.
*/
bool _tryPoorMansIncrementalResolution(Source unitSource, String newCode) {
- incrementalResolutionValidation_lastUnitSource = null;
- incrementalResolutionValidation_lastLibrarySource = null;
- incrementalResolutionValidation_lastUnit = null;
- // prepare the entry
- DartEntry dartEntry = _cache.get(unitSource);
- if (dartEntry == null) {
- return false;
- }
- // prepare the (only) library source
- List<Source> librarySources = getLibrariesContaining(unitSource);
- if (librarySources.length != 1) {
- return false;
- }
- Source librarySource = librarySources[0];
- // prepare the library element
- LibraryElement libraryElement = getLibraryElement(librarySource);
- if (libraryElement == null) {
- return false;
- }
- // prepare the existing unit
- CompilationUnit oldUnit =
- getResolvedCompilationUnit2(unitSource, librarySource);
- if (oldUnit == null) {
- return false;
- }
- // do resolution
- Stopwatch perfCounter = new Stopwatch()..start();
- PoorMansIncrementalResolver resolver = new PoorMansIncrementalResolver(
- typeProvider,
- unitSource,
- dartEntry,
- oldUnit,
- analysisOptions.incrementalApi);
- bool success = resolver.resolve(newCode);
- AnalysisEngine.instance.instrumentationService.logPerformance(
- AnalysisPerformanceKind.INCREMENTAL,
- perfCounter,
- 'success=$success,context_id=$_id,code_length=${newCode.length}');
- if (!success) {
- return false;
- }
- // if validation, remember the result, but throw it away
- if (analysisOptions.incrementalValidation) {
- incrementalResolutionValidation_lastUnitSource = oldUnit.element.source;
- incrementalResolutionValidation_lastLibrarySource =
- oldUnit.element.library.source;
- incrementalResolutionValidation_lastUnit = oldUnit;
- return false;
- }
- // prepare notice
- {
- LineInfo lineInfo = getLineInfo(unitSource);
- ChangeNoticeImpl notice = _getNotice(unitSource);
- notice.resolvedDartUnit = oldUnit;
- notice.setErrors(dartEntry.allErrors, lineInfo);
- }
- // OK
- return true;
+ return PerformanceStatistics.incrementalAnalysis.makeCurrentWhile(() {
+ incrementalResolutionValidation_lastUnitSource = null;
+ incrementalResolutionValidation_lastLibrarySource = null;
+ incrementalResolutionValidation_lastUnit = null;
+ // prepare the entry
+ DartEntry dartEntry = _cache.get(unitSource);
+ if (dartEntry == null) {
+ return false;
+ }
+ // prepare the (only) library source
+ List<Source> librarySources = getLibrariesContaining(unitSource);
+ if (librarySources.length != 1) {
+ return false;
+ }
+ Source librarySource = librarySources[0];
+ // prepare the library element
+ LibraryElement libraryElement = getLibraryElement(librarySource);
+ if (libraryElement == null) {
+ return false;
+ }
+ // prepare the existing unit
+ CompilationUnit oldUnit =
+ getResolvedCompilationUnit2(unitSource, librarySource);
+ if (oldUnit == null) {
+ return false;
+ }
+ // do resolution
+ Stopwatch perfCounter = new Stopwatch()..start();
+ PoorMansIncrementalResolver resolver = new PoorMansIncrementalResolver(
+ typeProvider,
+ unitSource,
+ dartEntry,
+ oldUnit,
+ analysisOptions.incrementalApi);
+ bool success = resolver.resolve(newCode);
+ AnalysisEngine.instance.instrumentationService.logPerformance(
+ AnalysisPerformanceKind.INCREMENTAL,
+ perfCounter,
+ 'success=$success,context_id=$_id,code_length=${newCode.length}');
+ if (!success) {
+ return false;
+ }
+ // if validation, remember the result, but throw it away
+ if (analysisOptions.incrementalValidation) {
+ incrementalResolutionValidation_lastUnitSource = oldUnit.element.source;
+ incrementalResolutionValidation_lastLibrarySource =
+ oldUnit.element.library.source;
+ incrementalResolutionValidation_lastUnit = oldUnit;
+ return false;
+ }
+ // prepare notice
+ {
+ LineInfo lineInfo = getLineInfo(unitSource);
+ ChangeNoticeImpl notice = _getNotice(unitSource);
+ notice.resolvedDartUnit = oldUnit;
+ notice.setErrors(dartEntry.allErrors, lineInfo);
+ }
+ // OK
+ return true;
+ });
}
/**
@@ -6852,7 +6823,8 @@
"Task failed: $taskDescription",
new CaughtException(exception, stackTrace));
}
- return accept(visitor);
+ return PerformanceStatistics.analysisTaskVisitor.makeCurrentWhile(
+ () => accept(visitor));
}
@override
@@ -6868,7 +6840,7 @@
try {
internalPerform();
} on AnalysisException catch (exception) {
- throw exception;
+ rethrow;
} catch (exception, stackTrace) {
throw new AnalysisException(
exception.toString(),
@@ -7251,30 +7223,35 @@
}
/**
- * The enumeration `CacheState` defines the possible states of cached data.
+ * The possible states of cached data.
*/
class CacheState extends Enum<CacheState> {
/**
- * The data is not in the cache and the last time an attempt was made to compute the data an
- * exception occurred, making it pointless to attempt.
+ * The data is not in the cache and the last time an attempt was made to
+ * compute the data an exception occurred, making it pointless to attempt to
+ * compute the data again.
*
* Valid Transitions:
- * * [INVALID] if a source was modified that might cause the data to be computable
+ * * [INVALID] if a source was modified that might cause the data to be
+ * computable
*/
static const CacheState ERROR = const CacheState('ERROR', 0);
/**
- * The data is not in the cache because it was flushed from the cache in order to control memory
- * usage. If the data is recomputed, results do not need to be reported.
+ * The data is not in the cache because it was flushed from the cache in order
+ * to control memory usage. If the data is recomputed, results do not need to
+ * be reported.
*
* Valid Transitions:
* * [IN_PROCESS] if the data is being recomputed
- * * [INVALID] if a source was modified that causes the data to need to be recomputed
+ * * [INVALID] if a source was modified that causes the data to need to be
+ * recomputed
*/
static const CacheState FLUSHED = const CacheState('FLUSHED', 1);
/**
- * The data might or might not be in the cache but is in the process of being recomputed.
+ * The data might or might not be in the cache but is in the process of being
+ * recomputed.
*
* Valid Transitions:
* * [ERROR] if an exception occurred while trying to compute the data
@@ -7283,7 +7260,8 @@
static const CacheState IN_PROCESS = const CacheState('IN_PROCESS', 2);
/**
- * The data is not in the cache and needs to be recomputed so that results can be reported.
+ * The data is not in the cache and needs to be recomputed so that results can
+ * be reported.
*
* Valid Transitions:
* * [IN_PROCESS] if an attempt is being made to recompute the data
@@ -7295,7 +7273,8 @@
*
* Valid Transitions:
* * [FLUSHED] if the data is removed in order to manage memory usage
- * * [INVALID] if a source was modified in such a way as to invalidate the previous data
+ * * [INVALID] if a source was modified in such a way as to invalidate the
+ * previous data
*/
static const CacheState VALID = const CacheState('VALID', 4);
@@ -8693,6 +8672,16 @@
*/
class DataDescriptor<E> {
/**
+ * The next artificial hash code.
+ */
+ static int _NEXT_HASH_CODE = 0;
+
+ /**
+ * The artifitial hash code for this object.
+ */
+ final int _hashCode = _NEXT_HASH_CODE++;
+
+ /**
* The name of the descriptor, used for debugging purposes.
*/
final String _name;
@@ -8709,6 +8698,9 @@
DataDescriptor(this._name, [this.defaultValue = null]);
@override
+ int get hashCode => _hashCode;
+
+ @override
String toString() => _name;
}
@@ -8802,9 +8794,7 @@
@override
void internalPerform() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.errors.start();
- try {
+ PerformanceStatistics.errors.makeCurrentWhile(() {
RecordingErrorListener errorListener = new RecordingErrorListener();
ErrorReporter errorReporter = new ErrorReporter(errorListener, source);
TypeProvider typeProvider = context.typeProvider;
@@ -8833,9 +8823,7 @@
new InheritanceManager(libraryElement));
_unit.accept(errorVerifier);
_errors = errorListener.getErrorsForSource(source);
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -9729,6 +9717,12 @@
*/
TypeProvider get typeProvider;
+ /** A factory to override how [ResolverVisitor] is created. */
+ ResolverVisitorFactory get resolverVisitorFactory;
+
+ /** A factory to override how [TypeResolverVisitor] is created. */
+ TypeResolverVisitorFactory get typeResolverVisitorFactory;
+
/**
* Add the given source with the given information to this context.
*
@@ -10066,9 +10060,7 @@
//
// Then parse the token stream.
//
- TimeCounter_TimeCounterHandle timeCounterParse =
- PerformanceStatistics.parse.start();
- try {
+ PerformanceStatistics.parse.makeCurrentWhile(() {
RecordingErrorListener errorListener = new RecordingErrorListener();
Parser parser = new Parser(source, errorListener);
AnalysisOptions options = context.analysisOptions;
@@ -10102,9 +10094,7 @@
}
}
_errors = errorListener.getErrorsForSource(source);
- } finally {
- timeCounterParse.stop();
- }
+ });
}
/**
@@ -10490,52 +10480,69 @@
*/
class PerformanceStatistics {
/**
- * The [TimeCounter] for time spent in reading files.
+ * The [PerformanceTag] for time spent in reading files.
*/
- static TimeCounter io = new TimeCounter();
+ static PerformanceTag io = new PerformanceTag('io');
/**
- * The [TimeCounter] for time spent in scanning.
+ * The [PerformanceTag] for time spent in scanning.
*/
- static TimeCounter scan = new TimeCounter();
+ static PerformanceTag scan = new PerformanceTag('scan');
/**
- * The [TimeCounter] for time spent in parsing.
+ * The [PerformanceTag] for time spent in parsing.
*/
- static TimeCounter parse = new TimeCounter();
+ static PerformanceTag parse = new PerformanceTag('parse');
/**
- * The [TimeCounter] for time spent in resolving.
+ * The [PerformanceTag] for time spent in resolving.
*/
- static TimeCounter resolve = new TimeCounter();
+ static PerformanceTag resolve = new PerformanceTag('resolve');
/**
- * The [TimeCounter] for time spent in error verifier.
+ * The [PerformanceTag] for time spent in error verifier.
*/
- static TimeCounter errors = new TimeCounter();
+ static PerformanceTag errors = new PerformanceTag('errors');
/**
- * The [TimeCounter] for time spent in hints generator.
+ * The [PerformanceTag] for time spent in hints generator.
*/
- static TimeCounter hints = new TimeCounter();
+ static PerformanceTag hints = new PerformanceTag('hints');
/**
- * The [TimeCounter] for time spent in linting.
+ * The [PerformanceTag] for time spent in linting.
*/
- static TimeCounter lint = new TimeCounter();
+ static PerformanceTag lint = new PerformanceTag('lint');
/**
- * Reset all of the time counters to zero.
+ * The [PerformanceTag] for time spent computing cycles.
*/
- static void reset() {
- io = new TimeCounter();
- scan = new TimeCounter();
- parse = new TimeCounter();
- resolve = new TimeCounter();
- errors = new TimeCounter();
- hints = new TimeCounter();
- lint = new TimeCounter();
- }
+ static PerformanceTag cycles = new PerformanceTag('cycles');
+
+ /**
+ * The [PerformanceTag] for time spent in other phases of analysis.
+ */
+ static PerformanceTag performAnaysis = new PerformanceTag('performAnaysis');
+
+ /**
+ * The [PerformanceTag] for time spent in the analysis task visitor after
+ * tasks are complete.
+ */
+ static PerformanceTag analysisTaskVisitor =
+ new PerformanceTag('analysisTaskVisitor');
+
+ /**
+ * The [PerformanceTag] for time spent in the getter
+ * AnalysisContextImpl.nextAnalysisTask.
+ */
+ static var nextTask = new PerformanceTag('nextAnalysisTask');
+
+ /**
+ * The [PerformanceTag] for time spent during otherwise not accounted parts
+ * incremental of analysis.
+ */
+ static PerformanceTag incrementalAnalysis =
+ new PerformanceTag('incrementalAnalysis');
}
/**
@@ -11306,9 +11313,7 @@
//
// Perform additional error checking.
//
- TimeCounter_TimeCounterHandle counterHandleErrors =
- PerformanceStatistics.errors.start();
- try {
+ PerformanceStatistics.errors.makeCurrentWhile(() {
ErrorReporter errorReporter = new ErrorReporter(errorListener, source);
ErrorVerifier errorVerifier = new ErrorVerifier(
errorReporter,
@@ -11322,9 +11327,7 @@
// call to ConstantVerifier.
// ConstantVerifier constantVerifier = new ConstantVerifier(errorReporter, _libraryElement, typeProvider);
// unit.accept(constantVerifier);
- } finally {
- counterHandleErrors.stop();
- }
+ });
//
// Capture the results.
//
@@ -11552,23 +11555,21 @@
@override
void internalPerform() {
- RecordingErrorListener errorListener = new RecordingErrorListener();
- TimeCounter_TimeCounterHandle timeCounterScan =
- PerformanceStatistics.scan.start();
- try {
- Scanner scanner =
- new Scanner(source, new CharSequenceReader(_content), errorListener);
- scanner.preserveComments = context.analysisOptions.preserveComments;
- _tokenStream = scanner.tokenize();
- _lineInfo = new LineInfo(scanner.lineStarts);
- _errors = errorListener.getErrorsForSource(source);
- } catch (exception, stackTrace) {
- throw new AnalysisException(
- "Exception",
- new CaughtException(exception, stackTrace));
- } finally {
- timeCounterScan.stop();
- }
+ PerformanceStatistics.scan.makeCurrentWhile(() {
+ RecordingErrorListener errorListener = new RecordingErrorListener();
+ try {
+ Scanner scanner =
+ new Scanner(source, new CharSequenceReader(_content), errorListener);
+ scanner.preserveComments = context.analysisOptions.preserveComments;
+ _tokenStream = scanner.tokenize();
+ _lineInfo = new LineInfo(scanner.lineStarts);
+ _errors = errorListener.getErrorsForSource(source);
+ } catch (exception, stackTrace) {
+ throw new AnalysisException(
+ "Exception",
+ new CaughtException(exception, stackTrace));
+ }
+ });
}
}
diff --git a/pkg/analyzer/lib/src/generated/error.dart b/pkg/analyzer/lib/src/generated/error.dart
index 7801e2e..668fcf4 100644
--- a/pkg/analyzer/lib/src/generated/error.dart
+++ b/pkg/analyzer/lib/src/generated/error.dart
@@ -3806,7 +3806,9 @@
*/
static const StaticWarningCode AMBIGUOUS_IMPORT = const StaticWarningCode(
'AMBIGUOUS_IMPORT',
- "The name '{0}' is defined in the libraries {1}");
+ "The name '{0}' is defined in the libraries {1}",
+ "Consider using 'as prefix' for one of the import directives "
+ "or hiding the name from all but one of the imports.");
/**
* 12.11.1 New: It is a static warning if the static type of <i>a<sub>i</sub>,
diff --git a/pkg/analyzer/lib/src/generated/error_verifier.dart b/pkg/analyzer/lib/src/generated/error_verifier.dart
index 06026b3..bf32a2a 100644
--- a/pkg/analyzer/lib/src/generated/error_verifier.dart
+++ b/pkg/analyzer/lib/src/generated/error_verifier.dart
@@ -3813,12 +3813,8 @@
visitedClasses.add(superclassElement);
LibraryElement superclassLibrary = superclassElement.library;
// Check fields.
- List<FieldElement> fieldElts = superclassElement.fields;
- for (FieldElement fieldElt in fieldElts) {
- // We need the same name.
- if (fieldElt.name != executableElementName) {
- continue;
- }
+ FieldElement fieldElt = superclassElement.getField(executableElementName);
+ if (fieldElt != null) {
// Ignore if private in a different library - cannot collide.
if (executableElementPrivate &&
_currentLibrary != superclassLibrary) {
@@ -4587,16 +4583,14 @@
//
// Store in local sets the set of all method and accessor names
//
- List<MethodElement> methods = _enclosingClass.methods;
- for (MethodElement method in methods) {
- String methodName = method.name;
+ MethodElement method =
+ _enclosingClass.getMethod(FunctionElement.NO_SUCH_METHOD_METHOD_NAME);
+ if (method != null) {
// If the enclosing class declares the method noSuchMethod(), then return.
// From Spec: It is a static warning if a concrete class does not have an
// implementation for a method in any of its superinterfaces unless it
// declares its own noSuchMethod method (7.10).
- if (methodName == FunctionElement.NO_SUCH_METHOD_METHOD_NAME) {
- return false;
- }
+ return false;
}
HashSet<ExecutableElement> missingOverrides =
new HashSet<ExecutableElement>();
diff --git a/pkg/analyzer/lib/src/generated/java_engine.dart b/pkg/analyzer/lib/src/generated/java_engine.dart
index cd3f6bf..8a6bb5d 100644
--- a/pkg/analyzer/lib/src/generated/java_engine.dart
+++ b/pkg/analyzer/lib/src/generated/java_engine.dart
@@ -115,10 +115,6 @@
}
}
-class ObjectUtilities {
- static int combineHashCodes(int first, int second) => first * 31 + second;
-}
-
class StringUtilities {
static const String EMPTY = '';
diff --git a/pkg/analyzer/lib/src/generated/parser.dart b/pkg/analyzer/lib/src/generated/parser.dart
index 3787d75..ca76b3a 100644
--- a/pkg/analyzer/lib/src/generated/parser.dart
+++ b/pkg/analyzer/lib/src/generated/parser.dart
@@ -4095,6 +4095,24 @@
_injectToken(new StringToken(type, "", _currentToken.offset));
/**
+ * Create and return a new token with the given [type]. The token will replace
+ * the first portion of the given [token], so it will have the same offset and
+ * will have any comments that might have preceeded the token.
+ */
+ Token _createToken(Token token, TokenType type, {bool isBegin: false}) {
+ CommentToken comments = token.precedingComments;
+ if (comments == null) {
+ if (isBegin) {
+ return new BeginToken(type, token.offset);
+ }
+ return new Token(type, token.offset);
+ } else if (isBegin) {
+ return new BeginTokenWithComment(type, token.offset, comments);
+ }
+ return new TokenWithComment(type, token.offset, comments);
+ }
+
+ /**
* Check that the given expression is assignable and report an error if it isn't.
*
* <pre>
@@ -4592,18 +4610,16 @@
if (currentType == TokenType.GT) {
return true;
} else if (currentType == TokenType.GT_GT) {
- int offset = _currentToken.offset;
- Token first = new Token(TokenType.GT, offset);
- Token second = new Token(TokenType.GT, offset + 1);
+ Token first = _createToken(_currentToken, TokenType.GT);
+ Token second = new Token(TokenType.GT, _currentToken.offset + 1);
second.setNext(_currentToken.next);
first.setNext(second);
_currentToken.previous.setNext(first);
_currentToken = first;
return true;
} else if (currentType == TokenType.GT_EQ) {
- int offset = _currentToken.offset;
- Token first = new Token(TokenType.GT, offset);
- Token second = new Token(TokenType.EQ, offset + 1);
+ Token first = _createToken(_currentToken, TokenType.GT);
+ Token second = new Token(TokenType.EQ, _currentToken.offset + 1);
second.setNext(_currentToken.next);
first.setNext(second);
_currentToken.previous.setNext(first);
@@ -4611,7 +4627,7 @@
return true;
} else if (currentType == TokenType.GT_GT_EQ) {
int offset = _currentToken.offset;
- Token first = new Token(TokenType.GT, offset);
+ Token first = _createToken(_currentToken, TokenType.GT);
Token second = new Token(TokenType.GT, offset + 1);
Token third = new Token(TokenType.EQ, offset + 2);
third.setNext(_currentToken.next);
@@ -6085,7 +6101,9 @@
name = _createSyntheticIdentifier();
}
if (commentAndMetadata.metadata.isNotEmpty) {
- _reportErrorForNode(ParserErrorCode.ANNOTATION_ON_ENUM_CONSTANT, commentAndMetadata.metadata[0]);
+ _reportErrorForNode(
+ ParserErrorCode.ANNOTATION_ON_ENUM_CONSTANT,
+ commentAndMetadata.metadata[0]);
}
return new EnumConstantDeclaration(
commentAndMetadata.comment,
@@ -7056,7 +7074,7 @@
// may be empty list literal
if (_matches(TokenType.INDEX)) {
BeginToken leftBracket =
- new BeginToken(TokenType.OPEN_SQUARE_BRACKET, _currentToken.offset);
+ _createToken(_currentToken, TokenType.OPEN_SQUARE_BRACKET, isBegin: true);
Token rightBracket =
new Token(TokenType.CLOSE_SQUARE_BRACKET, _currentToken.offset + 1);
leftBracket.endToken = rightBracket;
@@ -8598,9 +8616,9 @@
// valid.
//
if (operator.type == TokenType.MINUS_MINUS) {
- int offset = operator.offset;
- Token firstOperator = new Token(TokenType.MINUS, offset);
- Token secondOperator = new Token(TokenType.MINUS, offset + 1);
+ Token firstOperator = _createToken(operator, TokenType.MINUS);
+ Token secondOperator =
+ new Token(TokenType.MINUS, operator.offset + 1);
secondOperator.setNext(_currentToken);
firstOperator.setNext(secondOperator);
operator.previous.setNext(firstOperator);
@@ -10018,9 +10036,10 @@
'ABSTRACT_TYPEDEF',
"Type aliases cannot be declared to be 'abstract'");
- static const ParserErrorCode ANNOTATION_ON_ENUM_CONSTANT = const ParserErrorCode(
- 'ANNOTATION_ON_ENUM_CONSTANT',
- "Enum constants cannot have annotations");
+ static const ParserErrorCode ANNOTATION_ON_ENUM_CONSTANT =
+ const ParserErrorCode(
+ 'ANNOTATION_ON_ENUM_CONSTANT',
+ "Enum constants cannot have annotations");
static const ParserErrorCode ASSERT_DOES_NOT_TAKE_ASSIGNMENT =
const ParserErrorCode(
diff --git a/pkg/analyzer/lib/src/generated/resolver.dart b/pkg/analyzer/lib/src/generated/resolver.dart
index f130d40..1a45e9b 100644
--- a/pkg/analyzer/lib/src/generated/resolver.dart
+++ b/pkg/analyzer/lib/src/generated/resolver.dart
@@ -36,6 +36,14 @@
typedef void ImplicitConstructorBuilderCallback(ClassElement classElement,
ClassElement superclassElement, void computation());
+typedef ResolverVisitor ResolverVisitorFactory(Library library, Source source,
+ TypeProvider typeProvider);
+
+typedef StaticTypeAnalyzer StaticTypeAnalyzerFactory(ResolverVisitor visitor);
+
+typedef TypeResolverVisitor TypeResolverVisitorFactory(Library library,
+ Source source, TypeProvider typeProvider);
+
typedef void VoidFunction();
/**
@@ -801,9 +809,7 @@
*/
CompilationUnitElementImpl buildCompilationUnit(Source source,
CompilationUnit unit) {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ return PerformanceStatistics.resolve.makeCurrentWhile(() {
if (unit == null) {
return null;
}
@@ -822,9 +828,7 @@
unit.element = element;
holder.validate();
return element;
- } finally {
- timeCounter.stop();
- }
+ });
}
}
@@ -2607,9 +2611,12 @@
Identifier returnType = node.returnType;
if (returnType != null) {
element.nameOffset = returnType.offset;
+ element.nameEnd = returnType.end;
}
} else {
constructorName.staticElement = element;
+ element.periodOffset = node.period.offset;
+ element.nameEnd = constructorName.end;
}
holder.validate();
return null;
@@ -3193,7 +3200,7 @@
getter.getter = true;
_currentHolder.addAccessor(getter);
variable.getter = getter;
- if (!isFinal) {
+ if (!isConst && !isFinal) {
PropertyAccessorElementImpl setter =
new PropertyAccessorElementImpl.forVariable(variable);
setter.setter = true;
@@ -4340,6 +4347,7 @@
}
}
+
/**
* Instances of the class `FunctionScope` implement the scope defined by a function.
*/
@@ -4461,9 +4469,7 @@
}
void generateForLibrary() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.hints.start();
- try {
+ PerformanceStatistics.hints.makeCurrentWhile(() {
for (int i = 0; i < _compilationUnits.length; i++) {
CompilationUnitElement element = _compilationUnits[i].element;
if (element != null) {
@@ -4484,9 +4490,7 @@
definingCompilationUnitErrorReporter);
_library.accept(
new _UnusedElementsVerifier(_errorListener, _usedElementsVisitor.usedElements));
- } finally {
- timeCounter.stop();
- }
+ });
}
void _generateForCompilationUnit(CompilationUnit unit, Source source) {
@@ -4512,7 +4516,6 @@
}
}
-
/**
* Instances of the class {@code HtmlTagInfo} record information about the tags used in an HTML
* file.
@@ -8223,18 +8226,14 @@
* @throws AnalysisException if any of the enum members could not be built
*/
void _buildEnumMembers() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
for (Library library in _librariesInCycles) {
for (Source source in library.compilationUnitSources) {
EnumMemberBuilder builder = new EnumMemberBuilder(_typeProvider);
library.getAST(source).accept(builder);
}
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -8244,9 +8243,7 @@
* @throws AnalysisException if any of the type hierarchies could not be resolved
*/
void _buildImplicitConstructors() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
ImplicitConstructorComputer computer =
new ImplicitConstructorComputer(_typeProvider);
for (Library library in _librariesInCycles) {
@@ -8259,9 +8256,7 @@
}
}
computer.compute();
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -8271,9 +8266,7 @@
* @throws AnalysisException if any of the function type aliases could not be resolved
*/
void _buildTypeAliases() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
List<LibraryResolver_TypeAliasInfo> typeAliases =
new List<LibraryResolver_TypeAliasInfo>();
for (Library library in _librariesInCycles) {
@@ -8294,9 +8287,7 @@
new TypeResolverVisitor.con1(info._library, info._source, _typeProvider);
info._typeAlias.accept(visitor);
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -8306,19 +8297,18 @@
* @throws AnalysisException if any of the type hierarchies could not be resolved
*/
void _buildTypeHierarchies() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
for (Library library in _librariesInCycles) {
for (Source source in library.compilationUnitSources) {
- TypeResolverVisitor visitor =
- new TypeResolverVisitor.con1(library, source, _typeProvider);
+ TypeResolverVisitorFactory typeResolverVisitorFactory =
+ analysisContext.typeResolverVisitorFactory;
+ TypeResolverVisitor visitor = (typeResolverVisitorFactory == null) ?
+ new TypeResolverVisitor.con1(library, source, _typeProvider) :
+ typeResolverVisitorFactory(library, source, _typeProvider);
library.getAST(source).accept(visitor);
}
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -8523,9 +8513,7 @@
* Compute a value for all of the constants in the libraries being analyzed.
*/
void _performConstantEvaluation() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
ConstantValueComputer computer =
new ConstantValueComputer(_typeProvider, analysisContext.declaredVariables);
for (Library library in _librariesInCycles) {
@@ -8562,9 +8550,7 @@
}
}
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -8587,20 +8573,19 @@
* the library cannot be analyzed
*/
void _resolveReferencesAndTypesInLibrary(Library library) {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
for (Source source in library.compilationUnitSources) {
CompilationUnit ast = library.getAST(source);
ast.accept(
new VariableResolverVisitor.con1(library, source, _typeProvider));
- ResolverVisitor visitor =
+ ResolverVisitorFactory visitorFactory =
+ analysisContext.resolverVisitorFactory;
+ ResolverVisitor visitor = visitorFactory != null ?
+ visitorFactory(library, source, _typeProvider) :
new ResolverVisitor.con1(library, source, _typeProvider);
ast.accept(visitor);
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -8958,18 +8943,14 @@
* @throws AnalysisException if any of the enum members could not be built
*/
void _buildEnumMembers() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
for (ResolvableLibrary library in _librariesInCycle) {
for (Source source in library.compilationUnitSources) {
EnumMemberBuilder builder = new EnumMemberBuilder(_typeProvider);
library.getAST(source).accept(builder);
}
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -8979,9 +8960,7 @@
* @throws AnalysisException if any of the type hierarchies could not be resolved
*/
void _buildImplicitConstructors() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
ImplicitConstructorComputer computer =
new ImplicitConstructorComputer(_typeProvider);
for (ResolvableLibrary library in _librariesInCycle) {
@@ -8997,9 +8976,7 @@
}
}
computer.compute();
- } finally {
- timeCounter.stop();
- }
+ });
}
HashMap<Source, ResolvableLibrary> _buildLibraryMap() {
@@ -9028,9 +9005,7 @@
* @throws AnalysisException if any of the function type aliases could not be resolved
*/
void _buildTypeAliases() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
List<LibraryResolver2_TypeAliasInfo> typeAliases =
new List<LibraryResolver2_TypeAliasInfo>();
for (ResolvableLibrary library in _librariesInCycle) {
@@ -9052,9 +9027,7 @@
new TypeResolverVisitor.con4(info._library, info._source, _typeProvider);
info._typeAlias.accept(visitor);
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -9064,9 +9037,7 @@
* @throws AnalysisException if any of the type hierarchies could not be resolved
*/
void _buildTypeHierarchies() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
for (ResolvableLibrary library in _librariesInCycle) {
for (ResolvableCompilationUnit unit in
library.resolvableCompilationUnits) {
@@ -9077,9 +9048,7 @@
ast.accept(visitor);
}
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -9101,9 +9070,7 @@
* Compute a value for all of the constants in the libraries being analyzed.
*/
void _performConstantEvaluation() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
ConstantValueComputer computer =
new ConstantValueComputer(_typeProvider, analysisContext.declaredVariables);
for (ResolvableLibrary library in _librariesInCycle) {
@@ -9129,9 +9096,7 @@
ast.accept(constantVerifier);
}
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -9154,9 +9119,7 @@
* the library cannot be analyzed
*/
void _resolveReferencesAndTypesInLibrary(ResolvableLibrary library) {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.resolve.start();
- try {
+ PerformanceStatistics.resolve.makeCurrentWhile(() {
for (ResolvableCompilationUnit unit in library.resolvableCompilationUnits)
{
Source source = unit.source;
@@ -9167,9 +9130,7 @@
new ResolverVisitor.con4(library, source, _typeProvider);
ast.accept(visitor);
}
- } finally {
- timeCounter.stop();
- }
+ });
}
/**
@@ -9196,6 +9157,7 @@
}
}
+
/**
* Instances of the class `TypeAliasInfo` hold information about a [TypeAlias].
*/
@@ -9318,7 +9280,6 @@
}
}
-
/**
* This class is used to replace uses of `HashMap<String, ExecutableElement>` which are not as
* performant as this class.
@@ -10080,6 +10041,33 @@
static List<ResolvableLibrary> _EMPTY_ARRAY = new List<ResolvableLibrary>(0);
/**
+<<<<<<< .working
+ * The next artificial hash code.
+ */
+ static int _NEXT_HASH_CODE = 0;
+
+ /**
+ * The artifitial hash code for this object.
+ */
+<<<<<<< .working
+ final int _hashCode = _nextHashCode();
+
+ /**
+=======
+ * The next artificial hash code.
+ */
+ static int _NEXT_HASH_CODE = 0;
+
+ /**
+ * The artifitial hash code for this object.
+ */
+ final int _hashCode = _NEXT_HASH_CODE++;
+=======
+ final int _hashCode = _nextHashCode();
+>>>>>>> .merge-right.r43886
+
+ /**
+>>>>>>> .merge-right.r43835
* The source specifying the defining compilation unit of this library.
*/
final Source librarySource;
@@ -10199,6 +10187,9 @@
*/
List<ResolvableLibrary> get exports => _exportedLibraries;
+ @override
+ int get hashCode => _hashCode;
+
/**
* Set the libraries that are imported into this library to be those in the given array.
*
@@ -10314,6 +10305,12 @@
@override
String toString() => librarySource.shortName;
+
+ static int _nextHashCode() {
+ int next = (_NEXT_HASH_CODE + 1) & 0xFFFFFF;
+ _NEXT_HASH_CODE = next;
+ return next;
+ }
}
/**
@@ -10433,13 +10430,19 @@
* @param typeProvider the object used to access the types from the core library
*/
ResolverVisitor.con1(Library library, Source source,
- TypeProvider typeProvider)
+ TypeProvider typeProvider, {StaticTypeAnalyzer typeAnalyzer,
+ StaticTypeAnalyzerFactory typeAnalyzerFactory})
: super.con1(library, source, typeProvider) {
this._inheritanceManager = library.inheritanceManager;
this._elementResolver = new ElementResolver(this);
- this._typeAnalyzer = new StaticTypeAnalyzer(this);
+ this._typeAnalyzer = typeAnalyzer != null ?
+ typeAnalyzer :
+ (typeAnalyzerFactory != null ?
+ typeAnalyzerFactory(this) :
+ new StaticTypeAnalyzer(this));
}
+
/**
* Initialize a newly created visitor to resolve the nodes in a compilation unit.
*
@@ -13941,11 +13944,21 @@
@override
Object visitClassDeclaration(ClassDeclaration node) {
+ _hasReferenceToSuper = false;
+ super.visitClassDeclaration(node);
+ ClassElementImpl classElement = _getClassElement(node.name);
+ if (classElement != null) {
+ classElement.hasReferenceToSuper = _hasReferenceToSuper;
+ }
+ return null;
+ }
+
+ @override
+ void visitClassDeclarationInScope(ClassDeclaration node) {
+ super.visitClassDeclarationInScope(node);
ExtendsClause extendsClause = node.extendsClause;
WithClause withClause = node.withClause;
ImplementsClause implementsClause = node.implementsClause;
- _hasReferenceToSuper = false;
- super.visitClassDeclaration(node);
ClassElementImpl classElement = _getClassElement(node.name);
InterfaceType superclassType = null;
if (extendsClause != null) {
@@ -13969,7 +13982,6 @@
}
}
classElement.supertype = superclassType;
- classElement.hasReferenceToSuper = _hasReferenceToSuper;
}
_resolve(classElement, withClause, implementsClause);
return null;
diff --git a/pkg/analyzer/lib/src/generated/source_io.dart b/pkg/analyzer/lib/src/generated/source_io.dart
index e0078d5..06211df 100644
--- a/pkg/analyzer/lib/src/generated/source_io.dart
+++ b/pkg/analyzer/lib/src/generated/source_io.dart
@@ -129,12 +129,9 @@
@override
TimestampedData<String> get contents {
- TimeCounter_TimeCounterHandle handle = PerformanceStatistics.io.start();
- try {
+ return PerformanceStatistics.io.makeCurrentWhile(() {
return contentsFromFile;
- } finally {
- _reportIfSlowIO(handle.stop());
- }
+ });
}
/**
@@ -197,7 +194,7 @@
@override
bool operator ==(Object object) =>
- object != null && object is FileBasedSource && file == object.file;
+ object is FileBasedSource && uri == object.uri;
@override
bool exists() => file.isFile();
@@ -235,23 +232,6 @@
}
return file.getAbsolutePath();
}
-
- /**
- * Record the time the IO took if it was slow
- */
- void _reportIfSlowIO(int nanos) {
- // TODO(brianwilkerson) Decide whether we still want to capture this data.
-// //If slower than 10ms
-// if (nanos > 10 * TimeCounter.NANOS_PER_MILLI) {
-// InstrumentationBuilder builder = Instrumentation.builder2("SlowIO");
-// try {
-// builder.data3("fileName", fullName);
-// builder.metric2("IO-Time-Nanos", nanos);
-// } finally {
-// builder.log();
-// }
-// }
- }
}
/**
diff --git a/pkg/analyzer/lib/src/generated/utilities_general.dart b/pkg/analyzer/lib/src/generated/utilities_general.dart
index 927f6d6..e62a781 100644
--- a/pkg/analyzer/lib/src/generated/utilities_general.dart
+++ b/pkg/analyzer/lib/src/generated/utilities_general.dart
@@ -7,64 +7,149 @@
library engine.utilities.general;
+import 'dart:profiler';
+
/**
- * Helper for measuring how much time is spent doing some operation.
+ * Jenkins hash function, optimized for small integers.
+ * Borrowed from sdk/lib/math/jenkins_smi_hash.dart.
*/
-class TimeCounter {
- static final int NANOS_PER_MILLI = 1000 * 1000;
- static final int NANOS_PER_MICRO = 1000;
- static TimeCounter _current = null;
- final Stopwatch _sw = new Stopwatch();
-
- /**
- * @return the number of milliseconds spent between [start] and [stop].
- */
- int get result => _sw.elapsedMilliseconds;
-
- /**
- * Starts counting time.
- *
- * @return the [TimeCounterHandle] that should be used to stop counting.
- */
- TimeCounter_TimeCounterHandle start() {
- return new TimeCounter_TimeCounterHandle(this);
+class JenkinsSmiHash {
+ static int combine(int hash, int value) {
+ hash = 0x1fffffff & (hash + value);
+ hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
+ return hash ^ (hash >> 6);
}
+
+ static int finish(int hash) {
+ hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
+ hash = hash ^ (hash >> 11);
+ return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
+ }
+
+ static int hash2(a, b) => finish(combine(combine(0, a), b));
+
+ static int hash4(a, b, c, d) =>
+ finish(combine(combine(combine(combine(0, a), b), c), d));
}
/**
- * The handle object that should be used to stop and update counter.
+ * Helper class for gathering performance statistics. This class is modeled on
+ * the UserTag class in dart:profiler so that it can interoperate easily with
+ * it.
*/
-class TimeCounter_TimeCounterHandle {
- final TimeCounter _counter;
- int _startMicros;
- TimeCounter _prev;
-
- TimeCounter_TimeCounterHandle(this._counter) {
- // if there is some counter running, pause it
- _prev = TimeCounter._current;
- if (_prev != null) {
- _prev._sw.stop();
- }
- TimeCounter._current = _counter;
- // start this counter
- _startMicros = _counter._sw.elapsedMicroseconds;
- _counter._sw.start();
- }
+abstract class PerformanceTag {
+ /**
+ * Return a list of all [PerformanceTag]s which have been created.
+ */
+ static List<PerformanceTag> get all => _PerformanceTagImpl.all.toList();
/**
- * Stops counting time and updates counter.
+ * Return the current [PerformanceTag] for the isolate.
*/
- int stop() {
- _counter._sw.stop();
- int elapsed =
- (_counter._sw.elapsedMicroseconds - _startMicros) *
- TimeCounter.NANOS_PER_MICRO;
- // restore previous counter and resume it
- TimeCounter._current = _prev;
- if (_prev != null) {
- _prev._sw.start();
+ static PerformanceTag get current => _PerformanceTagImpl.current;
+
+ /**
+ * Return the [PerformanceTag] that is initially current. This is intended
+ * to track time when the system is performing unknown operations.
+ */
+ static PerformanceTag get UNKNOWN => _PerformanceTagImpl.UNKNOWN;
+
+ /**
+ * Create a [PerformanceTag] having the given [label]. A [UserTag] will also
+ * be created, having the same [label], so that performance information can
+ * be queried using the observatory.
+ */
+ factory PerformanceTag(String label) = _PerformanceTagImpl;
+
+ /**
+ * Return the total number of milliseconds that this [PerformanceTag] has
+ * been the current [PerformanceTag] for the isolate.
+ *
+ * This call is safe even if this [PerformanceTag] is current.
+ */
+ int get elapsedMs;
+
+ /**
+ * Return the label for this [PerformanceTag].
+ */
+ String get label;
+
+ /**
+ * Make this the current tag for the isolate, and return the previous tag.
+ */
+ PerformanceTag makeCurrent();
+
+ /**
+ * Make this the current tag for the isolate, run [f], and restore the
+ * previous tag. Returns the result of invoking [f].
+ */
+ makeCurrentWhile(f());
+
+ /**
+ * Reset the total time tracked by all [PerformanceTag]s to zero.
+ */
+ static void reset() {
+ for (_PerformanceTagImpl tag in _PerformanceTagImpl.all) {
+ tag.stopwatch.reset();
}
- // done
- return elapsed;
+ }
+}
+
+class _PerformanceTagImpl implements PerformanceTag {
+ /**
+ * The current performance tag for the isolate.
+ */
+ static _PerformanceTagImpl current = UNKNOWN;
+
+ static final _PerformanceTagImpl UNKNOWN = new _PerformanceTagImpl('unknown');
+
+ /**
+ * A list of all performance tags that have been created so far.
+ */
+ static List<_PerformanceTagImpl> all = <_PerformanceTagImpl>[];
+
+ /**
+ * The [UserTag] associated with this [PerformanceTag].
+ */
+ final UserTag userTag;
+
+ /**
+ * Stopwatch tracking the amount of time this [PerformanceTag] has been the
+ * current tag for the isolate.
+ */
+ final Stopwatch stopwatch;
+
+ _PerformanceTagImpl(String label)
+ : userTag = new UserTag(label),
+ stopwatch = new Stopwatch() {
+ all.add(this);
+ }
+
+ @override
+ int get elapsedMs => stopwatch.elapsedMilliseconds;
+
+ @override
+ String get label => userTag.label;
+
+ @override
+ PerformanceTag makeCurrent() {
+ if (identical(this, current)) {
+ return current;
+ }
+ _PerformanceTagImpl previous = current;
+ previous.stopwatch.stop();
+ stopwatch.start();
+ current = this;
+ userTag.makeCurrent();
+ return previous;
+ }
+
+ makeCurrentWhile(f()) {
+ PerformanceTag prevTag = makeCurrent();
+ try {
+ return f();
+ } finally {
+ prevTag.makeCurrent();
+ }
}
}
diff --git a/pkg/analyzer/lib/src/services/lint.dart b/pkg/analyzer/lib/src/services/lint.dart
index c0edb2c..829b371 100644
--- a/pkg/analyzer/lib/src/services/lint.dart
+++ b/pkg/analyzer/lib/src/services/lint.dart
@@ -42,17 +42,13 @@
: _linters = linters != null ? linters : LINTERS;
void generate() {
- TimeCounter_TimeCounterHandle timeCounter =
- PerformanceStatistics.lint.start();
- try {
+ PerformanceStatistics.lint.makeCurrentWhile(() {
_compilationUnits.forEach((cu) {
if (cu.element != null) {
_generate(cu, cu.element.source);
}
});
- } finally {
- timeCounter.stop();
- }
+ });
}
void _generate(CompilationUnit unit, Source source) {
diff --git a/pkg/analyzer/pubspec.yaml b/pkg/analyzer/pubspec.yaml
index e0c1fe4..d4b49c4 100644
--- a/pkg/analyzer/pubspec.yaml
+++ b/pkg/analyzer/pubspec.yaml
@@ -1,5 +1,5 @@
name: analyzer
-version: 0.24.0-dev.1
+version: 0.24.0
author: Dart Team <misc@dartlang.org>
description: Static analyzer for Dart.
homepage: http://www.dartlang.org
diff --git a/pkg/analyzer/test/file_system/memory_file_system_test.dart b/pkg/analyzer/test/file_system/memory_file_system_test.dart
index ecd647e..2dd95de 100644
--- a/pkg/analyzer/test/file_system/memory_file_system_test.dart
+++ b/pkg/analyzer/test/file_system/memory_file_system_test.dart
@@ -17,7 +17,7 @@
var _isFile = new isInstanceOf<File>();
var _isFolder = new isInstanceOf<Folder>();
-var _isMemoryResourceException = new isInstanceOf<MemoryResourceException>();
+var _isFileSystemException = new isInstanceOf<FileSystemException>();
main() {
@@ -30,13 +30,13 @@
provider = new MemoryResourceProvider();
});
- test('MemoryResourceException', () {
- var exception = new MemoryResourceException('/my/path', 'my message');
+ test('FileSystemException', () {
+ var exception = new FileSystemException('/my/path', 'my message');
expect(exception.path, '/my/path');
expect(exception.message, 'my message');
expect(
exception.toString(),
- 'MemoryResourceException(path=/my/path; message=my message)');
+ 'FileSystemException(path=/my/path; message=my message)');
});
group('Watch', () {
@@ -281,6 +281,23 @@
expect(file.isOrContains('/foo/bar'), isFalse);
});
+ group('modificationStamp', () {
+ test('exists', () {
+ String path = '/foo/bar/file.txt';
+ File file = provider.newFile(path, 'qwerty');
+ expect(file.modificationStamp, isNonNegative);
+ });
+
+ test('does not exist', () {
+ String path = '/foo/bar/file.txt';
+ File file = provider.newFile(path, 'qwerty');
+ provider.deleteFile(path);
+ expect(() {
+ file.modificationStamp;
+ }, throwsA(_isFileSystemException));
+ });
+ });
+
test('shortName', () {
File file = provider.getResource('/foo/bar/file.txt');
expect(file.shortName, 'file.txt');
@@ -485,7 +502,7 @@
test('contents', () {
expect(() {
source.contents;
- }, throwsA(_isMemoryResourceException));
+ }, throwsA(_isFileSystemException));
});
test('encoding', () {
@@ -500,6 +517,10 @@
expect(source.fullName, '/foo/test.dart');
});
+ test('modificationStamp', () {
+ expect(source.modificationStamp, -1);
+ });
+
test('shortName', () {
expect(source.shortName, 'test.dart');
});
diff --git a/pkg/analyzer/test/file_system/physical_resource_provider_test.dart b/pkg/analyzer/test/file_system/physical_resource_provider_test.dart
index c1c09ca..3ba46e8 100644
--- a/pkg/analyzer/test/file_system/physical_resource_provider_test.dart
+++ b/pkg/analyzer/test/file_system/physical_resource_provider_test.dart
@@ -17,6 +17,7 @@
var _isFile = new isInstanceOf<File>();
var _isFolder = new isInstanceOf<Folder>();
+var _isFileSystemException = new isInstanceOf<FileSystemException>();
main() {
@@ -199,6 +200,21 @@
expect(file.isOrContains('foo'), isFalse);
});
+ group('modificationStamp', () {
+ test('exists', () {
+ new io.File(path).writeAsStringSync('contents');
+ File file = PhysicalResourceProvider.INSTANCE.getResource(path);
+ expect(file.modificationStamp, isNonNegative);
+ });
+
+ test('does not exist', () {
+ File file = PhysicalResourceProvider.INSTANCE.getResource(path);
+ expect(() {
+ file.modificationStamp;
+ }, throwsA(_isFileSystemException));
+ });
+ });
+
test('shortName', () {
expect(file.shortName, 'file.txt');
});
diff --git a/pkg/analyzer/test/generated/all_the_rest_test.dart b/pkg/analyzer/test/generated/all_the_rest_test.dart
index 8f190b8..0e9027e 100644
--- a/pkg/analyzer/test/generated/all_the_rest_test.dart
+++ b/pkg/analyzer/test/generated/all_the_rest_test.dart
@@ -9,7 +9,10 @@
import 'dart:collection';
+import 'package:analyzer/file_system/file_system.dart';
+import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
+import 'package:analyzer/source/package_map_resolver.dart';
import 'package:analyzer/src/generated/ast.dart' hide ConstantEvaluator;
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/element.dart';
@@ -32,16 +35,13 @@
import 'package:analyzer/src/generated/testing/test_type_provider.dart';
import 'package:analyzer/src/generated/utilities_collection.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
+import 'package:path/src/context.dart';
import 'package:unittest/unittest.dart';
import '../reflective_tests.dart';
import 'parser_test.dart';
import 'resolver_test.dart';
import 'test_support.dart';
-import 'package:analyzer/source/package_map_resolver.dart';
-import 'package:analyzer/file_system/memory_file_system.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:path/src/context.dart';
main() {
@@ -508,10 +508,6 @@
expect(value, null);
}
- void fail_plus_string_string() {
- _assertValue4("ab", "'a' + 'b'");
- }
-
void fail_prefixedIdentifier_invalid() {
EvaluationResult result = _getExpressionValue("?");
expect(result.isValid, isTrue);
@@ -554,14 +550,6 @@
expect(value, null);
}
- void fail_stringLength_complex() {
- _assertValue3(6, "('qwe' + 'rty').length");
- }
-
- void fail_stringLength_simple() {
- _assertValue3(6, "'Dvorak'.length");
- }
-
void test_bitAnd_int_int() {
_assertValue3(74 & 42, "74 & 42");
}
@@ -577,6 +565,7 @@
void test_bitXor_int_int() {
_assertValue3(74 ^ 42, "74 ^ 42");
}
+
void test_divide_double_double() {
_assertValue2(3.2 / 2.3, "3.2 / 2.3");
}
@@ -592,7 +581,6 @@
void test_divide_int_int() {
_assertValue3(1, "3 / 2");
}
-
void test_divide_int_int_byZero() {
EvaluationResult result = _getExpressionValue("3 / 0");
expect(result.isValid, isTrue);
@@ -631,6 +619,7 @@
void test_leftShift_int_int() {
_assertValue3(64, "16 << 2");
}
+
void test_lessThan_int_int() {
_assertValue(true, "2 < 3");
}
@@ -642,7 +631,6 @@
void test_literal_boolean_false() {
_assertValue(false, "false");
}
-
void test_literal_boolean_true() {
_assertValue(true, "true");
}
@@ -757,6 +745,10 @@
_assertValue3(5, "2 + 3");
}
+ void test_plus_string_string() {
+ _assertValue4("ab", "'a' + 'b'");
+ }
+
void test_remainder_double_double() {
_assertValue2(3.2 % 2.3, "3.2 % 2.3");
}
@@ -769,6 +761,14 @@
_assertValue3(16, "64 >> 2");
}
+ void test_stringLength_complex() {
+ _assertValue3(6, "('qwe' + 'rty').length");
+ }
+
+ void test_stringLength_simple() {
+ _assertValue3(6, "'Dvorak'.length");
+ }
+
void test_times_double_double() {
_assertValue2(2.3 * 3.2, "2.3 * 3.2");
}
@@ -2405,28 +2405,38 @@
@reflectiveTest
+class CustomUriResolverTest {
+ void test_creation() {
+ expect(new CustomUriResolver({}), isNotNull);
+ }
+
+ void test_resolve_unknown_uri() {
+ UriResolver resolver = new CustomUriResolver({
+ 'custom:library': '/path/to/library.dart',
+ });
+ Source result =
+ resolver.resolveAbsolute(parseUriWithException("custom:non_library"));
+ expect(result, isNull);
+ }
+
+ void test_resolve_uri() {
+ String path =
+ FileUtilities2.createFile("/path/to/library.dart").getAbsolutePath();
+ UriResolver resolver = new CustomUriResolver({
+ 'custom:library': path,
+ });
+ Source result =
+ resolver.resolveAbsolute(parseUriWithException("custom:library"));
+ expect(result, isNotNull);
+ expect(result.fullName, path);
+ }
+}
+
+
+@reflectiveTest
class DartObjectImplTest extends EngineTestCase {
TypeProvider _typeProvider = new TestTypeProvider();
- void fail_add_knownString_knownString() {
- fail("New constant semantics are not yet enabled");
- _assertAdd(_stringValue("ab"), _stringValue("a"), _stringValue("b"));
- }
-
- void fail_add_knownString_unknownString() {
- fail("New constant semantics are not yet enabled");
- _assertAdd(_stringValue(null), _stringValue("a"), _stringValue(null));
- }
-
- void fail_add_unknownString_knownString() {
- fail("New constant semantics are not yet enabled");
- _assertAdd(_stringValue(null), _stringValue(null), _stringValue("b"));
- }
- void fail_add_unknownString_unknownString() {
- fail("New constant semantics are not yet enabled");
- _assertAdd(_stringValue(null), _stringValue(null), _stringValue(null));
- }
-
void test_add_knownDouble_knownDouble() {
_assertAdd(_doubleValue(3.0), _doubleValue(1.0), _doubleValue(2.0));
}
@@ -2463,6 +2473,14 @@
_assertAdd(null, _stringValue("1"), _intValue(2));
}
+ void test_add_knownString_knownString() {
+ _assertAdd(_stringValue("ab"), _stringValue("a"), _stringValue("b"));
+ }
+
+ void test_add_knownString_unknownString() {
+ _assertAdd(_stringValue(null), _stringValue("a"), _stringValue(null));
+ }
+
void test_add_unknownDouble_knownDouble() {
_assertAdd(_doubleValue(null), _doubleValue(null), _doubleValue(2.0));
}
@@ -2478,6 +2496,14 @@
void test_add_unknownInt_knownInt() {
_assertAdd(_intValue(null), _intValue(null), _intValue(2));
}
+
+ void test_add_unknownString_knownString() {
+ _assertAdd(_stringValue(null), _stringValue(null), _stringValue("b"));
+ }
+
+ void test_add_unknownString_unknownString() {
+ _assertAdd(_stringValue(null), _stringValue(null), _stringValue(null));
+ }
void test_bitAnd_knownInt_knownInt() {
_assertBitAnd(_intValue(2), _intValue(6), _intValue(3));
}
@@ -6173,6 +6199,48 @@
expect(variable.setter, isNotNull);
}
+ void test_visitVariableDeclaration_top_const_hasInitializer() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = new ElementBuilder(holder);
+ String variableName = "v";
+ VariableDeclaration variableDeclaration =
+ AstFactory.variableDeclaration2(variableName, AstFactory.integer(42));
+ AstFactory.variableDeclarationList2(Keyword.CONST, [variableDeclaration]);
+ variableDeclaration.accept(builder);
+ List<TopLevelVariableElement> variables = holder.topLevelVariables;
+ expect(variables, hasLength(1));
+ TopLevelVariableElement variable = variables[0];
+ expect(variable, new isInstanceOf<ConstTopLevelVariableElementImpl>());
+ expect(variable.initializer, isNotNull);
+ expect(variable.name, variableName);
+ expect(variable.isConst, isTrue);
+ expect(variable.isFinal, isFalse);
+ expect(variable.isSynthetic, isFalse);
+ expect(variable.getter, isNotNull);
+ expect(variable.setter, isNull);
+ }
+
+ void test_visitVariableDeclaration_top_final() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = new ElementBuilder(holder);
+ String variableName = "v";
+ VariableDeclaration variableDeclaration =
+ AstFactory.variableDeclaration2(variableName, null);
+ AstFactory.variableDeclarationList2(Keyword.FINAL, [variableDeclaration]);
+ variableDeclaration.accept(builder);
+ List<TopLevelVariableElement> variables = holder.topLevelVariables;
+ expect(variables, hasLength(1));
+ TopLevelVariableElement variable = variables[0];
+ expect(variable, isNotNull);
+ expect(variable.initializer, isNull);
+ expect(variable.name, variableName);
+ expect(variable.isConst, isFalse);
+ expect(variable.isFinal, isTrue);
+ expect(variable.isSynthetic, isFalse);
+ expect(variable.getter, isNotNull);
+ expect(variable.setter, isNull);
+ }
+
void _useParameterInMethod(FormalParameter formalParameter, int blockOffset,
int blockEnd) {
Block block = AstFactory.block();
@@ -6797,7 +6865,6 @@
}
}
-
@reflectiveTest
class ErrorSeverityTest extends EngineTestCase {
void test_max_error_error() {
@@ -7356,6 +7423,7 @@
}
}
+
/**
* Tests for the [ExitDetector] that require that the AST be resolved.
*
@@ -7734,35 +7802,6 @@
@reflectiveTest
-class CustomUriResolverTest {
- void test_creation() {
- expect(new CustomUriResolver({}), isNotNull);
- }
-
- void test_resolve_unknown_uri() {
- UriResolver resolver = new CustomUriResolver({
- 'custom:library': '/path/to/library.dart',
- });
- Source result = resolver.resolveAbsolute(
- parseUriWithException("custom:non_library"));
- expect(result, isNull);
- }
-
- void test_resolve_uri() {
- String path =
- FileUtilities2.createFile("/path/to/library.dart").getAbsolutePath();
- UriResolver resolver = new CustomUriResolver({
- 'custom:library': path,
- });
- Source result = resolver.resolveAbsolute(
- parseUriWithException("custom:library"));
- expect(result, isNotNull);
- expect(result.fullName, path);
- }
-}
-
-
-@reflectiveTest
class HtmlParserTest extends EngineTestCase {
/**
* The name of the 'script' tag in an HTML file.
@@ -8512,21 +8551,25 @@
void test_resolveUri_nonAbsolute_relative_package() {
MemoryResourceProvider provider = new MemoryResourceProvider();
Context context = provider.pathContext;
- String packagePath = context.joinAll([context.separator, 'path', 'to', 'package']);
+ String packagePath =
+ context.joinAll([context.separator, 'path', 'to', 'package']);
String libPath = context.joinAll([packagePath, 'lib']);
String dirPath = context.joinAll([libPath, 'dir']);
String firstPath = context.joinAll([dirPath, 'first.dart']);
String secondPath = context.joinAll([dirPath, 'second.dart']);
provider.newFolder(packagePath);
- Folder libFolder = provider.newFolder(libPath);
+ Folder libFolder = provider.newFolder(libPath);
provider.newFolder(dirPath);
File firstFile = provider.newFile(firstPath, '');
provider.newFile(secondPath, '');
- PackageMapUriResolver resolver = new PackageMapUriResolver(provider, {'package' : [libFolder]});
+ PackageMapUriResolver resolver = new PackageMapUriResolver(provider, {
+ 'package': [libFolder]
+ });
SourceFactory factory = new SourceFactory([resolver]);
- Source librarySource = firstFile.createSource(Uri.parse('package:package/dir/first.dart'));
+ Source librarySource =
+ firstFile.createSource(Uri.parse('package:package/dir/first.dart'));
Source result = factory.resolveUri(librarySource, 'second.dart');
expect(result, isNotNull);
diff --git a/pkg/analyzer/test/generated/engine_test.dart b/pkg/analyzer/test/generated/engine_test.dart
index 934334d..d20ab08 100644
--- a/pkg/analyzer/test/generated/engine_test.dart
+++ b/pkg/analyzer/test/generated/engine_test.dart
@@ -20,6 +20,7 @@
import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/java_engine_io.dart';
+import 'package:analyzer/src/generated/java_io.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/scanner.dart';
@@ -97,6 +98,31 @@
expect(iterator.moveNext(), isFalse);
}
+ /**
+ * Verify that if multiple Source objects refer to the same file via
+ * different URIs, they are treated as separate entries in the cache.
+ */
+ void test_lookup_distinguishes_uris() {
+ CachePartition partition =
+ new UniversalCachePartition(null, 8, new DefaultRetentionPolicy());
+ AnalysisCache cache = new AnalysisCache(<CachePartition>[partition]);
+ JavaFile file = new JavaFile('baz.dart');
+ Source source1 = new FileBasedSource.con1(file);
+ Source source2 =
+ new FileBasedSource.con2(Uri.parse('package:foo/baz.dart'), file);
+ Source source3 =
+ new FileBasedSource.con2(Uri.parse('package:bar/baz.dart'), file);
+ DartEntry entry1 = new DartEntry();
+ DartEntry entry2 = new DartEntry();
+ DartEntry entry3 = new DartEntry();
+ cache.put(source1, entry1);
+ cache.put(source2, entry2);
+ cache.put(source3, entry3);
+ expect(cache.get(source1), same(entry1));
+ expect(cache.get(source2), same(entry2));
+ expect(cache.get(source3), same(entry3));
+ }
+
void test_put_noFlush() {
CachePartition partition =
new UniversalCachePartition(null, 8, new DefaultRetentionPolicy());
@@ -6030,6 +6056,19 @@
fail("Unexpected invocation of getTypeProvider");
return null;
}
+
+ @override
+ TypeResolverVisitorFactory get typeResolverVisitorFactory {
+ fail("Unexpected invocation of getTypeResolverVisitorFactory");
+ return null;
+ }
+
+ @override
+ ResolverVisitorFactory get resolverVisitorFactory {
+ fail("Unexpected invocation of getResolverVisitorFactory");
+ return null;
+ }
+
@override
void addListener(AnalysisListener listener) {
fail("Unexpected invocation of addListener");
diff --git a/pkg/analyzer/test/generated/non_error_resolver_test.dart b/pkg/analyzer/test/generated/non_error_resolver_test.dart
index 1761c81..034544f 100644
--- a/pkg/analyzer/test/generated/non_error_resolver_test.dart
+++ b/pkg/analyzer/test/generated/non_error_resolver_test.dart
@@ -1167,6 +1167,16 @@
verify([source]);
}
+ void test_constEvelTypeNum_String() {
+ Source source = addSource(r'''
+const String A = 'a';
+const String B = A + 'b';
+''');
+ resolve(source);
+ assertNoErrors(source);
+ verify([source]);
+ }
+
void test_constMapKeyExpressionTypeImplementsEquals_abstract() {
Source source = addSource(r'''
abstract class B {
diff --git a/pkg/analyzer/test/generated/parser_test.dart b/pkg/analyzer/test/generated/parser_test.dart
index db3753c..77877f9 100644
--- a/pkg/analyzer/test/generated/parser_test.dart
+++ b/pkg/analyzer/test/generated/parser_test.dart
@@ -125,14 +125,6 @@
*/
@reflectiveTest
class ComplexParserTest extends ParserTestCase {
- void test_additiveExpression_normal() {
- BinaryExpression expression = ParserTestCase.parseExpression("x + y - z");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is BinaryExpression,
- BinaryExpression,
- expression.leftOperand);
- }
-
void test_additiveExpression_noSpaces() {
BinaryExpression expression = ParserTestCase.parseExpression("i+1");
EngineTestCase.assertInstanceOf(
@@ -145,6 +137,14 @@
expression.rightOperand);
}
+ void test_additiveExpression_normal() {
+ BinaryExpression expression = ParserTestCase.parseExpression("x + y - z");
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is BinaryExpression,
+ BinaryExpression,
+ expression.leftOperand);
+ }
+
void test_additiveExpression_precedence_multiplicative_left() {
BinaryExpression expression = ParserTestCase.parseExpression("x * y + z");
EngineTestCase.assertInstanceOf(
@@ -934,6 +934,12 @@
[ParserErrorCode.CONST_METHOD]);
}
+ void test_constTypedef() {
+ ParserTestCase.parseCompilationUnit(
+ "const typedef F();",
+ [ParserErrorCode.CONST_TYPEDEF]);
+ }
+
void test_constructorWithReturnType() {
ParserTestCase.parse3(
"parseClassMember",
@@ -950,12 +956,6 @@
[ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE]);
}
- void test_constTypedef() {
- ParserTestCase.parseCompilationUnit(
- "const typedef F();",
- [ParserErrorCode.CONST_TYPEDEF]);
- }
-
void test_continueOutsideOfLoop_continueInDoStatement() {
ParserTestCase.parse4("parseDoStatement", "do {continue;} while (x);");
}
@@ -1036,6 +1036,13 @@
expect(unit, isNotNull);
}
+ void test_duplicateLabelInSwitchStatement() {
+ ParserTestCase.parse4(
+ "parseSwitchStatement",
+ "switch (e) {l1: case 0: break; l1: case 1: break;}",
+ [ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT]);
+ }
+
void test_duplicatedModifier_const() {
ParserTestCase.parse3(
"parseClassMember",
@@ -1084,13 +1091,6 @@
[ParserErrorCode.DUPLICATED_MODIFIER]);
}
- void test_duplicateLabelInSwitchStatement() {
- ParserTestCase.parse4(
- "parseSwitchStatement",
- "switch (e) {l1: case 0: break; l1: case 1: break;}",
- [ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT]);
- }
-
void test_emptyEnumBody() {
ParserTestCase.parse3(
"parseEnumDeclaration",
@@ -2348,14 +2348,6 @@
ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES]);
}
- void test_topLevelOperator_withoutType() {
- ParserTestCase.parse3(
- "parseCompilationUnitMember",
- <Object>[emptyCommentAndMetadata()],
- "operator +(bool x, bool y) => x | y;",
- [ParserErrorCode.TOP_LEVEL_OPERATOR]);
- }
-
void test_topLevelOperator_withType() {
ParserTestCase.parse3(
"parseCompilationUnitMember",
@@ -2372,10 +2364,12 @@
[ParserErrorCode.TOP_LEVEL_OPERATOR]);
}
- void test_typedefInClass_withoutReturnType() {
- ParserTestCase.parseCompilationUnit(
- "class C { typedef F(x); }",
- [ParserErrorCode.TYPEDEF_IN_CLASS]);
+ void test_topLevelOperator_withoutType() {
+ ParserTestCase.parse3(
+ "parseCompilationUnitMember",
+ <Object>[emptyCommentAndMetadata()],
+ "operator +(bool x, bool y) => x | y;",
+ [ParserErrorCode.TOP_LEVEL_OPERATOR]);
}
void test_typedefInClass_withReturnType() {
@@ -2384,6 +2378,12 @@
[ParserErrorCode.TYPEDEF_IN_CLASS]);
}
+ void test_typedefInClass_withoutReturnType() {
+ ParserTestCase.parseCompilationUnit(
+ "class C { typedef F(x); }",
+ [ParserErrorCode.TYPEDEF_IN_CLASS]);
+ }
+
void test_unexpectedTerminatorForParameterGroup_named() {
ParserTestCase.parse4(
"parseFormalParameterList",
@@ -2503,18 +2503,6 @@
[ParserErrorCode.VOID_VARIABLE]);
}
- void test_voidVariable_parseCompilationUnit_initializer() {
- ParserTestCase.parseCompilationUnit(
- "void x = 0;",
- [ParserErrorCode.VOID_VARIABLE]);
- }
-
- void test_voidVariable_parseCompilationUnit_noInitializer() {
- ParserTestCase.parseCompilationUnit(
- "void x;",
- [ParserErrorCode.VOID_VARIABLE]);
- }
-
void test_voidVariable_parseCompilationUnitMember_initializer() {
ParserTestCase.parse3(
"parseCompilationUnitMember",
@@ -2531,6 +2519,18 @@
[ParserErrorCode.VOID_VARIABLE]);
}
+ void test_voidVariable_parseCompilationUnit_initializer() {
+ ParserTestCase.parseCompilationUnit(
+ "void x = 0;",
+ [ParserErrorCode.VOID_VARIABLE]);
+ }
+
+ void test_voidVariable_parseCompilationUnit_noInitializer() {
+ ParserTestCase.parseCompilationUnit(
+ "void x;",
+ [ParserErrorCode.VOID_VARIABLE]);
+ }
+
void test_voidVariable_statement_initializer() {
ParserTestCase.parseStatement(
"void x = 0;",
@@ -2727,6 +2727,12 @@
_assertParse("f() => a + b", "", ".", ";");
}
+ void test_insert_periodAndIdentifier() {
+ // "f() => a + b;"
+ // "f() => a + b.x;"
+ _assertParse("f() => a + b", "", ".x", ";");
+ }
+
void test_insert_period_betweenIdentifiers1() {
// "f() => a b;"
// "f() => a. b;"
@@ -2751,12 +2757,6 @@
_assertParse("f() => a", "", ".", "b;");
}
- void test_insert_periodAndIdentifier() {
- // "f() => a + b;"
- // "f() => a + b.x;"
- _assertParse("f() => a + b", "", ".x", ";");
- }
-
void test_insert_simpleToComplexExression() {
// "/** An [A]. */ class A {} class B { m() => 1; }"
// "/** An [A]. */ class A {} class B { m() => 1 + 2; }"
@@ -3376,6 +3376,26 @@
expression.leftOperand);
}
+ void test_assignmentExpression_missing_LHS() {
+ AssignmentExpression expression =
+ ParserTestCase.parseExpression("= 0", [ParserErrorCode.MISSING_IDENTIFIER]);
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is SimpleIdentifier,
+ SimpleIdentifier,
+ expression.leftHandSide);
+ expect(expression.leftHandSide.isSynthetic, isTrue);
+ }
+
+ void test_assignmentExpression_missing_RHS() {
+ AssignmentExpression expression =
+ ParserTestCase.parseExpression("x =", [ParserErrorCode.MISSING_IDENTIFIER]);
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is SimpleIdentifier,
+ SimpleIdentifier,
+ expression.leftHandSide);
+ expect(expression.rightHandSide.isSynthetic, isTrue);
+ }
+
void test_assignmentExpression_missing_compound1() {
AssignmentExpression expression = ParserTestCase.parseExpression(
"= y = 0",
@@ -3414,26 +3434,6 @@
expect(syntheticExpression.isSynthetic, isTrue);
}
- void test_assignmentExpression_missing_LHS() {
- AssignmentExpression expression =
- ParserTestCase.parseExpression("= 0", [ParserErrorCode.MISSING_IDENTIFIER]);
- EngineTestCase.assertInstanceOf(
- (obj) => obj is SimpleIdentifier,
- SimpleIdentifier,
- expression.leftHandSide);
- expect(expression.leftHandSide.isSynthetic, isTrue);
- }
-
- void test_assignmentExpression_missing_RHS() {
- AssignmentExpression expression =
- ParserTestCase.parseExpression("x =", [ParserErrorCode.MISSING_IDENTIFIER]);
- EngineTestCase.assertInstanceOf(
- (obj) => obj is SimpleIdentifier,
- SimpleIdentifier,
- expression.leftHandSide);
- expect(expression.rightHandSide.isSynthetic, isTrue);
- }
-
void test_bitwiseAndExpression_missing_LHS() {
BinaryExpression expression =
ParserTestCase.parseExpression("& y", [ParserErrorCode.MISSING_IDENTIFIER]);
@@ -3865,6 +3865,90 @@
[ParserErrorCode.EXPECTED_TOKEN]);
}
+ void test_incompleteField_const() {
+ CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
+class C {
+ const
+}''', [ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.EXPECTED_TOKEN]);
+ NodeList<CompilationUnitMember> declarations = unit.declarations;
+ expect(declarations, hasLength(1));
+ CompilationUnitMember unitMember = declarations[0];
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is ClassDeclaration,
+ ClassDeclaration,
+ unitMember);
+ NodeList<ClassMember> members = (unitMember as ClassDeclaration).members;
+ expect(members, hasLength(1));
+ ClassMember classMember = members[0];
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is FieldDeclaration,
+ FieldDeclaration,
+ classMember);
+ VariableDeclarationList fieldList =
+ (classMember as FieldDeclaration).fields;
+ expect((fieldList.keyword as KeywordToken).keyword, Keyword.CONST);
+ NodeList<VariableDeclaration> fields = fieldList.variables;
+ expect(fields, hasLength(1));
+ VariableDeclaration field = fields[0];
+ expect(field.name.isSynthetic, isTrue);
+ }
+
+ void test_incompleteField_final() {
+ CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
+class C {
+ final
+}''', [ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.EXPECTED_TOKEN]);
+ NodeList<CompilationUnitMember> declarations = unit.declarations;
+ expect(declarations, hasLength(1));
+ CompilationUnitMember unitMember = declarations[0];
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is ClassDeclaration,
+ ClassDeclaration,
+ unitMember);
+ NodeList<ClassMember> members = (unitMember as ClassDeclaration).members;
+ expect(members, hasLength(1));
+ ClassMember classMember = members[0];
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is FieldDeclaration,
+ FieldDeclaration,
+ classMember);
+ VariableDeclarationList fieldList =
+ (classMember as FieldDeclaration).fields;
+ expect((fieldList.keyword as KeywordToken).keyword, Keyword.FINAL);
+ NodeList<VariableDeclaration> fields = fieldList.variables;
+ expect(fields, hasLength(1));
+ VariableDeclaration field = fields[0];
+ expect(field.name.isSynthetic, isTrue);
+ }
+
+ void test_incompleteField_var() {
+ CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
+class C {
+ var
+}''', [ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.EXPECTED_TOKEN]);
+ NodeList<CompilationUnitMember> declarations = unit.declarations;
+ expect(declarations, hasLength(1));
+ CompilationUnitMember unitMember = declarations[0];
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is ClassDeclaration,
+ ClassDeclaration,
+ unitMember);
+ NodeList<ClassMember> members = (unitMember as ClassDeclaration).members;
+ expect(members, hasLength(1));
+ ClassMember classMember = members[0];
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is FieldDeclaration,
+ FieldDeclaration,
+ classMember);
+ VariableDeclarationList fieldList =
+ (classMember as FieldDeclaration).fields;
+ expect((fieldList.keyword as KeywordToken).keyword, Keyword.VAR);
+ NodeList<VariableDeclaration> fields = fieldList.variables;
+ expect(fields, hasLength(1));
+ VariableDeclaration field = fields[0];
+ expect(field.name.isSynthetic, isTrue);
+ }
+
void test_incomplete_conditionalExpression() {
ParserTestCase.parseExpression(
"x ? 0",
@@ -3983,90 +4067,6 @@
expect(name.isSynthetic, isTrue);
}
- void test_incompleteField_const() {
- CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
-class C {
- const
-}''', [ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.EXPECTED_TOKEN]);
- NodeList<CompilationUnitMember> declarations = unit.declarations;
- expect(declarations, hasLength(1));
- CompilationUnitMember unitMember = declarations[0];
- EngineTestCase.assertInstanceOf(
- (obj) => obj is ClassDeclaration,
- ClassDeclaration,
- unitMember);
- NodeList<ClassMember> members = (unitMember as ClassDeclaration).members;
- expect(members, hasLength(1));
- ClassMember classMember = members[0];
- EngineTestCase.assertInstanceOf(
- (obj) => obj is FieldDeclaration,
- FieldDeclaration,
- classMember);
- VariableDeclarationList fieldList =
- (classMember as FieldDeclaration).fields;
- expect((fieldList.keyword as KeywordToken).keyword, Keyword.CONST);
- NodeList<VariableDeclaration> fields = fieldList.variables;
- expect(fields, hasLength(1));
- VariableDeclaration field = fields[0];
- expect(field.name.isSynthetic, isTrue);
- }
-
- void test_incompleteField_final() {
- CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
-class C {
- final
-}''', [ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.EXPECTED_TOKEN]);
- NodeList<CompilationUnitMember> declarations = unit.declarations;
- expect(declarations, hasLength(1));
- CompilationUnitMember unitMember = declarations[0];
- EngineTestCase.assertInstanceOf(
- (obj) => obj is ClassDeclaration,
- ClassDeclaration,
- unitMember);
- NodeList<ClassMember> members = (unitMember as ClassDeclaration).members;
- expect(members, hasLength(1));
- ClassMember classMember = members[0];
- EngineTestCase.assertInstanceOf(
- (obj) => obj is FieldDeclaration,
- FieldDeclaration,
- classMember);
- VariableDeclarationList fieldList =
- (classMember as FieldDeclaration).fields;
- expect((fieldList.keyword as KeywordToken).keyword, Keyword.FINAL);
- NodeList<VariableDeclaration> fields = fieldList.variables;
- expect(fields, hasLength(1));
- VariableDeclaration field = fields[0];
- expect(field.name.isSynthetic, isTrue);
- }
-
- void test_incompleteField_var() {
- CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
-class C {
- var
-}''', [ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.EXPECTED_TOKEN]);
- NodeList<CompilationUnitMember> declarations = unit.declarations;
- expect(declarations, hasLength(1));
- CompilationUnitMember unitMember = declarations[0];
- EngineTestCase.assertInstanceOf(
- (obj) => obj is ClassDeclaration,
- ClassDeclaration,
- unitMember);
- NodeList<ClassMember> members = (unitMember as ClassDeclaration).members;
- expect(members, hasLength(1));
- ClassMember classMember = members[0];
- EngineTestCase.assertInstanceOf(
- (obj) => obj is FieldDeclaration,
- FieldDeclaration,
- classMember);
- VariableDeclarationList fieldList =
- (classMember as FieldDeclaration).fields;
- expect((fieldList.keyword as KeywordToken).keyword, Keyword.VAR);
- NodeList<VariableDeclaration> fields = fieldList.variables;
- expect(fields, hasLength(1));
- VariableDeclaration field = fields[0];
- expect(field.name.isSynthetic, isTrue);
- }
-
void test_invalidFunctionBodyModifier() {
ParserTestCase.parseCompilationUnit(
"f() sync {}",
@@ -4228,12 +4228,6 @@
expression.rightOperand);
}
- void test_missing_commaInArgumentList() {
- ParserTestCase.parseExpression(
- "f(x: 1 y: 2)",
- [ParserErrorCode.EXPECTED_TOKEN]);
- }
-
void test_missingGet() {
CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
class C {
@@ -4269,6 +4263,12 @@
expect(metadata[0].name.name, "override");
}
+ void test_missing_commaInArgumentList() {
+ ParserTestCase.parseExpression(
+ "f(x: 1 y: 2)",
+ [ParserErrorCode.EXPECTED_TOKEN]);
+ }
+
void test_multiplicativeExpression_missing_LHS() {
BinaryExpression expression =
ParserTestCase.parseExpression("* y", [ParserErrorCode.MISSING_IDENTIFIER]);
@@ -4977,18 +4977,6 @@
expect(toNode.staticType, same(staticType));
}
- void test_visitPrefixedIdentifier() {
- PrefixedIdentifier fromNode = AstFactory.identifier5("p", "f");
- DartType propagatedType = ElementFactory.classElement2("C").type;
- fromNode.propagatedType = propagatedType;
- DartType staticType = ElementFactory.classElement2("C").type;
- fromNode.staticType = staticType;
- PrefixedIdentifier toNode = AstFactory.identifier5("p", "f");
- ResolutionCopier.copyResolutionData(fromNode, toNode);
- expect(toNode.propagatedType, same(propagatedType));
- expect(toNode.staticType, same(staticType));
- }
-
void test_visitPrefixExpression() {
PrefixExpression fromNode =
AstFactory.prefixExpression(TokenType.PLUS_PLUS, AstFactory.identifier3("x"));
@@ -5011,6 +4999,18 @@
expect(toNode.staticType, same(staticType));
}
+ void test_visitPrefixedIdentifier() {
+ PrefixedIdentifier fromNode = AstFactory.identifier5("p", "f");
+ DartType propagatedType = ElementFactory.classElement2("C").type;
+ fromNode.propagatedType = propagatedType;
+ DartType staticType = ElementFactory.classElement2("C").type;
+ fromNode.staticType = staticType;
+ PrefixedIdentifier toNode = AstFactory.identifier5("p", "f");
+ ResolutionCopier.copyResolutionData(fromNode, toNode);
+ expect(toNode.propagatedType, same(propagatedType));
+ expect(toNode.staticType, same(staticType));
+ }
+
void test_visitPropertyAccess() {
PropertyAccess fromNode =
AstFactory.propertyAccess2(AstFactory.identifier3("x"), "y");
@@ -5224,6 +5224,10 @@
expect(identifier.offset, 5);
}
+ void test_Parser() {
+ expect(new Parser(null, null), isNotNull);
+ }
+
void test_computeStringValue_emptyInterpolationPrefix() {
expect(_computeStringValue("'''", true, false), "");
}
@@ -5596,22 +5600,6 @@
expect(annotation.arguments, isNotNull);
}
- void test_parseArgument_named() {
- NamedExpression expression = ParserTestCase.parse4("parseArgument", "n: x");
- Label name = expression.name;
- expect(name, isNotNull);
- expect(name.label, isNotNull);
- expect(name.colon, isNotNull);
- expect(expression.expression, isNotNull);
- }
-
- void test_parseArgument_unnamed() {
- String lexeme = "x";
- SimpleIdentifier identifier =
- ParserTestCase.parse4("parseArgument", lexeme);
- expect(identifier.name, lexeme);
- }
-
void test_parseArgumentList_empty() {
ArgumentList argumentList =
ParserTestCase.parse4("parseArgumentList", "()");
@@ -5640,6 +5628,22 @@
expect(arguments, hasLength(2));
}
+ void test_parseArgument_named() {
+ NamedExpression expression = ParserTestCase.parse4("parseArgument", "n: x");
+ Label name = expression.name;
+ expect(name, isNotNull);
+ expect(name.label, isNotNull);
+ expect(name.colon, isNotNull);
+ expect(expression.expression, isNotNull);
+ }
+
+ void test_parseArgument_unnamed() {
+ String lexeme = "x";
+ SimpleIdentifier identifier =
+ ParserTestCase.parse4("parseArgument", lexeme);
+ expect(identifier.name, lexeme);
+ }
+
void test_parseAssertStatement() {
AssertStatement statement =
ParserTestCase.parse4("parseAssertStatement", "assert (x);");
@@ -6985,116 +6989,6 @@
expect(reference.offset, 15);
}
- void test_parseCompilationUnit_abstractAsPrefix_parameterized() {
- CompilationUnit unit = ParserTestCase.parse4(
- "parseCompilationUnit",
- "abstract<dynamic> _abstract = new abstract.A();");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(0));
- expect(unit.declarations, hasLength(1));
- }
-
- void test_parseCompilationUnit_builtIn_asFunctionName() {
- ParserTestCase.parse4("parseCompilationUnit", "abstract(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "as(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "dynamic(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "export(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "external(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "factory(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "get(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "implements(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "import(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "library(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "operator(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "part(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "set(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "static(x) => 0;");
- ParserTestCase.parse4("parseCompilationUnit", "typedef(x) => 0;");
- }
-
- void test_parseCompilationUnit_directives_multiple() {
- CompilationUnit unit =
- ParserTestCase.parse4("parseCompilationUnit", "library l;\npart 'a.dart';");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(2));
- expect(unit.declarations, hasLength(0));
- }
-
- void test_parseCompilationUnit_directives_single() {
- CompilationUnit unit =
- ParserTestCase.parse4("parseCompilationUnit", "library l;");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(1));
- expect(unit.declarations, hasLength(0));
- }
-
- void test_parseCompilationUnit_empty() {
- CompilationUnit unit = ParserTestCase.parse4("parseCompilationUnit", "");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(0));
- expect(unit.declarations, hasLength(0));
- }
-
- void test_parseCompilationUnit_exportAsPrefix() {
- CompilationUnit unit = ParserTestCase.parse4(
- "parseCompilationUnit",
- "export.A _export = new export.A();");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(0));
- expect(unit.declarations, hasLength(1));
- }
-
- void test_parseCompilationUnit_exportAsPrefix_parameterized() {
- CompilationUnit unit = ParserTestCase.parse4(
- "parseCompilationUnit",
- "export<dynamic> _export = new export.A();");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(0));
- expect(unit.declarations, hasLength(1));
- }
-
- void test_parseCompilationUnit_operatorAsPrefix_parameterized() {
- CompilationUnit unit = ParserTestCase.parse4(
- "parseCompilationUnit",
- "operator<dynamic> _operator = new operator.A();");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(0));
- expect(unit.declarations, hasLength(1));
- }
-
- void test_parseCompilationUnit_script() {
- CompilationUnit unit =
- ParserTestCase.parse4("parseCompilationUnit", "#! /bin/dart");
- expect(unit.scriptTag, isNotNull);
- expect(unit.directives, hasLength(0));
- expect(unit.declarations, hasLength(0));
- }
-
- void test_parseCompilationUnit_skipFunctionBody_withInterpolation() {
- ParserTestCase.parseFunctionBodies = false;
- CompilationUnit unit =
- ParserTestCase.parse4("parseCompilationUnit", "f() { '\${n}'; }");
- expect(unit.scriptTag, isNull);
- expect(unit.declarations, hasLength(1));
- }
-
- void test_parseCompilationUnit_topLevelDeclaration() {
- CompilationUnit unit =
- ParserTestCase.parse4("parseCompilationUnit", "class A {}");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(0));
- expect(unit.declarations, hasLength(1));
- }
-
- void test_parseCompilationUnit_typedefAsPrefix() {
- CompilationUnit unit = ParserTestCase.parse4(
- "parseCompilationUnit",
- "typedef.A _typedef = new typedef.A();");
- expect(unit.scriptTag, isNull);
- expect(unit.directives, hasLength(0));
- expect(unit.declarations, hasLength(1));
- }
-
void test_parseCompilationUnitMember_abstractAsPrefix() {
TopLevelVariableDeclaration declaration = ParserTestCase.parse(
"parseCompilationUnitMember",
@@ -7363,6 +7257,116 @@
expect(declaration.variables, isNotNull);
}
+ void test_parseCompilationUnit_abstractAsPrefix_parameterized() {
+ CompilationUnit unit = ParserTestCase.parse4(
+ "parseCompilationUnit",
+ "abstract<dynamic> _abstract = new abstract.A();");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(0));
+ expect(unit.declarations, hasLength(1));
+ }
+
+ void test_parseCompilationUnit_builtIn_asFunctionName() {
+ ParserTestCase.parse4("parseCompilationUnit", "abstract(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "as(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "dynamic(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "export(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "external(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "factory(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "get(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "implements(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "import(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "library(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "operator(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "part(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "set(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "static(x) => 0;");
+ ParserTestCase.parse4("parseCompilationUnit", "typedef(x) => 0;");
+ }
+
+ void test_parseCompilationUnit_directives_multiple() {
+ CompilationUnit unit =
+ ParserTestCase.parse4("parseCompilationUnit", "library l;\npart 'a.dart';");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(2));
+ expect(unit.declarations, hasLength(0));
+ }
+
+ void test_parseCompilationUnit_directives_single() {
+ CompilationUnit unit =
+ ParserTestCase.parse4("parseCompilationUnit", "library l;");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(1));
+ expect(unit.declarations, hasLength(0));
+ }
+
+ void test_parseCompilationUnit_empty() {
+ CompilationUnit unit = ParserTestCase.parse4("parseCompilationUnit", "");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(0));
+ expect(unit.declarations, hasLength(0));
+ }
+
+ void test_parseCompilationUnit_exportAsPrefix() {
+ CompilationUnit unit = ParserTestCase.parse4(
+ "parseCompilationUnit",
+ "export.A _export = new export.A();");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(0));
+ expect(unit.declarations, hasLength(1));
+ }
+
+ void test_parseCompilationUnit_exportAsPrefix_parameterized() {
+ CompilationUnit unit = ParserTestCase.parse4(
+ "parseCompilationUnit",
+ "export<dynamic> _export = new export.A();");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(0));
+ expect(unit.declarations, hasLength(1));
+ }
+
+ void test_parseCompilationUnit_operatorAsPrefix_parameterized() {
+ CompilationUnit unit = ParserTestCase.parse4(
+ "parseCompilationUnit",
+ "operator<dynamic> _operator = new operator.A();");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(0));
+ expect(unit.declarations, hasLength(1));
+ }
+
+ void test_parseCompilationUnit_script() {
+ CompilationUnit unit =
+ ParserTestCase.parse4("parseCompilationUnit", "#! /bin/dart");
+ expect(unit.scriptTag, isNotNull);
+ expect(unit.directives, hasLength(0));
+ expect(unit.declarations, hasLength(0));
+ }
+
+ void test_parseCompilationUnit_skipFunctionBody_withInterpolation() {
+ ParserTestCase.parseFunctionBodies = false;
+ CompilationUnit unit =
+ ParserTestCase.parse4("parseCompilationUnit", "f() { '\${n}'; }");
+ expect(unit.scriptTag, isNull);
+ expect(unit.declarations, hasLength(1));
+ }
+
+ void test_parseCompilationUnit_topLevelDeclaration() {
+ CompilationUnit unit =
+ ParserTestCase.parse4("parseCompilationUnit", "class A {}");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(0));
+ expect(unit.declarations, hasLength(1));
+ }
+
+ void test_parseCompilationUnit_typedefAsPrefix() {
+ CompilationUnit unit = ParserTestCase.parse4(
+ "parseCompilationUnit",
+ "typedef.A _typedef = new typedef.A();");
+ expect(unit.scriptTag, isNull);
+ expect(unit.directives, hasLength(0));
+ expect(unit.declarations, hasLength(1));
+ }
+
void test_parseConditionalExpression() {
ConditionalExpression expression =
ParserTestCase.parse4("parseConditionalExpression", "x ? y : z");
@@ -7431,33 +7435,6 @@
// null, null, null, null, null, null}, "");
}
- void test_parseConstructor_with_pseudo_function_literal() {
- // "(b) {}" should not be misinterpreted as a function literal even though
- // it looks like one.
- ClassMember classMember =
- ParserTestCase.parse("parseClassMember", <Object>["C"], "C() : a = (b) {}");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is ConstructorDeclaration,
- ConstructorDeclaration,
- classMember);
- ConstructorDeclaration constructor = classMember as ConstructorDeclaration;
- NodeList<ConstructorInitializer> initializers = constructor.initializers;
- expect(initializers, hasLength(1));
- ConstructorInitializer initializer = initializers[0];
- EngineTestCase.assertInstanceOf(
- (obj) => obj is ConstructorFieldInitializer,
- ConstructorFieldInitializer,
- initializer);
- EngineTestCase.assertInstanceOf(
- (obj) => obj is ParenthesizedExpression,
- ParenthesizedExpression,
- (initializer as ConstructorFieldInitializer).expression);
- EngineTestCase.assertInstanceOf(
- (obj) => obj is BlockFunctionBody,
- BlockFunctionBody,
- constructor.body);
- }
-
void test_parseConstructorFieldInitializer_qualified() {
ConstructorFieldInitializer invocation =
ParserTestCase.parse4("parseConstructorFieldInitializer", "this.a = b");
@@ -7509,6 +7486,33 @@
expect(name.name, isNull);
}
+ void test_parseConstructor_with_pseudo_function_literal() {
+ // "(b) {}" should not be misinterpreted as a function literal even though
+ // it looks like one.
+ ClassMember classMember =
+ ParserTestCase.parse("parseClassMember", <Object>["C"], "C() : a = (b) {}");
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is ConstructorDeclaration,
+ ConstructorDeclaration,
+ classMember);
+ ConstructorDeclaration constructor = classMember as ConstructorDeclaration;
+ NodeList<ConstructorInitializer> initializers = constructor.initializers;
+ expect(initializers, hasLength(1));
+ ConstructorInitializer initializer = initializers[0];
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is ConstructorFieldInitializer,
+ ConstructorFieldInitializer,
+ initializer);
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is ParenthesizedExpression,
+ ParenthesizedExpression,
+ (initializer as ConstructorFieldInitializer).expression);
+ EngineTestCase.assertInstanceOf(
+ (obj) => obj is BlockFunctionBody,
+ BlockFunctionBody,
+ constructor.body);
+ }
+
void test_parseContinueStatement_label() {
ContinueStatement statement = ParserTestCase.parse4(
"parseContinueStatement",
@@ -7628,6 +7632,18 @@
expect(unit.directives, hasLength(0));
}
+ void test_parseDoStatement() {
+ DoStatement statement =
+ ParserTestCase.parse4("parseDoStatement", "do {} while (x);");
+ expect(statement.doKeyword, isNotNull);
+ expect(statement.body, isNotNull);
+ expect(statement.whileKeyword, isNotNull);
+ expect(statement.leftParenthesis, isNotNull);
+ expect(statement.condition, isNotNull);
+ expect(statement.rightParenthesis, isNotNull);
+ expect(statement.semicolon, isNotNull);
+ }
+
void test_parseDocumentationComment_block() {
Comment comment =
ParserTestCase.parse4("parseDocumentationComment", "/** */ class");
@@ -7657,18 +7673,6 @@
expect(comment.isEndOfLine, isFalse);
}
- void test_parseDoStatement() {
- DoStatement statement =
- ParserTestCase.parse4("parseDoStatement", "do {} while (x);");
- expect(statement.doKeyword, isNotNull);
- expect(statement.body, isNotNull);
- expect(statement.whileKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.condition, isNotNull);
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.semicolon, isNotNull);
- }
-
void test_parseEmptyStatement() {
EmptyStatement statement =
ParserTestCase.parse4("parseEmptyStatement", ";");
@@ -7790,6 +7794,44 @@
expect(directive.semicolon, isNotNull);
}
+ void test_parseExpressionList_multiple() {
+ List<Expression> result =
+ ParserTestCase.parse4("parseExpressionList", "1, 2, 3");
+ expect(result, hasLength(3));
+ }
+
+ void test_parseExpressionList_single() {
+ List<Expression> result = ParserTestCase.parse4("parseExpressionList", "1");
+ expect(result, hasLength(1));
+ }
+
+ void test_parseExpressionWithoutCascade_assign() {
+ // TODO(brianwilkerson) Implement more tests for this method.
+ AssignmentExpression expression =
+ ParserTestCase.parse4("parseExpressionWithoutCascade", "x = y");
+ expect(expression.leftHandSide, isNotNull);
+ expect(expression.operator, isNotNull);
+ expect(expression.operator.type, TokenType.EQ);
+ expect(expression.rightHandSide, isNotNull);
+ }
+
+ void test_parseExpressionWithoutCascade_comparison() {
+ BinaryExpression expression =
+ ParserTestCase.parse4("parseExpressionWithoutCascade", "--a.b == c");
+ expect(expression.leftOperand, isNotNull);
+ expect(expression.operator, isNotNull);
+ expect(expression.operator.type, TokenType.EQ_EQ);
+ expect(expression.rightOperand, isNotNull);
+ }
+
+ void test_parseExpressionWithoutCascade_superMethodInvocation() {
+ MethodInvocation invocation =
+ ParserTestCase.parse4("parseExpressionWithoutCascade", "super.m()");
+ expect(invocation.target, isNotNull);
+ expect(invocation.methodName, isNotNull);
+ expect(invocation.argumentList, isNotNull);
+ }
+
void test_parseExpression_assign() {
// TODO(brianwilkerson) Implement more tests for this method.
AssignmentExpression expression =
@@ -7872,44 +7914,6 @@
expect(invocation.argumentList, isNotNull);
}
- void test_parseExpressionList_multiple() {
- List<Expression> result =
- ParserTestCase.parse4("parseExpressionList", "1, 2, 3");
- expect(result, hasLength(3));
- }
-
- void test_parseExpressionList_single() {
- List<Expression> result = ParserTestCase.parse4("parseExpressionList", "1");
- expect(result, hasLength(1));
- }
-
- void test_parseExpressionWithoutCascade_assign() {
- // TODO(brianwilkerson) Implement more tests for this method.
- AssignmentExpression expression =
- ParserTestCase.parse4("parseExpressionWithoutCascade", "x = y");
- expect(expression.leftHandSide, isNotNull);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.EQ);
- expect(expression.rightHandSide, isNotNull);
- }
-
- void test_parseExpressionWithoutCascade_comparison() {
- BinaryExpression expression =
- ParserTestCase.parse4("parseExpressionWithoutCascade", "--a.b == c");
- expect(expression.leftOperand, isNotNull);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.EQ_EQ);
- expect(expression.rightOperand, isNotNull);
- }
-
- void test_parseExpressionWithoutCascade_superMethodInvocation() {
- MethodInvocation invocation =
- ParserTestCase.parse4("parseExpressionWithoutCascade", "super.m()");
- expect(invocation.target, isNotNull);
- expect(invocation.methodName, isNotNull);
- expect(invocation.argumentList, isNotNull);
- }
-
void test_parseExtendsClause() {
ExtendsClause clause =
ParserTestCase.parse4("parseExtendsClause", "extends B");
@@ -7987,16 +7991,16 @@
expect(result.type, isNotNull);
}
- void test_parseFinalConstVarOrType_type_prefixed_noIdentifier() {
+ void test_parseFinalConstVarOrType_type_prefixedAndParameterized() {
FinalConstVarOrType result =
- ParserTestCase.parse("parseFinalConstVarOrType", <Object>[false], "p.A,");
+ ParserTestCase.parse("parseFinalConstVarOrType", <Object>[false], "p.A<B> a");
expect(result.keyword, isNull);
expect(result.type, isNotNull);
}
- void test_parseFinalConstVarOrType_type_prefixedAndParameterized() {
+ void test_parseFinalConstVarOrType_type_prefixed_noIdentifier() {
FinalConstVarOrType result =
- ParserTestCase.parse("parseFinalConstVarOrType", <Object>[false], "p.A<B> a");
+ ParserTestCase.parse("parseFinalConstVarOrType", <Object>[false], "p.A,");
expect(result.keyword, isNull);
expect(result.type, isNotNull);
}
@@ -8032,221 +8036,6 @@
expect(result.type, isNotNull);
}
- void test_parseFormalParameter_final_withType_named() {
- ParameterKind kind = ParameterKind.NAMED;
- DefaultFormalParameter parameter = ParserTestCase.parse(
- "parseFormalParameter",
- <Object>[kind],
- "final A a : null");
- SimpleFormalParameter simpleParameter =
- parameter.parameter as SimpleFormalParameter;
- expect(simpleParameter.identifier, isNotNull);
- expect(simpleParameter.keyword, isNotNull);
- expect(simpleParameter.type, isNotNull);
- expect(simpleParameter.kind, kind);
- expect(parameter.separator, isNotNull);
- expect(parameter.defaultValue, isNotNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameter_final_withType_normal() {
- ParameterKind kind = ParameterKind.REQUIRED;
- SimpleFormalParameter parameter =
- ParserTestCase.parse("parseFormalParameter", <Object>[kind], "final A a");
- expect(parameter.identifier, isNotNull);
- expect(parameter.keyword, isNotNull);
- expect(parameter.type, isNotNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameter_final_withType_positional() {
- ParameterKind kind = ParameterKind.POSITIONAL;
- DefaultFormalParameter parameter = ParserTestCase.parse(
- "parseFormalParameter",
- <Object>[kind],
- "final A a = null");
- SimpleFormalParameter simpleParameter =
- parameter.parameter as SimpleFormalParameter;
- expect(simpleParameter.identifier, isNotNull);
- expect(simpleParameter.keyword, isNotNull);
- expect(simpleParameter.type, isNotNull);
- expect(simpleParameter.kind, kind);
- expect(parameter.separator, isNotNull);
- expect(parameter.defaultValue, isNotNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameter_nonFinal_withType_named() {
- ParameterKind kind = ParameterKind.NAMED;
- DefaultFormalParameter parameter =
- ParserTestCase.parse("parseFormalParameter", <Object>[kind], "A a : null");
- SimpleFormalParameter simpleParameter =
- parameter.parameter as SimpleFormalParameter;
- expect(simpleParameter.identifier, isNotNull);
- expect(simpleParameter.keyword, isNull);
- expect(simpleParameter.type, isNotNull);
- expect(simpleParameter.kind, kind);
- expect(parameter.separator, isNotNull);
- expect(parameter.defaultValue, isNotNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameter_nonFinal_withType_normal() {
- ParameterKind kind = ParameterKind.REQUIRED;
- SimpleFormalParameter parameter =
- ParserTestCase.parse("parseFormalParameter", <Object>[kind], "A a");
- expect(parameter.identifier, isNotNull);
- expect(parameter.keyword, isNull);
- expect(parameter.type, isNotNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameter_nonFinal_withType_positional() {
- ParameterKind kind = ParameterKind.POSITIONAL;
- DefaultFormalParameter parameter =
- ParserTestCase.parse("parseFormalParameter", <Object>[kind], "A a = null");
- SimpleFormalParameter simpleParameter =
- parameter.parameter as SimpleFormalParameter;
- expect(simpleParameter.identifier, isNotNull);
- expect(simpleParameter.keyword, isNull);
- expect(simpleParameter.type, isNotNull);
- expect(simpleParameter.kind, kind);
- expect(parameter.separator, isNotNull);
- expect(parameter.defaultValue, isNotNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameter_var() {
- ParameterKind kind = ParameterKind.REQUIRED;
- SimpleFormalParameter parameter =
- ParserTestCase.parse("parseFormalParameter", <Object>[kind], "var a");
- expect(parameter.identifier, isNotNull);
- expect(parameter.keyword, isNotNull);
- expect(parameter.type, isNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameter_var_named() {
- ParameterKind kind = ParameterKind.NAMED;
- DefaultFormalParameter parameter =
- ParserTestCase.parse("parseFormalParameter", <Object>[kind], "var a : null");
- SimpleFormalParameter simpleParameter =
- parameter.parameter as SimpleFormalParameter;
- expect(simpleParameter.identifier, isNotNull);
- expect(simpleParameter.keyword, isNotNull);
- expect(simpleParameter.type, isNull);
- expect(simpleParameter.kind, kind);
- expect(parameter.separator, isNotNull);
- expect(parameter.defaultValue, isNotNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameter_var_positional() {
- ParameterKind kind = ParameterKind.POSITIONAL;
- DefaultFormalParameter parameter =
- ParserTestCase.parse("parseFormalParameter", <Object>[kind], "var a = null");
- SimpleFormalParameter simpleParameter =
- parameter.parameter as SimpleFormalParameter;
- expect(simpleParameter.identifier, isNotNull);
- expect(simpleParameter.keyword, isNotNull);
- expect(simpleParameter.type, isNull);
- expect(simpleParameter.kind, kind);
- expect(parameter.separator, isNotNull);
- expect(parameter.defaultValue, isNotNull);
- expect(parameter.kind, kind);
- }
-
- void test_parseFormalParameterList_empty() {
- FormalParameterList parameterList =
- ParserTestCase.parse4("parseFormalParameterList", "()");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(0));
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
- void test_parseFormalParameterList_named_multiple() {
- FormalParameterList parameterList =
- ParserTestCase.parse4("parseFormalParameterList", "({A a : 1, B b, C c : 3})");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(3));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
- void test_parseFormalParameterList_named_single() {
- FormalParameterList parameterList =
- ParserTestCase.parse4("parseFormalParameterList", "({A a})");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
- void test_parseFormalParameterList_normal_multiple() {
- FormalParameterList parameterList =
- ParserTestCase.parse4("parseFormalParameterList", "(A a, B b, C c)");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(3));
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
- void test_parseFormalParameterList_normal_named() {
- FormalParameterList parameterList =
- ParserTestCase.parse4("parseFormalParameterList", "(A a, {B b})");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(2));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
- void test_parseFormalParameterList_normal_positional() {
- FormalParameterList parameterList =
- ParserTestCase.parse4("parseFormalParameterList", "(A a, [B b])");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(2));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
- void test_parseFormalParameterList_normal_single() {
- FormalParameterList parameterList =
- ParserTestCase.parse4("parseFormalParameterList", "(A a)");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
- void test_parseFormalParameterList_positional_multiple() {
- FormalParameterList parameterList = ParserTestCase.parse4(
- "parseFormalParameterList",
- "([A a = null, B b, C c = null])");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(3));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
- void test_parseFormalParameterList_positional_single() {
- FormalParameterList parameterList =
- ParserTestCase.parse4("parseFormalParameterList", "([A a = null])");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
- }
-
void test_parseForStatement_each_await() {
ForEachStatement statement =
ParserTestCase.parse4("parseForStatement", "await for (element in list) {}");
@@ -8484,6 +8273,221 @@
expect(statement.body, isNotNull);
}
+ void test_parseFormalParameterList_empty() {
+ FormalParameterList parameterList =
+ ParserTestCase.parse4("parseFormalParameterList", "()");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNull);
+ expect(parameterList.parameters, hasLength(0));
+ expect(parameterList.rightDelimiter, isNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameterList_named_multiple() {
+ FormalParameterList parameterList =
+ ParserTestCase.parse4("parseFormalParameterList", "({A a : 1, B b, C c : 3})");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNotNull);
+ expect(parameterList.parameters, hasLength(3));
+ expect(parameterList.rightDelimiter, isNotNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameterList_named_single() {
+ FormalParameterList parameterList =
+ ParserTestCase.parse4("parseFormalParameterList", "({A a})");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNotNull);
+ expect(parameterList.parameters, hasLength(1));
+ expect(parameterList.rightDelimiter, isNotNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameterList_normal_multiple() {
+ FormalParameterList parameterList =
+ ParserTestCase.parse4("parseFormalParameterList", "(A a, B b, C c)");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNull);
+ expect(parameterList.parameters, hasLength(3));
+ expect(parameterList.rightDelimiter, isNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameterList_normal_named() {
+ FormalParameterList parameterList =
+ ParserTestCase.parse4("parseFormalParameterList", "(A a, {B b})");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNotNull);
+ expect(parameterList.parameters, hasLength(2));
+ expect(parameterList.rightDelimiter, isNotNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameterList_normal_positional() {
+ FormalParameterList parameterList =
+ ParserTestCase.parse4("parseFormalParameterList", "(A a, [B b])");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNotNull);
+ expect(parameterList.parameters, hasLength(2));
+ expect(parameterList.rightDelimiter, isNotNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameterList_normal_single() {
+ FormalParameterList parameterList =
+ ParserTestCase.parse4("parseFormalParameterList", "(A a)");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNull);
+ expect(parameterList.parameters, hasLength(1));
+ expect(parameterList.rightDelimiter, isNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameterList_positional_multiple() {
+ FormalParameterList parameterList = ParserTestCase.parse4(
+ "parseFormalParameterList",
+ "([A a = null, B b, C c = null])");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNotNull);
+ expect(parameterList.parameters, hasLength(3));
+ expect(parameterList.rightDelimiter, isNotNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameterList_positional_single() {
+ FormalParameterList parameterList =
+ ParserTestCase.parse4("parseFormalParameterList", "([A a = null])");
+ expect(parameterList.leftParenthesis, isNotNull);
+ expect(parameterList.leftDelimiter, isNotNull);
+ expect(parameterList.parameters, hasLength(1));
+ expect(parameterList.rightDelimiter, isNotNull);
+ expect(parameterList.rightParenthesis, isNotNull);
+ }
+
+ void test_parseFormalParameter_final_withType_named() {
+ ParameterKind kind = ParameterKind.NAMED;
+ DefaultFormalParameter parameter = ParserTestCase.parse(
+ "parseFormalParameter",
+ <Object>[kind],
+ "final A a : null");
+ SimpleFormalParameter simpleParameter =
+ parameter.parameter as SimpleFormalParameter;
+ expect(simpleParameter.identifier, isNotNull);
+ expect(simpleParameter.keyword, isNotNull);
+ expect(simpleParameter.type, isNotNull);
+ expect(simpleParameter.kind, kind);
+ expect(parameter.separator, isNotNull);
+ expect(parameter.defaultValue, isNotNull);
+ expect(parameter.kind, kind);
+ }
+
+ void test_parseFormalParameter_final_withType_normal() {
+ ParameterKind kind = ParameterKind.REQUIRED;
+ SimpleFormalParameter parameter =
+ ParserTestCase.parse("parseFormalParameter", <Object>[kind], "final A a");
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.keyword, isNotNull);
+ expect(parameter.type, isNotNull);
+ expect(parameter.kind, kind);
+ }
+
+ void test_parseFormalParameter_final_withType_positional() {
+ ParameterKind kind = ParameterKind.POSITIONAL;
+ DefaultFormalParameter parameter = ParserTestCase.parse(
+ "parseFormalParameter",
+ <Object>[kind],
+ "final A a = null");
+ SimpleFormalParameter simpleParameter =
+ parameter.parameter as SimpleFormalParameter;
+ expect(simpleParameter.identifier, isNotNull);
+ expect(simpleParameter.keyword, isNotNull);
+ expect(simpleParameter.type, isNotNull);
+ expect(simpleParameter.kind, kind);
+ expect(parameter.separator, isNotNull);
+ expect(parameter.defaultValue, isNotNull);
+ expect(parameter.kind, kind);
+ }
+
+ void test_parseFormalParameter_nonFinal_withType_named() {
+ ParameterKind kind = ParameterKind.NAMED;
+ DefaultFormalParameter parameter =
+ ParserTestCase.parse("parseFormalParameter", <Object>[kind], "A a : null");
+ SimpleFormalParameter simpleParameter =
+ parameter.parameter as SimpleFormalParameter;
+ expect(simpleParameter.identifier, isNotNull);
+ expect(simpleParameter.keyword, isNull);
+ expect(simpleParameter.type, isNotNull);
+ expect(simpleParameter.kind, kind);
+ expect(parameter.separator, isNotNull);
+ expect(parameter.defaultValue, isNotNull);
+ expect(parameter.kind, kind);
+ }
+
+ void test_parseFormalParameter_nonFinal_withType_normal() {
+ ParameterKind kind = ParameterKind.REQUIRED;
+ SimpleFormalParameter parameter =
+ ParserTestCase.parse("parseFormalParameter", <Object>[kind], "A a");
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.keyword, isNull);
+ expect(parameter.type, isNotNull);
+ expect(parameter.kind, kind);
+ }
+
+ void test_parseFormalParameter_nonFinal_withType_positional() {
+ ParameterKind kind = ParameterKind.POSITIONAL;
+ DefaultFormalParameter parameter =
+ ParserTestCase.parse("parseFormalParameter", <Object>[kind], "A a = null");
+ SimpleFormalParameter simpleParameter =
+ parameter.parameter as SimpleFormalParameter;
+ expect(simpleParameter.identifier, isNotNull);
+ expect(simpleParameter.keyword, isNull);
+ expect(simpleParameter.type, isNotNull);
+ expect(simpleParameter.kind, kind);
+ expect(parameter.separator, isNotNull);
+ expect(parameter.defaultValue, isNotNull);
+ expect(parameter.kind, kind);
+ }
+
+ void test_parseFormalParameter_var() {
+ ParameterKind kind = ParameterKind.REQUIRED;
+ SimpleFormalParameter parameter =
+ ParserTestCase.parse("parseFormalParameter", <Object>[kind], "var a");
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.keyword, isNotNull);
+ expect(parameter.type, isNull);
+ expect(parameter.kind, kind);
+ }
+
+ void test_parseFormalParameter_var_named() {
+ ParameterKind kind = ParameterKind.NAMED;
+ DefaultFormalParameter parameter =
+ ParserTestCase.parse("parseFormalParameter", <Object>[kind], "var a : null");
+ SimpleFormalParameter simpleParameter =
+ parameter.parameter as SimpleFormalParameter;
+ expect(simpleParameter.identifier, isNotNull);
+ expect(simpleParameter.keyword, isNotNull);
+ expect(simpleParameter.type, isNull);
+ expect(simpleParameter.kind, kind);
+ expect(parameter.separator, isNotNull);
+ expect(parameter.defaultValue, isNotNull);
+ expect(parameter.kind, kind);
+ }
+
+ void test_parseFormalParameter_var_positional() {
+ ParameterKind kind = ParameterKind.POSITIONAL;
+ DefaultFormalParameter parameter =
+ ParserTestCase.parse("parseFormalParameter", <Object>[kind], "var a = null");
+ SimpleFormalParameter simpleParameter =
+ parameter.parameter as SimpleFormalParameter;
+ expect(simpleParameter.identifier, isNotNull);
+ expect(simpleParameter.keyword, isNotNull);
+ expect(simpleParameter.type, isNull);
+ expect(simpleParameter.kind, kind);
+ expect(parameter.separator, isNotNull);
+ expect(parameter.defaultValue, isNotNull);
+ expect(parameter.kind, kind);
+ }
+
void test_parseFunctionBody_block() {
BlockFunctionBody functionBody =
ParserTestCase.parse("parseFunctionBody", <Object>[false, null, false], "{}");
@@ -8629,6 +8633,13 @@
functionBody);
}
+ void test_parseFunctionDeclarationStatement() {
+ FunctionDeclarationStatement statement = ParserTestCase.parse4(
+ "parseFunctionDeclarationStatement",
+ "void f(int p) => p * 2;");
+ expect(statement.functionDeclaration, isNotNull);
+ }
+
void test_parseFunctionDeclaration_function() {
Comment comment = Comment.createDocumentationComment(new List<Token>(0));
TypeName returnType = new TypeName(new SimpleIdentifier(null), null);
@@ -8680,13 +8691,6 @@
expect(declaration.propertyKeyword, isNotNull);
}
- void test_parseFunctionDeclarationStatement() {
- FunctionDeclarationStatement statement = ParserTestCase.parse4(
- "parseFunctionDeclarationStatement",
- "void f(int p) => p * 2;");
- expect(statement.functionDeclaration, isNotNull);
- }
-
void test_parseFunctionExpression_body_inExpression() {
FunctionExpression expression =
ParserTestCase.parse4("parseFunctionExpression", "(int i) => i++");
@@ -9036,6 +9040,22 @@
expect(literal.rightBracket, isNotNull);
}
+ void test_parseListLiteral_empty_oneToken_withComment() {
+ Token constToken = null;
+ TypeArgumentList typeArguments = null;
+ ListLiteral literal = ParserTestCase.parse(
+ "parseListLiteral",
+ <Object>[constToken, typeArguments],
+ "/* 0 */ []");
+ expect(literal.constKeyword, constToken);
+ expect(literal.typeArguments, typeArguments);
+ Token leftBracket = literal.leftBracket;
+ expect(leftBracket, isNotNull);
+ expect(leftBracket.precedingComments, isNotNull);
+ expect(literal.elements, hasLength(0));
+ expect(literal.rightBracket, isNotNull);
+ }
+
void test_parseListLiteral_empty_twoTokens() {
Token token = TokenFactory.tokenFromKeyword(Keyword.CONST);
TypeArgumentList typeArguments = null;
@@ -9130,6 +9150,30 @@
expect(expression.rightOperand, isNotNull);
}
+ void test_parseMapLiteralEntry_complex() {
+ MapLiteralEntry entry =
+ ParserTestCase.parse4("parseMapLiteralEntry", "2 + 2 : y");
+ expect(entry.key, isNotNull);
+ expect(entry.separator, isNotNull);
+ expect(entry.value, isNotNull);
+ }
+
+ void test_parseMapLiteralEntry_int() {
+ MapLiteralEntry entry =
+ ParserTestCase.parse4("parseMapLiteralEntry", "0 : y");
+ expect(entry.key, isNotNull);
+ expect(entry.separator, isNotNull);
+ expect(entry.value, isNotNull);
+ }
+
+ void test_parseMapLiteralEntry_string() {
+ MapLiteralEntry entry =
+ ParserTestCase.parse4("parseMapLiteralEntry", "'x' : y");
+ expect(entry.key, isNotNull);
+ expect(entry.separator, isNotNull);
+ expect(entry.value, isNotNull);
+ }
+
void test_parseMapLiteral_empty() {
Token token = TokenFactory.tokenFromKeyword(Keyword.CONST);
TypeArgumentList typeArguments = AstFactory.typeArgumentList(
@@ -9161,30 +9205,6 @@
expect(literal.rightBracket, isNotNull);
}
- void test_parseMapLiteralEntry_complex() {
- MapLiteralEntry entry =
- ParserTestCase.parse4("parseMapLiteralEntry", "2 + 2 : y");
- expect(entry.key, isNotNull);
- expect(entry.separator, isNotNull);
- expect(entry.value, isNotNull);
- }
-
- void test_parseMapLiteralEntry_int() {
- MapLiteralEntry entry =
- ParserTestCase.parse4("parseMapLiteralEntry", "0 : y");
- expect(entry.key, isNotNull);
- expect(entry.separator, isNotNull);
- expect(entry.value, isNotNull);
- }
-
- void test_parseMapLiteralEntry_string() {
- MapLiteralEntry entry =
- ParserTestCase.parse4("parseMapLiteralEntry", "'x' : y");
- expect(entry.key, isNotNull);
- expect(entry.separator, isNotNull);
- expect(entry.value, isNotNull);
- }
-
void test_parseModifiers_abstract() {
Modifiers modifiers = ParserTestCase.parse4("parseModifiers", "abstract A");
expect(modifiers.abstractKeyword, isNotNull);
@@ -9771,10 +9791,6 @@
expect(literal.value, isTrue);
}
- void test_Parser() {
- expect(new Parser(null, null), isNotNull);
- }
-
void test_parseRedirectingConstructorInvocation_named() {
RedirectingConstructorInvocation invocation =
ParserTestCase.parse4("parseRedirectingConstructorInvocation", "this.a()");
@@ -10361,6 +10377,51 @@
expect(argumentList.rightBracket, isNotNull);
}
+ void test_parseTypeArgumentList_nested_withComment_double() {
+ TypeArgumentList argumentList =
+ ParserTestCase.parse4("parseTypeArgumentList", "<A<B /* 0 */ >>");
+ expect(argumentList.leftBracket, isNotNull);
+ expect(argumentList.rightBracket, isNotNull);
+ expect(argumentList.arguments, hasLength(1));
+
+ TypeName argument = argumentList.arguments[0];
+ expect(argument, isNotNull);
+
+ TypeArgumentList innerList = argument.typeArguments;
+ expect(innerList, isNotNull);
+ expect(innerList.leftBracket, isNotNull);
+ expect(innerList.arguments, hasLength(1));
+ expect(innerList.rightBracket, isNotNull);
+ expect(innerList.rightBracket.precedingComments, isNotNull);
+ }
+
+ void test_parseTypeArgumentList_nested_withComment_tripple() {
+ TypeArgumentList argumentList =
+ ParserTestCase.parse4("parseTypeArgumentList", "<A<B<C /* 0 */ >>>");
+ expect(argumentList.leftBracket, isNotNull);
+ expect(argumentList.rightBracket, isNotNull);
+ expect(argumentList.arguments, hasLength(1));
+
+ TypeName argument = argumentList.arguments[0];
+ expect(argument, isNotNull);
+
+ TypeArgumentList innerList = argument.typeArguments;
+ expect(innerList, isNotNull);
+ expect(innerList.leftBracket, isNotNull);
+ expect(innerList.arguments, hasLength(1));
+ expect(innerList.rightBracket, isNotNull);
+
+ TypeName innerArgument = innerList.arguments[0];
+ expect(innerArgument, isNotNull);
+
+ TypeArgumentList innerInnerList = innerArgument.typeArguments;
+ expect(innerInnerList, isNotNull);
+ expect(innerInnerList.leftBracket, isNotNull);
+ expect(innerInnerList.arguments, hasLength(1));
+ expect(innerInnerList.rightBracket, isNotNull);
+ expect(innerInnerList.rightBracket.precedingComments, isNotNull);
+ }
+
void test_parseTypeArgumentList_single() {
TypeArgumentList argumentList =
ParserTestCase.parse4("parseTypeArgumentList", "<int>");
@@ -10381,21 +10442,6 @@
expect(typeName.typeArguments, isNull);
}
- void test_parseTypeParameter_bounded() {
- TypeParameter parameter =
- ParserTestCase.parse4("parseTypeParameter", "A extends B");
- expect(parameter.bound, isNotNull);
- expect(parameter.keyword, isNotNull);
- expect(parameter.name, isNotNull);
- }
-
- void test_parseTypeParameter_simple() {
- TypeParameter parameter = ParserTestCase.parse4("parseTypeParameter", "A");
- expect(parameter.bound, isNull);
- expect(parameter.keyword, isNull);
- expect(parameter.name, isNotNull);
- }
-
void test_parseTypeParameterList_multiple() {
TypeParameterList parameterList =
ParserTestCase.parse4("parseTypeParameterList", "<A, B extends C, D>");
@@ -10428,6 +10474,21 @@
expect(parameterList.typeParameters, hasLength(1));
}
+ void test_parseTypeParameter_bounded() {
+ TypeParameter parameter =
+ ParserTestCase.parse4("parseTypeParameter", "A extends B");
+ expect(parameter.bound, isNotNull);
+ expect(parameter.keyword, isNotNull);
+ expect(parameter.name, isNotNull);
+ }
+
+ void test_parseTypeParameter_simple() {
+ TypeParameter parameter = ParserTestCase.parse4("parseTypeParameter", "A");
+ expect(parameter.bound, isNull);
+ expect(parameter.keyword, isNull);
+ expect(parameter.name, isNotNull);
+ }
+
void test_parseUnaryExpression_decrement_normal() {
PrefixExpression expression =
ParserTestCase.parse4("parseUnaryExpression", "--x");
@@ -10461,6 +10522,21 @@
expect(operand.propertyName.name, "x");
}
+ void test_parseUnaryExpression_decrement_super_withComment() {
+ PrefixExpression expression =
+ ParserTestCase.parse4("parseUnaryExpression", "/* 0 */ --super");
+ expect(expression.operator, isNotNull);
+ expect(expression.operator.type, TokenType.MINUS);
+ expect(expression.operator.precedingComments, isNotNull);
+ Expression innerExpression = expression.operand;
+ expect(innerExpression, isNotNull);
+ expect(innerExpression is PrefixExpression, isTrue);
+ PrefixExpression operand = innerExpression as PrefixExpression;
+ expect(operand.operator, isNotNull);
+ expect(operand.operator.type, TokenType.MINUS);
+ expect(operand.operand, isNotNull);
+ }
+
void test_parseUnaryExpression_increment_normal() {
PrefixExpression expression =
ParserTestCase.parse4("parseUnaryExpression", "++x");
@@ -10539,22 +10615,6 @@
expect(expression.operand, isNotNull);
}
- void test_parseVariableDeclaration_equals() {
- VariableDeclaration declaration =
- ParserTestCase.parse4("parseVariableDeclaration", "a = b");
- expect(declaration.name, isNotNull);
- expect(declaration.equals, isNotNull);
- expect(declaration.initializer, isNotNull);
- }
-
- void test_parseVariableDeclaration_noEquals() {
- VariableDeclaration declaration =
- ParserTestCase.parse4("parseVariableDeclaration", "a");
- expect(declaration.name, isNotNull);
- expect(declaration.equals, isNull);
- expect(declaration.initializer, isNull);
- }
-
void test_parseVariableDeclarationListAfterMetadata_const_noType() {
VariableDeclarationList declarationList = ParserTestCase.parse(
"parseVariableDeclarationListAfterMetadata",
@@ -10679,6 +10739,22 @@
expect(variableList.variables, hasLength(1));
}
+ void test_parseVariableDeclaration_equals() {
+ VariableDeclaration declaration =
+ ParserTestCase.parse4("parseVariableDeclaration", "a = b");
+ expect(declaration.name, isNotNull);
+ expect(declaration.equals, isNotNull);
+ expect(declaration.initializer, isNotNull);
+ }
+
+ void test_parseVariableDeclaration_noEquals() {
+ VariableDeclaration declaration =
+ ParserTestCase.parse4("parseVariableDeclaration", "a");
+ expect(declaration.name, isNotNull);
+ expect(declaration.equals, isNull);
+ expect(declaration.initializer, isNull);
+ }
+
void test_parseWhileStatement() {
WhileStatement statement =
ParserTestCase.parse4("parseWhileStatement", "while (x) {}");
diff --git a/pkg/analyzer/test/generated/resolver_test.dart b/pkg/analyzer/test/generated/resolver_test.dart
index fb54593..dbebaa5 100644
--- a/pkg/analyzer/test/generated/resolver_test.dart
+++ b/pkg/analyzer/test/generated/resolver_test.dart
@@ -1697,12 +1697,8 @@
void test_visitPrefixedIdentifier_staticClassMember_method() {
ClassElementImpl classA = ElementFactory.classElement2("A");
- // set accessors
- String propName = "m";
- PropertyAccessorElement setter =
- ElementFactory.setterElement(propName, false, _typeProvider.intType);
- classA.accessors = <PropertyAccessorElement>[setter];
// set methods
+ String propName = "m";
MethodElement method =
ElementFactory.methodElement("m", _typeProvider.intType);
classA.methods = <MethodElement>[method];
diff --git a/pkg/analyzer/test/options_test.dart b/pkg/analyzer/test/options_test.dart
index dd65283..4830306 100644
--- a/pkg/analyzer/test/options_test.dart
+++ b/pkg/analyzer/test/options_test.dart
@@ -5,8 +5,11 @@
library options_test;
import 'package:analyzer/options.dart';
+import 'package:args/args.dart';
import 'package:unittest/unittest.dart';
+import 'reflective_tests.dart';
+
main() {
group('AnalyzerOptions.parse()', () {
@@ -110,29 +113,55 @@
});
test('customUrlMappings', () {
- CommandLineOptions options = CommandLineOptions.parse([
- '--dart-sdk', '.',
- '--url-mapping', 'dart:dummy,/path/to/dummy.dart',
- 'foo.dart']);
+ CommandLineOptions options = CommandLineOptions.parse(
+ [
+ '--dart-sdk',
+ '.',
+ '--url-mapping',
+ 'dart:dummy,/path/to/dummy.dart',
+ 'foo.dart']);
expect(options.customUrlMappings, isNotNull);
expect(options.customUrlMappings.isEmpty, isFalse);
- expect(options.customUrlMappings['dart:dummy'],
- equals('/path/to/dummy.dart'));
+ expect(
+ options.customUrlMappings['dart:dummy'],
+ equals('/path/to/dummy.dart'));
});
// test('notice unrecognized flags', () {
-// CommandLineOptions options = new CommandLineOptions.parse(['--bar', '--baz',
+// CommandLineOptions options = CommandLineOptions.parse(['--bar', '--baz',
// 'foo.dart']);
// expect(options, isNull);
// });
-//
-// test('ignore unrecognized flags', () {
-// CommandLineOptions options = new CommandLineOptions.parse([
-// '--ignore_unrecognized_flags', '--bar', '--baz', 'foo.dart']);
-// expect(options, isNotNull);
-// expect(options.sourceFiles, equals(['foo.dart']));
-// });
+
+ test('ignore unrecognized flags', () {
+ CommandLineOptions options = CommandLineOptions.parse(
+ [
+ '--ignore-unrecognized-flags',
+ '--bar',
+ '--baz',
+ '--dart-sdk',
+ '.',
+ 'foo.dart']);
+ expect(options, isNotNull);
+ expect(options.sourceFiles, equals(['foo.dart']));
+ });
});
+ runReflectiveTests(CommandLineParserTest);
+}
+
+
+@reflectiveTest
+class CommandLineParserTest {
+ test_ignoreUnrecognizedOptions() {
+ CommandLineParser parser =
+ new CommandLineParser(alwaysIgnoreUnrecognized: true);
+ parser.addOption('optionA');
+ parser.addFlag('flagA');
+ ArgResults argResults =
+ parser.parse(['--optionA=1', '--optionB=2', '--flagA'], {});
+ expect(argResults['optionA'], '1');
+ expect(argResults['flagA'], isTrue);
+ }
}
diff --git a/pkg/analyzer/test/source/package_map_resolver_test.dart b/pkg/analyzer/test/source/package_map_resolver_test.dart
index 0869c56..cacb186 100644
--- a/pkg/analyzer/test/source/package_map_resolver_test.dart
+++ b/pkg/analyzer/test/source/package_map_resolver_test.dart
@@ -177,6 +177,29 @@
}
}
+ void test_restoreAmbiguous() {
+ const file1 = '/foo1/lib/bar.dart';
+ const file2 = '/foo2/lib/bar.dart';
+ provider.newFile(file1, 'library bar');
+ provider.newFile(file2, 'library bar');
+ PackageMapUriResolver resolver =
+ new PackageMapUriResolver(provider, <String, List<Folder>>{
+ 'foo': [
+ provider.getResource('/foo1/lib'),
+ provider.getResource('/foo2/lib')]
+ });
+ // Restoring file1 should yield a package URI, and that package URI should
+ // resolve back to file1.
+ Source source1 = _createFileSource(file1);
+ Uri uri1 = resolver.restoreAbsolute(source1);
+ expect(uri1.toString(), 'package:foo/bar.dart');
+ expect(resolver.resolveAbsolute(uri1).fullName, file1);
+ // Restoring file2 should not yield a package URI, because there is no URI
+ // that resolves to file2.
+ Source source2 = _createFileSource(file2);
+ expect(resolver.restoreAbsolute(source2), isNull);
+ }
+
Source _createFileSource(String path) {
return new NonExistingSource(path, UriKind.FILE_URI);
}
diff --git a/pkg/async/LICENSE b/pkg/async/LICENSE
deleted file mode 100644
index ee99930..0000000
--- a/pkg/async/LICENSE
+++ /dev/null
@@ -1,26 +0,0 @@
-Copyright 2013, the Dart project authors. All rights reserved.
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials provided
- with the distribution.
- * Neither the name of Google Inc. nor the names of its
- contributors may be used to endorse or promote products derived
- from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pkg/async/README.md b/pkg/async/README.md
deleted file mode 100644
index 73a40f4..0000000
--- a/pkg/async/README.md
+++ /dev/null
@@ -1,19 +0,0 @@
-The `async` package will contain tools to work with asynchronous computations.
-
-The package contains sub-libraries with different utilities.
-
-### Zipping streams
-
-The "stream_zip.dart" sub-library contains functionality
-to combine several streams of events into a single stream of tuples of events.
-
-### Results
-The "result.dart" sub-library introduces a `Result` class that can hold either
-a value or an error.
-It allows capturing an asynchronous computation which can give either a value
-or an error, into an asynchronous computation that always gives a `Result`
-value, where errors can be treated as data.
-It also allows releasing the `Result` back into an asynchronous computation.
-
-### History.
-This package is unrelated to the discontinued `async` package with version 0.1.7.
diff --git a/pkg/async/lib/async.dart b/pkg/async/lib/async.dart
deleted file mode 100644
index 69c7a28..0000000
--- a/pkg/async/lib/async.dart
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) 2013, 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 dart.pkg.async;
-
-export "stream_zip.dart";
-export "result.dart";
diff --git a/pkg/async/lib/result.dart b/pkg/async/lib/result.dart
deleted file mode 100644
index db04ae7..0000000
--- a/pkg/async/lib/result.dart
+++ /dev/null
@@ -1,291 +0,0 @@
-// Copyright (c) 2013, 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.
-
-/**
- * Capture asynchronous results into synchronous values, and release them again.
- *
- * Capturing a result (either a returned value or a thrown error)
- * means converting it into a [Result] -
- * either a [ValueResult] or an [ErrorResult].
- *
- * This value can release itself by writing itself either to a
- * [EventSink] or a [Completer], or by becoming a [Future].
- */
-library dart.pkg.async.results;
-
-import "dart:async";
-
-/**
- * The result of a computation.
- */
-abstract class Result<T> {
- /**
- * Create a `Result` with the result of calling [computation].
- *
- * This generates either a [ValueResult] with the value returned by
- * calling `computation`, or an [ErrorResult] with an error thrown by
- * the call.
- */
- factory Result(T computation()) {
- try {
- return new ValueResult(computation());
- } catch (e, s) {
- return new ErrorResult(e, s);
- }
- }
-
- /**
- * Create a `Result` holding a value.
- *
- * Alias for [ValueResult.ValueResult].
- */
- factory Result.value(T value) = ValueResult<T>;
-
- /**
- * Create a `Result` holding an error.
- *
- * Alias for [ErrorResult.ErrorResult].
- */
- factory Result.error(Object error, [StackTrace stackTrace]) =>
- new ErrorResult(error, stackTrace);
-
- // Helper functions.
- static _captureValue(value) => new ValueResult(value);
- static _captureError(error, stack) => new ErrorResult(error, stack);
- static _release(Result v) {
- if (v.isValue) return v.asValue.value; // Avoid wrapping in future.
- return v.asFuture;
- }
-
- /**
- * Capture the result of a future into a `Result` future.
- *
- * The resulting future will never have an error.
- * Errors have been converted to an [ErrorResult] value.
- */
- static Future<Result> capture(Future future) {
- return future.then(_captureValue, onError: _captureError);
- }
-
- /**
- * Release the result of a captured future.
- *
- * Converts the [Result] value of the given [future] to a value or error
- * completion of the returned future.
- *
- * If [future] completes with an error, the returned future completes with
- * the same error.
- */
- static Future release(Future<Result> future) {
- return future.then(_release);
- }
-
- /**
- * Capture the results of a stream into a stream of [Result] values.
- *
- * The returned stream will not have any error events.
- * Errors from the source stream have been converted to [ErrorResult]s.
- *
- * Shorthand for transforming the stream using [CaptureStreamTransformer].
- */
- static Stream<Result> captureStream(Stream source) {
- return source.transform(const CaptureStreamTransformer());
- }
-
- /**
- * Release a stream of [result] values into a stream of the results.
- *
- * `Result` values of the source stream become value or error events in
- * the retuned stream as appropriate.
- * Errors from the source stream become errors in the returned stream.
- *
- * Shorthand for transforming the stream using [ReleaseStreamTransformer].
- */
- static Stream releaseStream(Stream<Result> source) {
- return source.transform(const ReleaseStreamTransformer());
- }
-
- /**
- * Converts a result of a result to a single result.
- *
- * If the result is an error, or it is a `Result` value
- * which is then an error, then a result with that error is returned.
- * Otherwise both levels of results are value results, and a single
- * result with the value is returned.
- */
- static Result flatten(Result<Result> result) {
- if (result.isError) return result;
- return result.asValue.value;
- }
-
- /**
- * Whether this result is a value result.
- *
- * Always the opposite of [isError].
- */
- bool get isValue;
-
- /**
- * Whether this result is an error result.
- *
- * Always the opposite of [isValue].
- */
- bool get isError;
-
- /**
- * If this is a value result, return itself.
- *
- * Otherwise return `null`.
- */
- ValueResult<T> get asValue;
-
- /**
- * If this is an error result, return itself.
- *
- * Otherwise return `null`.
- */
- ErrorResult get asError;
-
- /**
- * Complete a completer with this result.
- */
- void complete(Completer<T> completer);
-
- /**
- * Add this result to a [StreamSink].
- */
- void addTo(EventSink<T> sink);
-
- /**
- * Creates a future completed with this result as a value or an error.
- */
- Future<T> get asFuture;
-}
-
-/**
- * A result representing a returned value.
- */
-class ValueResult<T> implements Result<T> {
- /** The returned value that this result represents. */
- final T value;
- /** Create a value result with the given [value]. */
- ValueResult(this.value);
- bool get isValue => true;
- bool get isError => false;
- ValueResult<T> get asValue => this;
- ErrorResult get asError => null;
- void complete(Completer<T> completer) {
- completer.complete(value);
- }
- void addTo(EventSink<T> sink) {
- sink.add(value);
- }
- Future<T> get asFuture => new Future.value(value);
-}
-
-/**
- * A result representing a thrown error.
- */
-class ErrorResult implements Result {
- /** The thrown object that this result represents. */
- final error;
- /** The stack trace, if any, associated with the throw. */
- final StackTrace stackTrace;
- /** Create an error result with the given [error] and [stackTrace]. */
- ErrorResult(this.error, this.stackTrace);
- bool get isValue => false;
- bool get isError => true;
- ValueResult get asValue => null;
- ErrorResult get asError => this;
- void complete(Completer completer) {
- completer.completeError(error, stackTrace);
- }
- void addTo(EventSink sink) {
- sink.addError(error, stackTrace);
- }
- Future get asFuture => new Future.error(error, stackTrace);
-}
-
-/**
- * A stream transformer that captures a stream of events into [Result]s.
- *
- * The result of the transformation is a stream of [Result] values and
- * no error events.
- */
-class CaptureStreamTransformer<T> implements StreamTransformer<T, Result<T>> {
- const CaptureStreamTransformer();
-
- Stream<Result<T>> bind(Stream<T> source) {
- return new Stream<Result<T>>.eventTransformed(source, _createSink);
- }
-
- static EventSink _createSink(EventSink<Result> sink) {
- return new CaptureSink(sink);
- }
-}
-
-/**
- * A stream transformer that releases a stream of result events.
- *
- * The result of the transformation is a stream of values and
- * error events.
- */
-class ReleaseStreamTransformer<T> implements StreamTransformer<Result<T>, T> {
- const ReleaseStreamTransformer();
-
- Stream<T> bind(Stream<Result<T>> source) {
- return new Stream<T>.eventTransformed(source, _createSink);
- }
-
- static EventSink<Result> _createSink(EventSink sink) {
- return new ReleaseSink(sink);
- }
-}
-
-/**
- * An event sink wrapper that captures the incoming events.
- *
- * Wraps an [EventSink] that expects [Result] values.
- * Accepts any value and error result,
- * and passes them to the wrapped sink as [Result] values.
- *
- * The wrapped sink will never receive an error event.
- */
-class CaptureSink<T> implements EventSink<T> {
- final EventSink _sink;
-
- CaptureSink(EventSink<Result<T>> sink) : _sink = sink;
- void add(T value) { _sink.add(new ValueResult(value)); }
- void addError(Object error, [StackTrace stackTrace]) {
- _sink.add(new ErrorResult(error, stackTrace));
- }
- void close() { _sink.close(); }
-}
-
-/**
- * An event sink wrapper that releases the incoming result events.
- *
- * Wraps an output [EventSink] that expects any result.
- * Accepts [Result] values, and puts the result value or error into the
- * corresponding output sink add method.
- */
-class ReleaseSink<T> implements EventSink<Result<T>> {
- final EventSink _sink;
- ReleaseSink(EventSink<T> sink) : _sink = sink;
- void add(Result<T> result) {
- if (result.isValue) {
- _sink.add(result.asValue.value);
- } else {
- ErrorResult error = result.asError;
- _sink.addError(error.error, error.stackTrace);
- }
- }
- void addError(Object error, [StackTrace stackTrace]) {
- // Errors may be added by intermediate processing, even if it is never
- // added by CaptureSink.
- _sink.addError(error, stackTrace);
- }
-
- void close() { _sink.close(); }
-}
diff --git a/pkg/async/lib/stream_zip.dart b/pkg/async/lib/stream_zip.dart
deleted file mode 100644
index 055489d..0000000
--- a/pkg/async/lib/stream_zip.dart
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright (c) 2013, 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.
-
-/**
- * Help for combining multiple streams into a single stream.
- */
-library dart.pkg.async.stream_zip;
-
-import "dart:async";
-
-/**
- * A stream that combines the values of other streams.
- */
-class StreamZip extends Stream<List> {
- final Iterable<Stream> _streams;
- StreamZip(Iterable<Stream> streams) : _streams = streams;
-
- StreamSubscription<List> listen(void onData(List data), {
- Function onError,
- void onDone(),
- bool cancelOnError}) {
- cancelOnError = identical(true, cancelOnError);
- List<StreamSubscription> subscriptions = <StreamSubscription>[];
- StreamController controller;
- List current;
- int dataCount = 0;
-
- /// Called for each data from a subscription in [subscriptions].
- void handleData(int index, data) {
- current[index] = data;
- dataCount++;
- if (dataCount == subscriptions.length) {
- List data = current;
- current = new List(subscriptions.length);
- dataCount = 0;
- for (int i = 0; i < subscriptions.length; i++) {
- if (i != index) subscriptions[i].resume();
- }
- controller.add(data);
- } else {
- subscriptions[index].pause();
- }
- }
-
- /// Called for each error from a subscription in [subscriptions].
- /// Except if [cancelOnError] is true, in which case the function below
- /// is used instead.
- void handleError(Object error, StackTrace stackTrace) {
- controller.addError(error, stackTrace);
- }
-
- /// Called when a subscription has an error and [cancelOnError] is true.
- ///
- /// Prematurely cancels all subscriptions since we know that we won't
- /// be needing any more values.
- void handleErrorCancel(Object error, StackTrace stackTrace) {
- for (int i = 0; i < subscriptions.length; i++) {
- subscriptions[i].cancel();
- }
- controller.addError(error, stackTrace);
- }
-
- void handleDone() {
- for (int i = 0; i < subscriptions.length; i++) {
- subscriptions[i].cancel();
- }
- controller.close();
- }
-
- try {
- for (Stream stream in _streams) {
- int index = subscriptions.length;
- subscriptions.add(stream.listen(
- (data) { handleData(index, data); },
- onError: cancelOnError ? handleError : handleErrorCancel,
- onDone: handleDone,
- cancelOnError: cancelOnError));
- }
- } catch (e) {
- for (int i = subscriptions.length - 1; i >= 0; i--) {
- subscriptions[i].cancel();
- }
- rethrow;
- }
-
- current = new List(subscriptions.length);
-
- controller = new StreamController<List>(
- onPause: () {
- for (int i = 0; i < subscriptions.length; i++) {
- // This may pause some subscriptions more than once.
- // These will not be resumed by onResume below, but must wait for the
- // next round.
- subscriptions[i].pause();
- }
- },
- onResume: () {
- for (int i = 0; i < subscriptions.length; i++) {
- subscriptions[i].resume();
- }
- },
- onCancel: () {
- for (int i = 0; i < subscriptions.length; i++) {
- // Canceling more than once is safe.
- subscriptions[i].cancel();
- }
- }
- );
-
- if (subscriptions.isEmpty) {
- controller.close();
- }
- return controller.stream.listen(onData,
- onError: onError,
- onDone: onDone,
- cancelOnError: cancelOnError);
- }
-}
diff --git a/pkg/async/pubspec.yaml b/pkg/async/pubspec.yaml
deleted file mode 100644
index 65539f9..0000000
--- a/pkg/async/pubspec.yaml
+++ /dev/null
@@ -1,9 +0,0 @@
-name: async
-version: 1.0.0
-author: Dart Team <misc@dartlang.org>
-description: Utility functions and classes related to the 'dart:async' library.
-homepage: http://www.dartlang.org
-dev_dependencies:
- unittest: ">=0.10.0 <0.12.0"
-environment:
- sdk: ">=1.0.0 <2.0.0"
diff --git a/pkg/async/test/result_test.dart b/pkg/async/test/result_test.dart
deleted file mode 100644
index 0f2ae0a..0000000
--- a/pkg/async/test/result_test.dart
+++ /dev/null
@@ -1,286 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import "dart:async";
-import "dart:collection";
-import "package:async/result.dart";
-import "package:unittest/unittest.dart";
-
-void main() {
- StackTrace stack;
- try { throw 0; } catch (e, s) { stack = s; }
-
- test("create result value", () {
- Result<int> result = new Result<int>.value(42);
- expect(result.isValue, isTrue);
- expect(result.isError, isFalse);
- ValueResult value = result.asValue;
- expect(value.value, equals(42));
- });
-
- test("create result value 2", () {
- Result<int> result = new ValueResult<int>(42);
- expect(result.isValue, isTrue);
- expect(result.isError, isFalse);
- ValueResult<int> value = result.asValue;
- expect(value.value, equals(42));
- });
-
- test("create result error", () {
- Result<bool> result = new Result<bool>.error("BAD", stack);
- expect(result.isValue, isFalse);
- expect(result.isError, isTrue);
- ErrorResult error = result.asError;
- expect(error.error, equals("BAD"));
- expect(error.stackTrace, same(stack));
- });
-
- test("create result error 2", () {
- Result<bool> result = new ErrorResult("BAD", stack);
- expect(result.isValue, isFalse);
- expect(result.isError, isTrue);
- ErrorResult error = result.asError;
- expect(error.error, equals("BAD"));
- expect(error.stackTrace, same(stack));
- });
-
- test("create result error no stack", () {
- Result<bool> result = new Result<bool>.error("BAD");
- expect(result.isValue, isFalse);
- expect(result.isError, isTrue);
- ErrorResult error = result.asError;
- expect(error.error, equals("BAD"));
- expect(error.stackTrace, isNull);
- });
-
- test("complete with value", () {
- Result<int> result = new ValueResult<int>(42);
- Completer c = new Completer<int>();
- c.future.then(expectAsync((int v) { expect(v, equals(42)); }),
- onError: (e, s) { fail("Unexpected error"); });
- result.complete(c);
- });
-
- test("complete with error", () {
- Result<bool> result = new ErrorResult("BAD", stack);
- Completer c = new Completer<bool>();
- c.future.then((bool v) { fail("Unexpected value $v"); },
- onError: expectAsync((e, s) {
- expect(e, equals("BAD"));
- expect(s, same(stack));
- }));
- result.complete(c);
- });
-
- test("add sink value", () {
- Result<int> result = new ValueResult<int>(42);
- EventSink<int> sink = new TestSink(
- onData: expectAsync((v) { expect(v, equals(42)); })
- );
- result.addTo(sink);
- });
-
- test("add sink error", () {
- Result<bool> result = new ErrorResult("BAD", stack);
- EventSink<bool> sink = new TestSink(
- onError: expectAsync((e, s) {
- expect(e, equals("BAD"));
- expect(s, same(stack));
- })
- );
- result.addTo(sink);
- });
-
- test("value as future", () {
- Result<int> result = new ValueResult<int>(42);
- result.asFuture.then(expectAsync((int v) { expect(v, equals(42)); }),
- onError: (e, s) { fail("Unexpected error"); });
- });
-
- test("error as future", () {
- Result<bool> result = new ErrorResult("BAD", stack);
- result.asFuture.then((bool v) { fail("Unexpected value $v"); },
- onError: expectAsync((e, s) {
- expect(e, equals("BAD"));
- expect(s, same(stack));
- }));
- });
-
- test("capture future value", () {
- Future<int> value = new Future<int>.value(42);
- Result.capture(value).then(expectAsync((Result result) {
- expect(result.isValue, isTrue);
- expect(result.isError, isFalse);
- ValueResult value = result.asValue;
- expect(value.value, equals(42));
- }), onError: (e, s) {
- fail("Unexpected error: $e");
- });
- });
-
- test("capture future error", () {
- Future<bool> value = new Future<bool>.error("BAD", stack);
- Result.capture(value).then(expectAsync((Result result) {
- expect(result.isValue, isFalse);
- expect(result.isError, isTrue);
- ErrorResult error = result.asError;
- expect(error.error, equals("BAD"));
- expect(error.stackTrace, same(stack));
- }), onError: (e, s) {
- fail("Unexpected error: $e");
- });
- });
-
- test("release future value", () {
- Future<Result<int>> future =
- new Future<Result<int>>.value(new Result<int>.value(42));
- Result.release(future).then(expectAsync((v) {
- expect(v, equals(42));
- }), onError: (e, s) {
- fail("Unexpected error: $e");
- });
- });
-
- test("release future error", () {
- // An error in the result is unwrapped and reified by release.
- Future<Result<bool>> future =
- new Future<Result<bool>>.value(new Result<bool>.error("BAD", stack));
- Result.release(future).then((v) {
- fail("Unexpected value: $v");
- }, onError: expectAsync((e, s) {
- expect(e, equals("BAD"));
- expect(s, same(stack));
- }));
- });
-
- test("release future real error", () {
- // An error in the error lane is passed through by release.
- Future<Result<bool>> future = new Future<Result<bool>>.error("BAD", stack);
- Result.release(future).then((v) {
- fail("Unexpected value: $v");
- }, onError: expectAsync((e, s) {
- expect(e, equals("BAD"));
- expect(s, same(stack));
- }));
- });
-
- test("capture stream", () {
- StreamController<int> c = new StreamController<int>();
- Stream<Result> stream = Result.captureStream(c.stream);
- var expectedList = new Queue.from([new Result.value(42),
- new Result.error("BAD", stack),
- new Result.value(37)]);
- void listener(Result actual) {
- expect(expectedList.isEmpty, isFalse);
- expectResult(actual, expectedList.removeFirst());
- }
- stream.listen(expectAsync(listener, count: 3),
- onError: (e, s) { fail("Unexpected error: $e"); },
- onDone: expectAsync((){}),
- cancelOnError: true);
- c.add(42);
- c.addError("BAD", stack);
- c.add(37);
- c.close();
- });
-
- test("release stream", () {
- StreamController<Result<int>> c = new StreamController<Result<int>>();
- Stream<int> stream = Result.releaseStream(c.stream);
- List events = [new Result<int>.value(42),
- new Result<int>.error("BAD", stack),
- new Result<int>.value(37)];
- // Expect the data events, and an extra error event.
- var expectedList = new Queue.from(events)..add(new Result.error("BAD2"));
- void dataListener(int v) {
- expect(expectedList.isEmpty, isFalse);
- Result expected = expectedList.removeFirst();
- expect(expected.isValue, isTrue);
- expect(v, equals(expected.asValue.value));
- }
- void errorListener(error, StackTrace stackTrace) {
- expect(expectedList.isEmpty, isFalse);
- Result expected = expectedList.removeFirst();
- expect(expected.isError, isTrue);
- expect(error, equals(expected.asError.error));
- expect(stackTrace, same(expected.asError.stackTrace));
- }
- stream.listen(expectAsync(dataListener, count: 2),
- onError: expectAsync(errorListener, count: 2),
- onDone: expectAsync((){}));
- for (Result<int> result in events) {
- c.add(result); // Result value or error in data line.
- }
- c.addError("BAD2"); // Error in error line.
- c.close();
- });
-
- test("release stream cancel on error", () {
- StreamController<Result<int>> c = new StreamController<Result<int>>();
- Stream<int> stream = Result.releaseStream(c.stream);
- stream.listen(expectAsync((v) { expect(v, equals(42)); }),
- onError: expectAsync((e, s) {
- expect(e, equals("BAD"));
- expect(s, same(stack));
- }),
- onDone: () { fail("Unexpected done event"); },
- cancelOnError: true);
- c.add(new Result.value(42));
- c.add(new Result.error("BAD", stack));
- c.add(new Result.value(37));
- c.close();
- });
-
-
- test("flatten error 1", () {
- Result<int> error = new Result<int>.error("BAD", stack);
- Result<int> flattened =
- Result.flatten(new Result<Result<int>>.error("BAD", stack));
- expectResult(flattened, error);
- });
-
- test("flatten error 2", () {
- Result<int> error = new Result<int>.error("BAD", stack);
- Result<Result<int>> result = new Result<Result<int>>.value(error);
- Result<int> flattened = Result.flatten(result);
- expectResult(flattened, error);
- });
-
- test("flatten value", () {
- Result<Result<int>> result =
- new Result<Result<int>>.value(new Result<int>.value(42));
- expectResult(Result.flatten(result), new Result<int>.value(42));
- });
-}
-
-void expectResult(Result actual, Result expected) {
- expect(actual.isValue, equals(expected.isValue));
- expect(actual.isError, equals(expected.isError));
- if (actual.isValue) {
- expect(actual.asValue.value, equals(expected.asValue.value));
- } else {
- expect(actual.asError.error, equals(expected.asError.error));
- expect(actual.asError.stackTrace, same(expected.asError.stackTrace));
- }
-}
-
-class TestSink<T> implements EventSink<T> {
- final Function onData;
- final Function onError;
- final Function onDone;
-
- TestSink({void this.onData(T data) : _nullData,
- void this.onError(e, StackTrace s) : _nullError,
- void this.onDone() : _nullDone });
-
- void add(T value) { onData(value); }
- void addError(error, [StackTrace stack]) { onError(error, stack); }
- void close() { onDone(); }
-
- static void _nullData(value) { fail("Unexpected sink add: $value"); }
- static void _nullError(e, StackTrace s) {
- fail("Unexpected sink addError: $e");
- }
- static void _nullDone() { fail("Unepxected sink close"); }
-}
diff --git a/pkg/async/test/stream_zip_test.dart b/pkg/async/test/stream_zip_test.dart
deleted file mode 100644
index 56a016a..0000000
--- a/pkg/async/test/stream_zip_test.dart
+++ /dev/null
@@ -1,231 +0,0 @@
-// Copyright (c) 2013, 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:async/stream_zip.dart";
-import "package:unittest/unittest.dart";
-
-/// Create an error with the same values as [base], except that it throwsA
-/// when seeing the value [errorValue].
-Stream streamError(Stream base, int errorValue, error) {
- return base.map((x) => (x == errorValue) ? throw error : x);
-}
-
-/// Make a [Stream] from an [Iterable] by adding events to a stream controller
-/// at periodic intervals.
-Stream mks(Iterable iterable) {
- Iterator iterator = iterable.iterator;
- StreamController controller = new StreamController();
- // Some varying time between 3 and 10 ms.
- int ms = ((++ctr) * 5) % 7 + 3;
- new Timer.periodic(new Duration(milliseconds: ms), (Timer timer) {
- if (iterator.moveNext()) {
- controller.add(iterator.current);
- } else {
- controller.close();
- timer.cancel();
- }
- });
- return controller.stream;
-}
-
-/// Counter used to give varying delays for streams.
-int ctr = 0;
-
-main() {
- // Test that zipping [streams] gives the results iterated by [expectedData].
- testZip(Iterable streams, Iterable expectedData) {
- List data = [];
- Stream zip = new StreamZip(streams);
- zip.listen(data.add, onDone: expectAsync(() {
- expect(data, equals(expectedData));
- }));
- }
-
- test("Basic", () {
- testZip([mks([1, 2, 3]), mks([4, 5, 6]), mks([7, 8, 9])],
- [[1, 4, 7], [2, 5, 8], [3, 6, 9]]);
- });
-
- test("Uneven length 1", () {
- testZip([mks([1, 2, 3, 99, 100]), mks([4, 5, 6]), mks([7, 8, 9])],
- [[1, 4, 7], [2, 5, 8], [3, 6, 9]]);
- });
-
- test("Uneven length 2", () {
- testZip([mks([1, 2, 3]), mks([4, 5, 6, 99, 100]), mks([7, 8, 9])],
- [[1, 4, 7], [2, 5, 8], [3, 6, 9]]);
- });
-
- test("Uneven length 3", () {
- testZip([mks([1, 2, 3]), mks([4, 5, 6]), mks([7, 8, 9, 99, 100])],
- [[1, 4, 7], [2, 5, 8], [3, 6, 9]]);
- });
-
- test("Uneven length 4", () {
- testZip([mks([1, 2, 3, 98]), mks([4, 5, 6]), mks([7, 8, 9, 99, 100])],
- [[1, 4, 7], [2, 5, 8], [3, 6, 9]]);
- });
-
- test("Empty 1", () {
- testZip([mks([]), mks([4, 5, 6]), mks([7, 8, 9])], []);
- });
-
- test("Empty 2", () {
- testZip([mks([1, 2, 3]), mks([]), mks([7, 8, 9])], []);
- });
-
- test("Empty 3", () {
- testZip([mks([1, 2, 3]), mks([4, 5, 6]), mks([])], []);
- });
-
- test("Empty source", () {
- testZip([], []);
- });
-
- test("Single Source", () {
- testZip([mks([1, 2, 3])], [[1], [2], [3]]);
- });
-
- test("Other-streams", () {
- Stream st1 = mks([1, 2, 3, 4, 5, 6]).where((x) => x < 4);
- Stream st2 = new Stream.periodic(const Duration(milliseconds: 5),
- (x) => x + 4).take(3);
- StreamController c = new StreamController.broadcast();
- Stream st3 = c.stream;
- testZip([st1, st2, st3],
- [[1, 4, 7], [2, 5, 8], [3, 6, 9]]);
- c..add(7)..add(8)..add(9)..close();
- });
-
- test("Error 1", () {
- expect(new StreamZip([streamError(mks([1, 2, 3]), 2, "BAD-1"),
- mks([4, 5, 6]),
- mks([7, 8, 9])]).toList(),
- throwsA(equals("BAD-1")));
- });
-
- test("Error 2", () {
- expect(new StreamZip([mks([1, 2, 3]),
- streamError(mks([4, 5, 6]), 5, "BAD-2"),
- mks([7, 8, 9])]).toList(),
- throwsA(equals("BAD-2")));
- });
-
- test("Error 3", () {
- expect(new StreamZip([mks([1, 2, 3]),
- mks([4, 5, 6]),
- streamError(mks([7, 8, 9]), 8, "BAD-3")]).toList(),
- throwsA(equals("BAD-3")));
- });
-
- test("Error at end", () {
- expect(new StreamZip([mks([1, 2, 3]),
- streamError(mks([4, 5, 6]), 6, "BAD-4"),
- mks([7, 8, 9])]).toList(),
- throwsA(equals("BAD-4")));
- });
-
- test("Error before first end", () {
- // StreamControllers' streams with no "close" called will never be done,
- // so the fourth event of the first stream is guaranteed to come first.
- expect(new StreamZip(
- [streamError(mks([1, 2, 3, 4]), 4, "BAD-5"),
- (new StreamController()..add(4)..add(5)..add(6)).stream,
- (new StreamController()..add(7)..add(8)..add(9)).stream]
- ).toList(),
- throwsA(equals("BAD-5")));
- });
-
- test("Error after first end", () {
- StreamController controller = new StreamController();
- controller..add(7)..add(8)..add(9);
- // Transformer that puts error into controller when one of the first two
- // streams have sent a done event.
- StreamTransformer trans = new StreamTransformer.fromHandlers(
- handleDone: (EventSink s) {
- Timer.run(() { controller.addError("BAD-6"); });
- s.close();
- });
- testZip([mks([1, 2, 3]).transform(trans),
- mks([4, 5, 6]).transform(trans),
- controller.stream],
- [[1, 4, 7], [2, 5, 8], [3, 6, 9]]);
- });
-
- test("Pause/Resume", () {
- var done = expectAsync((){}); // Call to complete test.
-
- int sc1p = 0;
- StreamController c1 = new StreamController(
- onPause: () {
- sc1p++;
- },
- onResume: () {
- sc1p--;
- });
-
- int sc2p = 0;
- StreamController c2 = new StreamController(
- onPause: () {
- sc2p++;
- },
- onResume: () {
- sc2p--;
- });
- Stream zip = new StreamZip([c1.stream, c2.stream]);
-
- const ms25 = const Duration(milliseconds: 25);
-
- // StreamIterator uses pause and resume to control flow.
- StreamIterator it = new StreamIterator(zip);
-
- it.moveNext().then((hasMore) {
- expect(hasMore, isTrue);
- expect(it.current, equals([1, 2]));
- return it.moveNext();
- }).then((hasMore) {
- expect(hasMore, isTrue);
- expect(it.current, equals([3, 4]));
- c2.add(6);
- return it.moveNext();
- }).then((hasMore) {
- expect(hasMore, isTrue);
- expect(it.current, equals([5, 6]));
- new Future.delayed(ms25).then((_) { c2.add(8); });
- return it.moveNext();
- }).then((hasMore) {
- expect(hasMore, isTrue);
- expect(it.current, equals([7, 8]));
- c2.add(9);
- return it.moveNext();
- }).then((hasMore) {
- expect(hasMore, isFalse);
- done();
- });
-
- c1..add(1)..add(3)..add(5)..add(7)..close();
- c2..add(2)..add(4);
- });
-
- test("pause-resume2", () {
- var s1 = new Stream.fromIterable([0, 2, 4, 6, 8]);
- var s2 = new Stream.fromIterable([1, 3, 5, 7]);
- var sz = new StreamZip([s1, s2]);
- int ctr = 0;
- var sub;
- sub = sz.listen(expectAsync((v) {
- expect(v, equals([ctr * 2, ctr * 2 + 1]));
- if (ctr == 1) {
- sub.pause(new Future.delayed(const Duration(milliseconds: 25)));
- } else if (ctr == 2) {
- sub.pause();
- new Future.delayed(const Duration(milliseconds: 25)).then((_) {
- sub.resume();
- });
- }
- ctr++;
- }, count: 4));
- });
-}
diff --git a/pkg/async/test/stream_zip_zone_test.dart b/pkg/async/test/stream_zip_zone_test.dart
deleted file mode 100644
index 0b0c4bc..0000000
--- a/pkg/async/test/stream_zip_zone_test.dart
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright (c) 2013, 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:unittest/unittest.dart";
-
-// Test that stream listener callbacks all happen in the zone where the
-// listen occurred.
-
-main() {
- StreamController controller;
- controller = new StreamController();
- testStream("singlesub-async", controller, controller.stream);
- controller = new StreamController.broadcast();
- testStream("broadcast-async", controller, controller.stream);
- controller = new StreamController();
- testStream("asbroadcast-async", controller,
- controller.stream.asBroadcastStream());
-
- controller = new StreamController(sync: true);
- testStream("singlesub-sync", controller, controller.stream);
- controller = new StreamController.broadcast(sync: true);
- testStream("broadcast-sync", controller, controller.stream);
- controller = new StreamController(sync: true);
- testStream("asbroadcast-sync", controller,
- controller.stream.asBroadcastStream());
-}
-
-void testStream(String name, StreamController controller, Stream stream) {
- test(name, () {
- Zone outer = Zone.current;
- runZoned(() {
- Zone newZone1 = Zone.current;
- StreamSubscription sub;
- sub = stream.listen(expectAsync((v) {
- expect(v, 42);
- expect(Zone.current, newZone1);
- outer.run(() {
- sub.onData(expectAsync((v) {
- expect(v, 37);
- expect(Zone.current, newZone1);
- runZoned(() {
- Zone newZone2 = Zone.current;
- sub.onData(expectAsync((v) {
- expect(v, 87);
- expect(Zone.current, newZone1);
- }));
- });
- controller.add(87);
- }));
- });
- controller.add(37);
- }));
- });
- controller.add(42);
- });
-}
diff --git a/pkg/compiler/lib/src/apiimpl.dart b/pkg/compiler/lib/src/apiimpl.dart
index be603fa..7449c7a7 100644
--- a/pkg/compiler/lib/src/apiimpl.dart
+++ b/pkg/compiler/lib/src/apiimpl.dart
@@ -220,7 +220,6 @@
}
Uri resourceUri = translateUri(node, readableUri);
- String resourceUriString = '$resourceUri';
if (resourceUri.scheme == 'dart-ext') {
if (!allowNativeExtensions) {
withCurrentElement(element, () {
@@ -236,9 +235,9 @@
return new Future.sync(() => callUserProvider(resourceUri)).then((data) {
SourceFile sourceFile;
if (data is List<int>) {
- sourceFile = new Utf8BytesSourceFile(resourceUriString, data);
+ sourceFile = new Utf8BytesSourceFile(resourceUri, data);
} else if (data is String) {
- sourceFile = new StringSourceFile(resourceUriString, data);
+ sourceFile = new StringSourceFile.fromUri(resourceUri, data);
} else {
String message = "Expected a 'String' or a 'List<int>' from the input "
"provider, but got: ${Error.safeToString(data)}.";
@@ -260,8 +259,8 @@
return new Future.value(
new leg.Script(
readableUri, resourceUri,
- new StringSourceFile(
- '$resourceUri',
+ new StringSourceFile.fromUri(
+ resourceUri,
"// Synthetic source file generated for '$readableUri'."),
isSynthesized: true));
}
diff --git a/pkg/compiler/lib/src/compiler.dart b/pkg/compiler/lib/src/compiler.dart
index a3adcdb..5427478 100644
--- a/pkg/compiler/lib/src/compiler.dart
+++ b/pkg/compiler/lib/src/compiler.dart
@@ -589,7 +589,7 @@
void onSuperNoSuchMethod(Registry registry) {}
/// Register that the application creates a constant map.
- void onConstantMap(Registry registry) {}
+ void onMapLiteral(Registry registry, DartType type, bool isConstant) {}
/// Called when resolving the `Symbol` constructor.
void onSymbolConstructor(Registry registry) {}
diff --git a/pkg/compiler/lib/src/cps_ir/cps_ir_builder.dart b/pkg/compiler/lib/src/cps_ir/cps_ir_builder.dart
index 366f409..e45762e 100644
--- a/pkg/compiler/lib/src/cps_ir/cps_ir_builder.dart
+++ b/pkg/compiler/lib/src/cps_ir/cps_ir_builder.dart
@@ -1822,7 +1822,12 @@
ir.Primitive buildFunctionExpression(ClosureClassElement classElement) {
List<ir.Primitive> arguments = <ir.Primitive>[];
for (ClosureFieldElement field in classElement.closureFields) {
- arguments.add(environment.lookup(field.local));
+ // Captured 'this' is not available as a local in the current environment,
+ // so treat that specially.
+ ir.Primitive value = field.local is ThisLocal
+ ? buildThis()
+ : environment.lookup(field.local);
+ arguments.add(value);
}
ir.Primitive closure = new ir.CreateInstance(classElement, arguments);
add(new ir.LetPrim(closure));
diff --git a/pkg/compiler/lib/src/cps_ir/cps_ir_builder_visitor.dart b/pkg/compiler/lib/src/cps_ir/cps_ir_builder_visitor.dart
index e859eef..492f117 100644
--- a/pkg/compiler/lib/src/cps_ir/cps_ir_builder_visitor.dart
+++ b/pkg/compiler/lib/src/cps_ir/cps_ir_builder_visitor.dart
@@ -758,15 +758,39 @@
ir.Primitive visitSuperSend(ast.Send node) {
assert(irBuilder.isOpen);
- if (node.isPropertyAccess) {
- return visitGetterSend(node);
- } else {
- Selector selector = elements.getSelector(node);
- Element target = elements[node];
+ Selector selector = elements.getSelector(node);
+ Element target = elements[node];
+
+ if (selector.isCall && (target.isGetter || target.isField)) {
+ // We are invoking a field or getter as if it was a method, e.g:
+ //
+ // class A { get foo => {..} }
+ // class B extends A {
+ // m() {
+ // super.foo(1, 2, 3); }
+ // }
+ // }
+ //
+ // We invoke the getter of 'foo' and then invoke the 'call' method on
+ // the result, using the given arguments.
+ Selector getter = new Selector.getterFrom(selector);
+ Selector call = new Selector.callClosureFrom(selector);
+ ir.Primitive receiver =
+ irBuilder.buildSuperInvocation(target, getter, []);
List<ir.Primitive> arguments = node.arguments.mapToList(visit);
- if (selector.isCall) {
- arguments = normalizeStaticArguments(selector, target, arguments);
- }
+ arguments = normalizeDynamicArguments(selector, arguments);
+ return irBuilder.buildCallInvocation(receiver, call, arguments);
+ } else if (selector.isCall) {
+ // We are invoking a method.
+ assert(target is FunctionElement);
+ List<ir.Primitive> arguments = node.arguments.mapToList(visit);
+ arguments = normalizeStaticArguments(selector, target, arguments);
+ return irBuilder.buildSuperInvocation(target, selector, arguments);
+ } else {
+ // We are invoking a getter, operator, indexer, etc.
+ List<ir.Primitive> arguments = node.argumentsNode == null
+ ? <ir.Primitive>[]
+ : node.arguments.mapToList(visit);
return irBuilder.buildSuperInvocation(target, selector, arguments);
}
}
@@ -1035,6 +1059,9 @@
visitFunctionExpression(ast.FunctionExpression node) {
FunctionElement oldFunction = currentFunction;
currentFunction = elements[node];
+ if (currentFunction.asyncMarker != AsyncMarker.SYNC) {
+ giveup(node, "cannot handle async/sync*/async* functions");
+ }
if (node.initializers != null) {
insideInitializer = true;
visit(node.initializers);
@@ -1128,6 +1155,9 @@
ir.FunctionDefinition buildFunction(FunctionElement element) {
assert(invariant(element, element.isImplementation));
ast.FunctionExpression node = element.node;
+ if (element.asyncMarker != AsyncMarker.SYNC) {
+ giveup(null, 'cannot handle async-await');
+ }
if (!element.isSynthesized) {
assert(node != null);
diff --git a/pkg/compiler/lib/src/cps_ir/cps_ir_nodes.dart b/pkg/compiler/lib/src/cps_ir/cps_ir_nodes.dart
index d1f51fc..f1d5616 100644
--- a/pkg/compiler/lib/src/cps_ir/cps_ir_nodes.dart
+++ b/pkg/compiler/lib/src/cps_ir/cps_ir_nodes.dart
@@ -454,7 +454,8 @@
///
/// let rec [variable] = [definition] in [body]
///
-class DeclareFunction extends Expression implements InteriorNode {
+class DeclareFunction extends Expression
+ implements InteriorNode, DartSpecificNode {
final MutableVariable variable;
final FunctionDefinition definition;
Expression body;
@@ -528,9 +529,12 @@
/// Marker interface for nodes that are only handled in the JavaScript backend.
///
-/// These nodes are generated by the unsugar step and need special translation
-/// to the Tree IR, which is implemented in JsTreeBuilder.
-abstract class JsSpecificNode {}
+/// These nodes are generated by the unsugar step or the [JsIrBuilder] and need
+/// special translation to the Tree IR, which is implemented in JsTreeBuilder.
+abstract class JsSpecificNode implements Node {}
+
+/// Marker interface for nodes that are only handled inthe Dart backend.
+abstract class DartSpecificNode implements Node {}
/// Directly assigns to a field on a given object.
class SetField extends Expression implements InteriorNode, JsSpecificNode {
@@ -656,7 +660,7 @@
}
/// Create a non-recursive function.
-class CreateFunction extends Primitive {
+class CreateFunction extends Primitive implements DartSpecificNode {
final FunctionDefinition definition;
CreateFunction(this.definition);
@@ -795,7 +799,7 @@
bool get isAbstract => body == null;
}
-abstract class Initializer extends Node {}
+abstract class Initializer extends Node implements DartSpecificNode {}
class FieldInitializer extends Initializer {
final FieldElement element;
diff --git a/pkg/compiler/lib/src/cps_ir/cps_ir_tracer.dart b/pkg/compiler/lib/src/cps_ir/cps_ir_tracer.dart
index 2fc8597..bb50842 100644
--- a/pkg/compiler/lib/src/cps_ir/cps_ir_tracer.dart
+++ b/pkg/compiler/lib/src/cps_ir/cps_ir_tracer.dart
@@ -466,6 +466,10 @@
visit(exp.body);
}
+ visitLetMutable(cps_ir.LetMutable exp) {
+ visit(exp.body);
+ }
+
visitSetField(cps_ir.SetField exp) {
visit(exp.body);
}
diff --git a/pkg/compiler/lib/src/dart2js.dart b/pkg/compiler/lib/src/dart2js.dart
index 1fbf543..2ea3faa 100644
--- a/pkg/compiler/lib/src/dart2js.dart
+++ b/pkg/compiler/lib/src/dart2js.dart
@@ -169,8 +169,8 @@
passThrough(argument);
}
- String getDepsOutput(Map<String, SourceFile> sourceFiles) {
- var filenames = new List.from(sourceFiles.keys);
+ String getDepsOutput(Map<Uri, SourceFile> sourceFiles) {
+ var filenames = sourceFiles.keys.map((uri) => '$uri').toList();
filenames.sort();
return filenames.join("\n");
}
@@ -588,9 +588,6 @@
Do not generate a call to main if either of the following
libraries are used: dart:dom, dart:html dart:io.
- --enable-concrete-type-inference
- Enable experimental concrete type inference.
-
--disable-native-live-type-analysis
Disable the optimization that removes unused native types from dart:html
and related libraries.
@@ -654,6 +651,9 @@
Future<api.CompilationResult> internalMain(List<String> arguments) {
Future onError(exception, trace) {
+ // If we are already trying to exit, just continue exiting.
+ if (exception == _EXIT_SIGNAL) throw exception;
+
try {
print('The compiler crashed: $exception');
} catch (ignored) {
diff --git a/pkg/compiler/lib/src/elements/elements.dart b/pkg/compiler/lib/src/elements/elements.dart
index b7c4bba..5560c4a 100644
--- a/pkg/compiler/lib/src/elements/elements.dart
+++ b/pkg/compiler/lib/src/elements/elements.dart
@@ -1430,7 +1430,7 @@
/// Enum declaration.
abstract class EnumClassElement extends ClassElement {
/// The static fields implied by the enum values.
- Iterable<FieldElement> get enumValues;
+ List<FieldElement> get enumValues;
}
/// The label entity defined by a labeled statement.
diff --git a/pkg/compiler/lib/src/elements/modelx.dart b/pkg/compiler/lib/src/elements/modelx.dart
index caa87de..19eee6a 100644
--- a/pkg/compiler/lib/src/elements/modelx.dart
+++ b/pkg/compiler/lib/src/elements/modelx.dart
@@ -1864,7 +1864,7 @@
}
abstract class FunctionElementX extends BaseFunctionElementX
- with AnalyzableElementX implements MemberElement {
+ with AnalyzableElementX implements MethodElement {
FunctionElementX(String name,
ElementKind kind,
Modifiers modifiers,
@@ -2670,7 +2670,7 @@
class EnumClassElementX extends ClassElementX implements EnumClassElement {
final Enum node;
- Iterable<FieldElement> _enumValues;
+ List<FieldElement> _enumValues;
EnumClassElementX(String name, Element enclosing, int id, this.node)
: super(name, enclosing, id, STATE_NOT_STARTED);
@@ -2692,13 +2692,13 @@
List<DartType> computeTypeParameters(Compiler compiler) => const <DartType>[];
- Iterable<FieldElement> get enumValues {
+ List<FieldElement> get enumValues {
assert(invariant(this, _enumValues != null,
message: "enumValues has not been computed for $this."));
return _enumValues;
}
- void set enumValues(Iterable<FieldElement> values) {
+ void set enumValues(List<FieldElement> values) {
assert(invariant(this, _enumValues == null,
message: "enumValues has already been computed for $this."));
_enumValues = values;
@@ -2935,8 +2935,6 @@
Node parseNode(compiler) => node;
- String toString() => "${enclosingElement.toString()}.${name}";
-
Token get position => node.getBeginToken();
accept(ElementVisitor visitor) => visitor.visitTypeVariableElement(this);
diff --git a/pkg/compiler/lib/src/io/code_output.dart b/pkg/compiler/lib/src/io/code_output.dart
index 5f13198..d046f22 100644
--- a/pkg/compiler/lib/src/io/code_output.dart
+++ b/pkg/compiler/lib/src/io/code_output.dart
@@ -10,7 +10,7 @@
class CodeOutputMarker {
final int offsetDelta;
- final SourceFileLocation sourcePosition;
+ final SourceLocation sourcePosition;
CodeOutputMarker(this.offsetDelta, this.sourcePosition);
}
@@ -43,7 +43,7 @@
/// Applies [f] to every marker in this output.
void forEachSourceLocation(void f(int targetOffset,
- SourceFileLocation sourceLocation));
+ SourceLocation sourceLocation));
}
abstract class AbstractCodeOutput extends CodeOutput {
@@ -91,7 +91,7 @@
--mappedRangeCounter;
}
- void setSourceLocation(SourceFileLocation sourcePosition) {
+ void setSourceLocation(SourceLocation sourcePosition) {
if (sourcePosition == null) {
if (markers.length > 0 && markers.last.sourcePosition == null) return;
}
diff --git a/pkg/compiler/lib/src/io/source_file.dart b/pkg/compiler/lib/src/io/source_file.dart
index a106e5e..c8f79cd 100644
--- a/pkg/compiler/lib/src/io/source_file.dart
+++ b/pkg/compiler/lib/src/io/source_file.dart
@@ -14,9 +14,13 @@
* a UTF-8 encoded [List<int>] of bytes.
*/
abstract class SourceFile implements LineColumnProvider {
+ /// The absolute URI of the source file.
+ Uri get uri;
- /** The name of the file. */
- String get filename;
+ /// The name of the file.
+ ///
+ /// This is [uri], maybe relativized to a more human-readable form.
+ String get filename => uri.toString();
/** The text content of the file represented as a String. */
String slowText();
@@ -165,12 +169,12 @@
}
class Utf8BytesSourceFile extends SourceFile {
- final String filename;
+ final Uri uri;
/** The UTF-8 encoded content of the source file. */
final List<int> content;
- Utf8BytesSourceFile(this.filename, this.content);
+ Utf8BytesSourceFile(this.uri, this.content);
String slowText() => UTF8.decode(content);
@@ -195,9 +199,10 @@
class CachingUtf8BytesSourceFile extends Utf8BytesSourceFile {
String cachedText;
+ final String filename;
- CachingUtf8BytesSourceFile(String filename, List<int> content)
- : super(filename, content);
+ CachingUtf8BytesSourceFile(Uri uri, this.filename, List<int> content)
+ : super(uri, content);
String slowText() {
if (cachedText == null) {
@@ -208,10 +213,17 @@
}
class StringSourceFile extends SourceFile {
+ final Uri uri;
final String filename;
final String text;
- StringSourceFile(this.filename, this.text);
+ StringSourceFile(this.uri, this.filename, this.text);
+
+ StringSourceFile.fromUri(Uri uri, String text)
+ : this(uri, uri.toString(), text);
+
+ StringSourceFile.fromName(String filename, String text)
+ : this(new Uri(path: filename), filename, text);
int get length => text.length;
set length(int v) { }
diff --git a/pkg/compiler/lib/src/io/source_information.dart b/pkg/compiler/lib/src/io/source_information.dart
index c0e6e0a8..c238268 100644
--- a/pkg/compiler/lib/src/io/source_information.dart
+++ b/pkg/compiler/lib/src/io/source_information.dart
@@ -23,13 +23,13 @@
/// Source information that contains start source position and optionally an
/// end source position.
class StartEndSourceInformation implements SourceInformation {
- final SourceFileLocation startPosition;
- final SourceFileLocation endPosition;
+ final SourceLocation startPosition;
+ final SourceLocation endPosition;
StartEndSourceInformation(this.startPosition, [this.endPosition]);
SourceSpan get sourceSpan {
- Uri uri = Uri.parse(startPosition.sourceFile.filename);
+ Uri uri = startPosition.sourceUri;
int begin = startPosition.offset;
int end = endPosition == null ? begin : endPosition.offset;
return new SourceSpan(uri, begin, end);
@@ -80,85 +80,87 @@
}
// TODO(podivilov): find the right sourceFile here and remove offset
// checks below.
- SourceFileLocation sourcePosition, endSourcePosition;
+ SourceLocation sourcePosition, endSourcePosition;
if (beginToken.charOffset < sourceFile.length) {
sourcePosition =
- new TokenSourceFileLocation(sourceFile, beginToken, name);
+ new TokenSourceLocation(sourceFile, beginToken, name);
}
if (endToken.charOffset < sourceFile.length) {
endSourcePosition =
- new TokenSourceFileLocation(sourceFile, endToken, name);
+ new TokenSourceLocation(sourceFile, endToken, name);
}
return new StartEndSourceInformation(sourcePosition, endSourcePosition);
}
String toString() {
StringBuffer sb = new StringBuffer();
- sb.write('${startPosition.getSourceUrl()}:');
- sb.write('[${startPosition.getLine()},${startPosition.getColumn()}]');
+ sb.write('${startPosition.sourceUri}:');
+ sb.write('[${startPosition.line},${startPosition.column}]');
if (endPosition != null) {
- sb.write('-[${endPosition.getLine()},${endPosition.getColumn()}]');
+ sb.write('-[${endPosition.line},${endPosition.column}]');
}
return sb.toString();
}
}
-// TODO(johnniwinther): Refactor this class to use getters.
-abstract class SourceFileLocation {
- SourceFile sourceFile;
+/// A location in a source file.
+abstract class SourceLocation {
+ final SourceFile _sourceFile;
+ int _line;
- SourceFileLocation(this.sourceFile) {
- assert(isValid());
+ SourceLocation(this._sourceFile) {
+ assert(isValid);
}
- int line;
+ /// The absolute URI of the source file of this source location.
+ Uri get sourceUri => _sourceFile.uri;
+ /// The character offset of the this source location into the source file.
int get offset;
- String getSourceUrl() => sourceFile.filename;
-
- int getLine() {
- if (line == null) line = sourceFile.getLine(offset);
- return line;
+ /// The 0-based line number of the [offset].
+ int get line {
+ if (_line == null) _line = _sourceFile.getLine(offset);
+ return _line;
}
- int getColumn() => sourceFile.getColumn(getLine(), offset);
+ /// The 0-base column number of the [offset] with its line.
+ int get column => _sourceFile.getColumn(line, offset);
- String getSourceName();
+ /// The name associated with this source location, if any.
+ String get sourceName;
- bool isValid() => offset < sourceFile.length;
+ /// `true` if the offset within the length of the source file.
+ bool get isValid => offset < _sourceFile.length;
int get hashCode {
- return getSourceUrl().hashCode * 17 +
+ return sourceUri.hashCode * 17 +
offset.hashCode * 17 +
- getSourceName().hashCode * 23;
+ sourceName.hashCode * 23;
}
bool operator ==(other) {
if (identical(this, other)) return true;
- if (other is! SourceFileLocation) return false;
- return getSourceUrl() == other.getSourceUrl() &&
+ if (other is! SourceLocation) return false;
+ return sourceUri == other.sourceUri &&
offset == other.offset &&
- getSourceName() == other.getSourceName();
+ sourceName == other.sourceName;
}
- String toString() => '${getSourceUrl()}:[${getLine()},${getColumn()}]';
+ String toString() => '${sourceUri}:[${line},${column}]';
}
-class TokenSourceFileLocation extends SourceFileLocation {
+class TokenSourceLocation extends SourceLocation {
final Token token;
- final String name;
+ final String sourceName;
- TokenSourceFileLocation(SourceFile sourceFile, this.token, this.name)
+ TokenSourceLocation(SourceFile sourceFile, this.token, this.sourceName)
: super(sourceFile);
+ @override
int get offset => token.charOffset;
- String getSourceName() {
- return name;
- }
-
String toString() {
- return '${super.toString()}:$name';
+ return '${super.toString()}:$sourceName';
}
}
diff --git a/pkg/compiler/lib/src/io/source_map_builder.dart b/pkg/compiler/lib/src/io/source_map_builder.dart
index ed546f2..bf614ab 100644
--- a/pkg/compiler/lib/src/io/source_map_builder.dart
+++ b/pkg/compiler/lib/src/io/source_map_builder.dart
@@ -7,7 +7,7 @@
import '../util/util.dart';
import '../util/uri_extras.dart' show relativize;
import 'line_column_provider.dart';
-import 'source_information.dart' show SourceFileLocation;
+import 'source_information.dart' show SourceLocation;
class SourceMapBuilder {
static const int VLQ_BASE_SHIFT = 5;
@@ -17,36 +17,40 @@
static const String BASE64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn'
'opqrstuvwxyz0123456789+/';
- final Uri uri;
- final Uri fileUri;
+ /// The URI of the source map file.
+ final Uri sourceMapUri;
+ /// The URI of the target language file.
+ final Uri targetFileUri;
LineColumnProvider lineColumnProvider;
List<SourceMapEntry> entries;
- Map<String, int> sourceUrlMap;
- List<String> sourceUrlList;
+ Map<Uri, int> sourceUriMap;
+ List<Uri> sourceUriList;
Map<String, int> sourceNameMap;
List<String> sourceNameList;
int previousTargetLine;
int previousTargetColumn;
- int previousSourceUrlIndex;
+ int previousSourceUriIndex;
int previousSourceLine;
int previousSourceColumn;
int previousSourceNameIndex;
bool firstEntryInLine;
- SourceMapBuilder(this.uri, this.fileUri, this.lineColumnProvider) {
+ SourceMapBuilder(this.sourceMapUri,
+ this.targetFileUri,
+ this.lineColumnProvider) {
entries = new List<SourceMapEntry>();
- sourceUrlMap = new Map<String, int>();
- sourceUrlList = new List<String>();
+ sourceUriMap = new Map<Uri, int>();
+ sourceUriList = new List<Uri>();
sourceNameMap = new Map<String, int>();
sourceNameList = new List<String>();
previousTargetLine = 0;
previousTargetColumn = 0;
- previousSourceUrlIndex = 0;
+ previousSourceUriIndex = 0;
previousSourceLine = 0;
previousSourceColumn = 0;
previousSourceNameIndex = 0;
@@ -54,37 +58,37 @@
}
resetPreviousSourceLocation() {
- previousSourceUrlIndex = 0;
+ previousSourceUriIndex = 0;
previousSourceLine = 0;
previousSourceColumn = 0;
previousSourceNameIndex = 0;
}
- updatePreviousSourceLocation(SourceFileLocation sourceLocation) {
- previousSourceLine = sourceLocation.getLine();
- previousSourceColumn = sourceLocation.getColumn();
- String sourceUrl = sourceLocation.getSourceUrl();
- previousSourceUrlIndex = indexOf(sourceUrlList, sourceUrl, sourceUrlMap);
- String sourceName = sourceLocation.getSourceName();
+ updatePreviousSourceLocation(SourceLocation sourceLocation) {
+ previousSourceLine = sourceLocation.line;
+ previousSourceColumn = sourceLocation.column;
+ Uri sourceUri = sourceLocation.sourceUri;
+ previousSourceUriIndex = indexOf(sourceUriList, sourceUri, sourceUriMap);
+ String sourceName = sourceLocation.sourceName;
if (sourceName != null) {
previousSourceNameIndex =
indexOf(sourceNameList, sourceName, sourceNameMap);
}
}
- bool sameAsPreviousLocation(SourceFileLocation sourceLocation) {
+ bool sameAsPreviousLocation(SourceLocation sourceLocation) {
if (sourceLocation == null) {
return true;
}
- int sourceUrlIndex =
- indexOf(sourceUrlList, sourceLocation.getSourceUrl(), sourceUrlMap);
+ int sourceUriIndex =
+ indexOf(sourceUriList, sourceLocation.sourceUri, sourceUriMap);
return
- sourceUrlIndex == previousSourceUrlIndex &&
- sourceLocation.getLine() == previousSourceLine &&
- sourceLocation.getColumn() == previousSourceColumn;
+ sourceUriIndex == previousSourceUriIndex &&
+ sourceLocation.line == previousSourceLine &&
+ sourceLocation.column == previousSourceColumn;
}
- void addMapping(int targetOffset, SourceFileLocation sourceLocation) {
+ void addMapping(int targetOffset, SourceLocation sourceLocation) {
bool sameLine(int position, otherPosition) {
return lineColumnProvider.getLine(position) ==
@@ -132,17 +136,19 @@
StringBuffer buffer = new StringBuffer();
buffer.write('{\n');
buffer.write(' "version": 3,\n');
- if (uri != null && fileUri != null) {
- buffer.write(' "file": "${relativize(uri, fileUri, false)}",\n');
+ if (sourceMapUri != null && targetFileUri != null) {
+ buffer.write(
+ ' "file": "${relativize(sourceMapUri, targetFileUri, false)}",\n');
}
buffer.write(' "sourceRoot": "",\n');
buffer.write(' "sources": ');
- if (uri != null) {
- sourceUrlList =
- sourceUrlList.map((url) => relativize(uri, Uri.parse(url), false))
- .toList();
+ List<String> relativeSourceUriList = <String>[];
+ if (sourceMapUri != null) {
+ relativeSourceUriList = sourceUriList
+ .map((u) => relativize(sourceMapUri, u, false))
+ .toList();
}
- printStringListOn(sourceUrlList, buffer);
+ printStringListOn(relativeSourceUriList, buffer);
buffer.write(',\n');
buffer.write(' "names": ');
printStringListOn(sourceNameList, buffer);
@@ -177,13 +183,13 @@
if (entry.sourceLocation == null) return;
- String sourceUrl = entry.sourceLocation.getSourceUrl();
- int sourceLine = entry.sourceLocation.getLine();
- int sourceColumn = entry.sourceLocation.getColumn();
- String sourceName = entry.sourceLocation.getSourceName();
+ Uri sourceUri = entry.sourceLocation.sourceUri;
+ int sourceLine = entry.sourceLocation.line;
+ int sourceColumn = entry.sourceLocation.column;
+ String sourceName = entry.sourceLocation.sourceName;
- int sourceUrlIndex = indexOf(sourceUrlList, sourceUrl, sourceUrlMap);
- encodeVLQ(output, sourceUrlIndex - previousSourceUrlIndex);
+ int sourceUriIndex = indexOf(sourceUriList, sourceUri, sourceUriMap);
+ encodeVLQ(output, sourceUriIndex - previousSourceUriIndex);
encodeVLQ(output, sourceLine - previousSourceLine);
encodeVLQ(output, sourceColumn - previousSourceColumn);
@@ -197,7 +203,7 @@
updatePreviousSourceLocation(entry.sourceLocation);
}
- int indexOf(List<String> list, String value, Map<String, int> map) {
+ int indexOf(List list, value, Map<dynamic, int> map) {
return map.putIfAbsent(value, () {
int index = list.length;
list.add(value);
@@ -224,7 +230,7 @@
}
class SourceMapEntry {
- SourceFileLocation sourceLocation;
+ SourceLocation sourceLocation;
int targetOffset;
SourceMapEntry(this.sourceLocation, this.targetOffset);
diff --git a/pkg/compiler/lib/src/js/builder.dart b/pkg/compiler/lib/src/js/builder.dart
deleted file mode 100644
index 72b4507..0000000
--- a/pkg/compiler/lib/src/js/builder.dart
+++ /dev/null
@@ -1,1336 +0,0 @@
-// Copyright (c) 2013, 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.
-
-// Utilities for building JS ASTs at runtime. Contains a builder class
-// and a parser that parses part of the language.
-
-part of js_ast;
-
-
-/**
- * Global template manager. We should aim to have a fixed number of
- * templates. This implies that we do not use js('xxx') to parse text that is
- * constructed from values that depend on names in the Dart program.
- *
- * TODO(sra): Find the remaining places where js('xxx') used to parse an
- * unbounded number of expression, or institute a cache policy.
- */
-TemplateManager templateManager = new TemplateManager();
-
-
-/**
-
-[js] is a singleton instace of JsBuilder. JsBuilder is a set of conveniences
-for constructing JavaScript ASTs.
-
-[string] and [number] are used to create leaf AST nodes:
-
- var s = js.string('hello'); // s = new LiteralString('"hello"')
- var n = js.number(123); // n = new LiteralNumber(123)
-
-In the line above `a --> b` means Dart expression `a` evaluates to a JavaScript
-AST that would pretty-print as `b`.
-
-The [call] method constructs an Expression AST.
-
-No argument
-
- js('window.alert("hello")') --> window.alert("hello")
-
-The input text can contain placeholders `#` that are replaced with provided
-arguments. A single argument can be passed directly:
-
- js('window.alert(#)', s) --> window.alert("hello")
-
-Multiple arguments are passed as a list:
-
- js('# + #', [s, s]) --> "hello" + "hello"
-
-The [statement] method constructs a Statement AST, but is otherwise like the
-[call] method. This constructs a Return AST:
-
- var ret = js.statement('return #;', n); --> return 123;
-
-A placeholder in a Statement context must be followed by a semicolon ';'. You
-can think of a statement placeholder as being `#;` to explain why the output
-still has one semicolon:
-
- js.statement('if (happy) #;', ret)
- -->
- if (happy)
- return 123;
-
-If the placeholder is not followed by a semicolon, it is part of an expression.
-Here the paceholder is in the position of the function in a function call:
-
- var vFoo = new VariableUse('foo');
- js.statement('if (happy) #("Happy!")', vFoo)
- -->
- if (happy)
- foo("Happy!");
-
-Generally, a placeholder in an expression position requires an Expression AST as
-an argument and a placeholder in a statement position requires a Statement AST.
-An expression will be converted to a Statement if needed by creating an
-ExpessionStatement. A String argument will be converted into a VariableUse and
-requires that the string is a JavaScript identifier.
-
- js('# + 1', vFoo) --> foo + 1
- js('# + 1', 'foo') --> foo + 1
- js('# + 1', 'foo.bar') --> assertion failure
-
-Some placeholder positions are _splicing contexts_. A function argument list is
-a splicing expression context. A placeholder in a splicing expression context
-can take a single Expression (or String, converted to VariableUse) or an
-Iterable of Expressions (and/or Strings).
-
- // non-splicing argument:
- js('#(#)', ['say', s]) --> say("hello")
- // splicing arguments:
- js('#(#)', ['say', []]) --> say()
- js('#(#)', ['say', [s]]) --> say("hello")
- js('#(#)', ['say', [s, n]]) --> say("hello", 123)
-
-A splicing context can be used to append 'lists' and add extra elements:
-
- js('foo(#, #, 1)', [ ['a', n], s]) --> foo(a, 123, "hello", 1)
- js('foo(#, #, 1)', [ ['a', n], [s, n]]) --> foo(a, 123, "hello", 123, 1)
- js('foo(#, #, 1)', [ [], [s, n]]) --> foo("hello", 123, 1)
- js('foo(#, #, 1)', [ [], [] ]) --> foo(1)
-
-The generation of a compile-time optional argument expression can be chosen by
-providing an empty or singleton list.
-
-In addition to Expressions and Statements, there are Parameters, which occur
-only in the parameter list of a function expression or declaration.
-Placeholders in parameter positions behave like placeholders in Expression
-positions, except only Parameter AST nodes are permitted. String arguments for
-parameter placeholders are converted to Parameter AST nodes.
-
- var pFoo = new Parameter('foo')
- js('function(#) { return #; }', [pFoo, vFoo])
- -->
- function(foo) { return foo; }
-
-Expressions and Parameters are not compatible with each other's context:
-
- js('function(#) { return #; }', [vFoo, vFoo]) --> error
- js('function(#) { return #; }', [pFoo, pFoo]) --> error
-
-The parameter context is a splicing context. When combined with the
-context-sensitive conversion of Strings, this simplifies the construction of
-trampoline-like functions:
-
- var args = ['a', 'b'];
- js('function(#) { return f(this, #); }', [args, args])
- -->
- function(a, b) { return f(this, a, b); }
-
-A statement placeholder in a Block is also in a splicing context. In addition
-to splicing Iterables, statement placeholders in a Block will also splice a
-Block or an EmptyStatement. This flattens nested blocks and allows blocks to be
-appended.
-
- var b1 = js.statement('{ 1; 2; }');
- var sEmpty = new Emptystatement();
- js.statement('{ #; #; #; #; }', [sEmpty, b1, b1, sEmpty])
- -->
- { 1; 2; 1; 2; }
-
-A placeholder in the context of an if-statement condition also accepts a Dart
-bool argument, which selects the then-part or else-part of the if-statement:
-
- js.statement('if (#) return;', vFoo) --> if (foo) return;
- js.statement('if (#) return;', true) --> return;
- js.statement('if (#) return;', false) --> ; // empty statement
- var eTrue = new LiteralBool(true);
- js.statement('if (#) return;', eTrue) --> if (true) return;
-
-Combined with block splicing, if-statement condition context placeholders allows
-the creation of tenplates that select code depending on variables.
-
- js.statement('{ 1; if (#) 2; else { 3; 4; } 5;}', true)
- --> { 1; 2; 5; }
-
- js.statement('{ 1; if (#) 2; else { 3; 4; } 5;}', false)
- --> { 1; 3; 4; 5; }
-
-A placeholder following a period in a property access is in a property access
-context. This is just like an expression context, except String arguments are
-converted to JavaScript property accesses. In JavaScript, `a.b` is short-hand
-for `a["b"]`:
-
- js('a[#]', vFoo) --> a[foo]
- js('a[#]', s) --> a.hello (i.e. a["hello"]).
- js('a[#]', 'x') --> a[x]
-
- js('a.#', vFoo) --> a[foo]
- js('a.#', s) --> a.hello (i.e. a["hello"])
- js('a.#', 'x') --> a.x (i.e. a["x"])
-
-(Question - should `.#` be restricted to permit only String arguments? The
-template should probably be writted with `[]` if non-strings are accepted.)
-
-
-Object initialiers allow placeholders in the key property name position:
-
- js('{#:1, #:2}', [s, 'bye']) --> {hello: 1, bye: 2}
-
-
-What is not implemented:
-
- - Array initializers and object initializers could support splicing. In the
- array case, we would need some way to know if an ArrayInitializer argument
- should be splice or is intended as a single value.
-
- - There are no placeholders in definition contexts:
-
- function #(){}
- var # = 1;
-
-*/
-const JsBuilder js = const JsBuilder();
-
-
-class JsBuilder {
- const JsBuilder();
-
- /**
- * Parses a bit of JavaScript, and returns an expression.
- *
- * See the MiniJsParser class.
- *
- * [arguments] can be a single [Node] (e.g. an [Expression] or [Statement]) or
- * a list of [Node]s, which will be interpolated into the source at the '#'
- * signs.
- */
- Expression call(String source, [var arguments]) {
- Template template = _findExpressionTemplate(source);
- if (arguments == null) return template.instantiate([]);
- // We allow a single argument to be given directly.
- if (arguments is! List && arguments is! Map) arguments = [arguments];
- return template.instantiate(arguments);
- }
-
- /**
- * Parses a JavaScript Statement, otherwise just like [call].
- */
- Statement statement(String source, [var arguments]) {
- Template template = _findStatementTemplate(source);
- if (arguments == null) return template.instantiate([]);
- // We allow a single argument to be given directly.
- if (arguments is! List && arguments is! Map) arguments = [arguments];
- return template.instantiate(arguments);
- }
-
- /**
- * Parses JavaScript written in the `JS` foreign instruction.
- *
- * The [source] must be a JavaScript expression or a JavaScript throw
- * statement.
- */
- Template parseForeignJS(String source) {
- // TODO(sra): Parse with extra validation to forbid `#` interpolation in
- // functions, as this leads to unanticipated capture of temporaries that are
- // reused after capture.
- if (source.startsWith("throw ")) {
- return _findStatementTemplate(source);
- } else {
- return _findExpressionTemplate(source);
- }
- }
-
- Template _findExpressionTemplate(String source) {
- Template template = templateManager.lookupExpressionTemplate(source);
- if (template == null) {
- MiniJsParser parser = new MiniJsParser(source);
- Expression expression = parser.expression();
- template = templateManager.defineExpressionTemplate(source, expression);
- }
- return template;
- }
-
- Template _findStatementTemplate(String source) {
- Template template = templateManager.lookupStatementTemplate(source);
- if (template == null) {
- MiniJsParser parser = new MiniJsParser(source);
- Statement statement = parser.statement();
- template = templateManager.defineStatementTemplate(source, statement);
- }
- return template;
- }
-
- /**
- * Creates an Expression template without caching the result.
- */
- Template uncachedExpressionTemplate(String source) {
- MiniJsParser parser = new MiniJsParser(source);
- Expression expression = parser.expression();
- return new Template(
- source, expression, isExpression: true, forceCopy: false);
- }
-
- /**
- * Creates a Statement template without caching the result.
- */
- Template uncachedStatementTemplate(String source) {
- MiniJsParser parser = new MiniJsParser(source);
- Statement statement = parser.statement();
- return new Template(
- source, statement, isExpression: false, forceCopy: false);
- }
-
- /**
- * Create an Expression template which has [ast] as the result. This is used
- * to wrap a generated AST in a zero-argument Template so it can be passed to
- * context that expects a template.
- */
- Template expressionTemplateYielding(Node ast) {
- return new Template.withExpressionResult(ast);
- }
-
- Template statementTemplateYielding(Node ast) {
- return new Template.withStatementResult(ast);
- }
-
- /// Creates a literal js string from [value].
- LiteralString escapedString(String value) {
- // Start by escaping the backslashes.
- String escaped = value.replaceAll('\\', '\\\\');
- // Do not escape unicode characters and ' because they are allowed in the
- // string literal anyway.
- escaped = escaped.replaceAllMapped(new RegExp('\n|"|\b|\t|\v'), (match) {
- switch (match.group(0)) {
- case "\n" : return r"\n";
- case "\"" : return r'\"';
- case "\b" : return r"\b";
- case "\t" : return r"\t";
- case "\f" : return r"\f";
- case "\v" : return r"\v";
- }
- });
- LiteralString result = string(escaped);
- // We don't escape ' under the assumption that the string is wrapped
- // into ". Verify that assumption.
- assert(result.value.codeUnitAt(0) == '"'.codeUnitAt(0));
- return result;
- }
-
- /// Creates a literal js string from [value].
- ///
- /// Note that this function only puts quotes around [value]. It does not do
- /// any escaping, so use only when you can guarantee that [value] does not
- /// contain newlines or backslashes. For escaping the string use
- /// [escapedString].
- LiteralString string(String value) => new LiteralString('"$value"');
-
- LiteralNumber number(num value) => new LiteralNumber('$value');
-
- LiteralBool boolean(bool value) => new LiteralBool(value);
-
- ArrayInitializer numArray(Iterable<int> list) =>
- new ArrayInitializer(list.map(number).toList());
-
- ArrayInitializer stringArray(Iterable<String> list) =>
- new ArrayInitializer(list.map(string).toList());
-
- Comment comment(String text) => new Comment(text);
-
- Call propertyCall(Expression receiver,
- String fieldName,
- List<Expression> arguments) {
- return new Call(new PropertyAccess.field(receiver, fieldName), arguments);
- }
-}
-
-LiteralString string(String value) => js.string(value);
-LiteralNumber number(num value) => js.number(value);
-ArrayInitializer numArray(Iterable<int> list) => js.numArray(list);
-ArrayInitializer stringArray(Iterable<String> list) => js.stringArray(list);
-Call propertyCall(Expression receiver,
- String fieldName,
- List<Expression> arguments) {
- return js.propertyCall(receiver, fieldName, arguments);
-}
-
-class MiniJsParserError {
- MiniJsParserError(this.parser, this.message) { }
-
- final MiniJsParser parser;
- final String message;
-
- String toString() {
- int pos = parser.lastPosition;
-
- // Discard lines following the line containing lastPosition.
- String src = parser.src;
- int newlinePos = src.indexOf('\n', pos);
- if (newlinePos >= pos) src = src.substring(0, newlinePos);
-
- // Extract the prefix of the error line before lastPosition.
- String line = src;
- int lastLineStart = line.lastIndexOf('\n');
- if (lastLineStart >= 0) line = line.substring(lastLineStart + 1);
- String prefix = line.substring(0, pos - (src.length - line.length));
-
- // Replace non-tabs with spaces, giving a print indent that matches the text
- // for tabbing.
- String spaces = prefix.replaceAll(new RegExp(r'[^\t]'), ' ');
- return 'Error in MiniJsParser:\n${src}\n$spaces^\n$spaces$message\n';
- }
-}
-
-/// Mini JavaScript parser for tiny snippets of code that we want to make into
-/// AST nodes. Handles:
-/// * identifiers.
-/// * dot access.
-/// * method calls.
-/// * [] access.
-/// * array, string, regexp, boolean, null and numeric literals.
-/// * most operators.
-/// * brackets.
-/// * var declarations.
-/// * operator precedence.
-/// * anonymous funtions and named function expressions and declarations.
-/// Notable things it can't do yet include:
-/// * some statements are still missing (do-while, while, switch).
-///
-/// It's a fairly standard recursive descent parser.
-///
-/// Literal strings are passed through to the final JS source code unchanged,
-/// including the choice of surrounding quotes, so if you parse
-/// r'var x = "foo\n\"bar\""' you will end up with
-/// var x = "foo\n\"bar\"" in the final program. \x and \u escapes are not
-/// allowed in string and regexp literals because the machinery for checking
-/// their correctness is rather involved.
-class MiniJsParser {
- MiniJsParser(this.src)
- : lastCategory = NONE,
- lastToken = null,
- lastPosition = 0,
- position = 0 {
- getToken();
- }
-
- int lastCategory = NONE;
- String lastToken = null;
- int lastPosition = 0;
- int position = 0;
- bool skippedNewline = false; // skipped newline in last getToken?
- final String src;
-
- final List<InterpolatedNode> interpolatedValues = <InterpolatedNode>[];
- bool get hasNamedHoles =>
- interpolatedValues.isNotEmpty && interpolatedValues.first.isNamed;
- bool get hasPositionalHoles =>
- interpolatedValues.isNotEmpty && interpolatedValues.first.isPositional;
-
- static const NONE = -1;
- static const ALPHA = 0;
- static const NUMERIC = 1;
- static const STRING = 2;
- static const SYMBOL = 3;
- static const ASSIGNMENT = 4;
- static const DOT = 5;
- static const LPAREN = 6;
- static const RPAREN = 7;
- static const LBRACE = 8;
- static const RBRACE = 9;
- static const LSQUARE = 10;
- static const RSQUARE = 11;
- static const COMMA = 12;
- static const QUERY = 13;
- static const COLON = 14;
- static const SEMICOLON = 15;
- static const HASH = 16;
- static const WHITESPACE = 17;
- static const OTHER = 18;
-
- // Make sure that ]] is two symbols.
- bool singleCharCategory(int category) => category >= DOT;
-
- static String categoryToString(int cat) {
- switch (cat) {
- case NONE: return "NONE";
- case ALPHA: return "ALPHA";
- case NUMERIC: return "NUMERIC";
- case SYMBOL: return "SYMBOL";
- case ASSIGNMENT: return "ASSIGNMENT";
- case DOT: return "DOT";
- case LPAREN: return "LPAREN";
- case RPAREN: return "RPAREN";
- case LBRACE: return "LBRACE";
- case RBRACE: return "RBRACE";
- case LSQUARE: return "LSQUARE";
- case RSQUARE: return "RSQUARE";
- case STRING: return "STRING";
- case COMMA: return "COMMA";
- case QUERY: return "QUERY";
- case COLON: return "COLON";
- case SEMICOLON: return "SEMICOLON";
- case HASH: return "HASH";
- case WHITESPACE: return "WHITESPACE";
- case OTHER: return "OTHER";
- }
- return "Unknown: $cat";
- }
-
- static const CATEGORIES = const <int>[
- OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, // 0-7
- OTHER, WHITESPACE, WHITESPACE, OTHER, OTHER, WHITESPACE, // 8-13
- OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, // 14-21
- OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, // 22-29
- OTHER, OTHER, WHITESPACE, // 30-32
- SYMBOL, OTHER, HASH, ALPHA, SYMBOL, SYMBOL, OTHER, // !"#$%&´
- LPAREN, RPAREN, SYMBOL, SYMBOL, COMMA, SYMBOL, DOT, SYMBOL, // ()*+,-./
- NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, // 01234
- NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, // 56789
- COLON, SEMICOLON, SYMBOL, SYMBOL, SYMBOL, QUERY, OTHER, // :;<=>?@
- ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // ABCDEFGH
- ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // IJKLMNOP
- ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // QRSTUVWX
- ALPHA, ALPHA, LSQUARE, OTHER, RSQUARE, SYMBOL, ALPHA, OTHER, // YZ[\]^_'
- ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // abcdefgh
- ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // ijklmnop
- ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // qrstuvwx
- ALPHA, ALPHA, LBRACE, SYMBOL, RBRACE, SYMBOL]; // yz{|}~
-
- // This must be a >= the highest precedence number handled by parseBinary.
- static var HIGHEST_PARSE_BINARY_PRECEDENCE = 16;
- static bool isAssignment(String symbol) => BINARY_PRECEDENCE[symbol] == 17;
-
- // From https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence
- static final BINARY_PRECEDENCE = {
- '+=': 17, '-=': 17, '*=': 17, '/=': 17, '%=': 17, '^=': 17, '|=': 17,
- '&=': 17, '<<=': 17, '>>=': 17, '>>>=': 17, '=': 17,
- '||': 14,
- '&&': 13,
- '|': 12,
- '^': 11,
- '&': 10,
- '!=': 9, '==': 9, '!==': 9, '===': 9,
- '<': 8, '<=': 8, '>=': 8, '>': 8, 'in': 8, 'instanceof': 8,
- '<<': 7, '>>': 7, '>>>': 7,
- '+': 6, '-': 6,
- '*': 5, '/': 5, '%': 5
- };
- static final UNARY_OPERATORS =
- ['++', '--', '+', '-', '~', '!', 'typeof', 'void', 'delete', 'await']
- .toSet();
-
- static final OPERATORS_THAT_LOOK_LIKE_IDENTIFIERS =
- ['typeof', 'void', 'delete', 'in', 'instanceof', 'await'].toSet();
-
- static int category(int code) {
- if (code >= CATEGORIES.length) return OTHER;
- return CATEGORIES[code];
- }
-
- String getDelimited(int startPosition) {
- position = startPosition;
- int delimiter = src.codeUnitAt(startPosition);
- int currentCode;
- do {
- position++;
- if (position >= src.length) error("Unterminated literal");
- currentCode = src.codeUnitAt(position);
- if (currentCode == charCodes.$LF) error("Unterminated literal");
- if (currentCode == charCodes.$BACKSLASH) {
- if (++position >= src.length) error("Unterminated literal");
- int escaped = src.codeUnitAt(position);
- if (escaped == charCodes.$x || escaped == charCodes.$X ||
- escaped == charCodes.$u || escaped == charCodes.$U ||
- category(escaped) == NUMERIC) {
- error('Numeric and hex escapes are not allowed in literals');
- }
- }
- } while (currentCode != delimiter);
- position++;
- return src.substring(lastPosition, position);
- }
-
- void getToken() {
- skippedNewline = false;
- for (;;) {
- if (position >= src.length) break;
- int code = src.codeUnitAt(position);
- // Skip '//' and '/*' style comments.
- if (code == charCodes.$SLASH &&
- position + 1 < src.length) {
- if (src.codeUnitAt(position + 1) == charCodes.$SLASH) {
- int nextPosition = src.indexOf('\n', position);
- if (nextPosition == -1) nextPosition = src.length;
- position = nextPosition;
- continue;
- } else if (src.codeUnitAt(position + 1) == charCodes.$STAR) {
- int nextPosition = src.indexOf('*/', position + 2);
- if (nextPosition == -1) error('Unterminated comment');
- position = nextPosition + 2;
- continue;
- }
- }
- if (category(code) != WHITESPACE) break;
- if (code == charCodes.$LF) skippedNewline = true;
- ++position;
- }
-
- if (position == src.length) {
- lastCategory = NONE;
- lastToken = null;
- lastPosition = position;
- return;
- }
- int code = src.codeUnitAt(position);
- lastPosition = position;
- if (code == charCodes.$SQ || code == charCodes.$DQ) {
- // String literal.
- lastCategory = STRING;
- lastToken = getDelimited(position);
- } else if (code == charCodes.$0 &&
- position + 2 < src.length &&
- src.codeUnitAt(position + 1) == charCodes.$x) {
- // Hex literal.
- for (position += 2; position < src.length; position++) {
- int cat = category(src.codeUnitAt(position));
- if (cat != NUMERIC && cat != ALPHA) break;
- }
- lastCategory = NUMERIC;
- lastToken = src.substring(lastPosition, position);
- int.parse(lastToken, onError: (_) {
- error("Unparseable number");
- });
- } else if (code == charCodes.$SLASH) {
- // Tokens that start with / are special due to regexp literals.
- lastCategory = SYMBOL;
- position++;
- if (position < src.length && src.codeUnitAt(position) == charCodes.$EQ) {
- position++;
- }
- lastToken = src.substring(lastPosition, position);
- } else {
- // All other tokens handled here.
- int cat = category(src.codeUnitAt(position));
- int newCat;
- do {
- position++;
- if (position == src.length) break;
- int code = src.codeUnitAt(position);
- // Special code to disallow ! and / in non-first position in token, so
- // that !! parses as two tokens and != parses as one, while =/ parses
- // as a an equals token followed by a regexp literal start.
- newCat = (code == charCodes.$BANG || code == charCodes.$SLASH)
- ? NONE
- : category(code);
- } while (!singleCharCategory(cat) &&
- (cat == newCat ||
- (cat == ALPHA && newCat == NUMERIC) || // eg. level42.
- (cat == NUMERIC && newCat == DOT))); // eg. 3.1415
- lastCategory = cat;
- lastToken = src.substring(lastPosition, position);
- if (cat == NUMERIC) {
- double.parse(lastToken, (_) {
- error("Unparseable number");
- });
- } else if (cat == SYMBOL) {
- int binaryPrecendence = BINARY_PRECEDENCE[lastToken];
- if (binaryPrecendence == null && !UNARY_OPERATORS.contains(lastToken)) {
- error("Unknown operator");
- }
- if (isAssignment(lastToken)) lastCategory = ASSIGNMENT;
- } else if (cat == ALPHA) {
- if (OPERATORS_THAT_LOOK_LIKE_IDENTIFIERS.contains(lastToken)) {
- lastCategory = SYMBOL;
- }
- }
- }
- }
-
- void expectCategory(int cat) {
- if (cat != lastCategory) error("Expected ${categoryToString(cat)}");
- getToken();
- }
-
- bool acceptCategory(int cat) {
- if (cat == lastCategory) {
- getToken();
- return true;
- }
- return false;
- }
-
- void expectSemicolon() {
- if (acceptSemicolon()) return;
- error('Expected SEMICOLON');
- }
-
- bool acceptSemicolon() {
- // Accept semicolon or automatically inserted semicolon before close brace.
- // Miniparser forbids other kinds of semicolon insertion.
- if (RBRACE == lastCategory) return true;
- if (NONE == lastCategory) return true; // end of input
- if (skippedNewline) {
- error('No automatic semicolon insertion at preceding newline');
- }
- return acceptCategory(SEMICOLON);
- }
-
- bool acceptString(String string) {
- if (lastToken == string) {
- getToken();
- return true;
- }
- return false;
- }
-
- void error(message) {
- throw new MiniJsParserError(this, message);
- }
-
- /// Returns either the name for the hole, or its integer position.
- parseHash() {
- String holeName = lastToken;
- if (acceptCategory(ALPHA)) {
- // Named hole. Example: 'function #funName() { ... }'
- if (hasPositionalHoles) {
- error('Holes must all be positional or named. $holeName');
- }
- return holeName;
- } else {
- if (hasNamedHoles) {
- error('Holes must all be positional or named. $holeName');
- }
- int position = interpolatedValues.length;
- return position;
- }
- }
-
- Expression parsePrimary() {
- String last = lastToken;
- if (acceptCategory(ALPHA)) {
- if (last == "true") {
- return new LiteralBool(true);
- } else if (last == "false") {
- return new LiteralBool(false);
- } else if (last == "null") {
- return new LiteralNull();
- } else if (last == "function") {
- return parseFunctionExpression();
- } else if (last == "this") {
- return new This();
- } else {
- return new VariableUse(last);
- }
- } else if (acceptCategory(LPAREN)) {
- Expression expression = parseExpression();
- expectCategory(RPAREN);
- return expression;
- } else if (acceptCategory(STRING)) {
- return new LiteralString(last);
- } else if (acceptCategory(NUMERIC)) {
- return new LiteralNumber(last);
- } else if (acceptCategory(LBRACE)) {
- return parseObjectInitializer();
- } else if (acceptCategory(LSQUARE)) {
- var values = <Expression>[];
-
- while (true) {
- if (acceptCategory(COMMA)) {
- values.add(new ArrayHole());
- continue;
- }
- if (acceptCategory(RSQUARE)) break;
- values.add(parseAssignment());
- if (acceptCategory(RSQUARE)) break;
- expectCategory(COMMA);
- }
- return new ArrayInitializer(values);
- } else if (last != null && last.startsWith("/")) {
- String regexp = getDelimited(lastPosition);
- getToken();
- String flags = lastToken;
- if (!acceptCategory(ALPHA)) flags = "";
- Expression expression = new RegExpLiteral(regexp + flags);
- return expression;
- } else if (acceptCategory(HASH)) {
- var nameOrPosition = parseHash();
- InterpolatedExpression expression =
- new InterpolatedExpression(nameOrPosition);
- interpolatedValues.add(expression);
- return expression;
- } else {
- error("Expected primary expression");
- return null;
- }
- }
-
- Expression parseFunctionExpression() {
- String last = lastToken;
- if (acceptCategory(ALPHA)) {
- String functionName = last;
- return new NamedFunction(new VariableDeclaration(functionName),
- parseFun());
- }
- return parseFun();
- }
-
- Expression parseFun() {
- List<Parameter> params = <Parameter>[];
-
- expectCategory(LPAREN);
- if (!acceptCategory(RPAREN)) {
- for (;;) {
- if (acceptCategory(HASH)) {
- var nameOrPosition = parseHash();
- InterpolatedParameter parameter =
- new InterpolatedParameter(nameOrPosition);
- interpolatedValues.add(parameter);
- params.add(parameter);
- } else {
- String argumentName = lastToken;
- expectCategory(ALPHA);
- params.add(new Parameter(argumentName));
- }
- if (acceptCategory(COMMA)) continue;
- expectCategory(RPAREN);
- break;
- }
- }
- AsyncModifier asyncModifier;
- if (acceptString('async')) {
- if (acceptString('*')) {
- asyncModifier = const AsyncModifier.asyncStar();
- } else {
- asyncModifier = const AsyncModifier.async();
- }
- } else if (acceptString('sync')) {
- if (!acceptString('*')) error("Only sync* is valid - sync is implied");
- asyncModifier = const AsyncModifier.syncStar();
- } else {
- asyncModifier = const AsyncModifier.sync();
- }
- expectCategory(LBRACE);
- Block block = parseBlock();
- return new Fun(params, block, asyncModifier: asyncModifier);
- }
-
- Expression parseObjectInitializer() {
- List<Property> properties = <Property>[];
- for (;;) {
- if (acceptCategory(RBRACE)) break;
- // Limited subset: keys are identifiers, no 'get' or 'set' properties.
- Literal propertyName;
- String identifier = lastToken;
- if (acceptCategory(ALPHA)) {
- propertyName = new LiteralString('"$identifier"');
- } else if (acceptCategory(STRING)) {
- propertyName = new LiteralString(identifier);
- } else if (acceptCategory(SYMBOL)) { // e.g. void
- propertyName = new LiteralString('"$identifier"');
- } else if (acceptCategory(HASH)) {
- var nameOrPosition = parseHash();
- InterpolatedLiteral interpolatedLiteral =
- new InterpolatedLiteral(nameOrPosition);
- interpolatedValues.add(interpolatedLiteral);
- propertyName = interpolatedLiteral;
- } else {
- error('Expected property name');
- }
- expectCategory(COLON);
- Expression value = parseAssignment();
- properties.add(new Property(propertyName, value));
- if (acceptCategory(RBRACE)) break;
- expectCategory(COMMA);
- }
- return new ObjectInitializer(properties);
- }
-
- Expression parseMember() {
- Expression receiver = parsePrimary();
- while (true) {
- if (acceptCategory(DOT)) {
- receiver = getDotRhs(receiver);
- } else if (acceptCategory(LSQUARE)) {
- Expression inBraces = parseExpression();
- expectCategory(RSQUARE);
- receiver = new PropertyAccess(receiver, inBraces);
- } else {
- break;
- }
- }
- return receiver;
- }
-
- Expression parseCall() {
- bool constructor = acceptString("new");
- Expression receiver = parseMember();
- while (true) {
- if (acceptCategory(LPAREN)) {
- final arguments = <Expression>[];
- if (!acceptCategory(RPAREN)) {
- while (true) {
- Expression argument = parseAssignment();
- arguments.add(argument);
- if (acceptCategory(RPAREN)) break;
- expectCategory(COMMA);
- }
- }
- receiver = constructor ?
- new New(receiver, arguments) :
- new Call(receiver, arguments);
- constructor = false;
- } else if (!constructor && acceptCategory(LSQUARE)) {
- Expression inBraces = parseExpression();
- expectCategory(RSQUARE);
- receiver = new PropertyAccess(receiver, inBraces);
- } else if (!constructor && acceptCategory(DOT)) {
- receiver = getDotRhs(receiver);
- } else {
- // JS allows new without (), but we don't.
- if (constructor) error("Parentheses are required for new");
- break;
- }
- }
- return receiver;
- }
-
- Expression getDotRhs(Expression receiver) {
- if (acceptCategory(HASH)) {
- var nameOrPosition = parseHash();
- InterpolatedSelector property = new InterpolatedSelector(nameOrPosition);
- interpolatedValues.add(property);
- return new PropertyAccess(receiver, property);
- }
- String identifier = lastToken;
- // In ES5 keywords like delete and continue are allowed as property
- // names, and the IndexedDB API uses that, so we need to allow it here.
- if (acceptCategory(SYMBOL)) {
- if (!OPERATORS_THAT_LOOK_LIKE_IDENTIFIERS.contains(identifier)) {
- error("Expected alphanumeric identifier");
- }
- } else {
- expectCategory(ALPHA);
- }
- return new PropertyAccess.field(receiver, identifier);
- }
-
- Expression parsePostfix() {
- Expression expression = parseCall();
- String operator = lastToken;
- // JavaScript grammar is:
- // LeftHandSideExpression [no LineTerminator here] ++
- if (lastCategory == SYMBOL &&
- !skippedNewline &&
- (acceptString("++") || acceptString("--"))) {
- return new Postfix(operator, expression);
- }
- // If we don't accept '++' or '--' due to skippedNewline a newline, no other
- // part of the parser will accept the token and we will get an error at the
- // whole expression level.
- return expression;
- }
-
- Expression parseUnaryHigh() {
- String operator = lastToken;
- if (lastCategory == SYMBOL && UNARY_OPERATORS.contains(operator) &&
- (acceptString("++") || acceptString("--") || acceptString('await'))) {
- if (operator == "await") return new Await(parsePostfix());
- return new Prefix(operator, parsePostfix());
- }
- return parsePostfix();
- }
-
- Expression parseUnaryLow() {
- String operator = lastToken;
- if (lastCategory == SYMBOL && UNARY_OPERATORS.contains(operator) &&
- operator != "++" && operator != "--") {
- expectCategory(SYMBOL);
- if (operator == "await") return new Await(parsePostfix());
- return new Prefix(operator, parseUnaryLow());
- }
- return parseUnaryHigh();
- }
-
- Expression parseBinary(int maxPrecedence) {
- Expression lhs = parseUnaryLow();
- int minPrecedence;
- String lastSymbol;
- Expression rhs; // This is null first time around.
- while (true) {
- String symbol = lastToken;
- if (lastCategory != SYMBOL ||
- !BINARY_PRECEDENCE.containsKey(symbol) ||
- BINARY_PRECEDENCE[symbol] > maxPrecedence) {
- break;
- }
- expectCategory(SYMBOL);
- if (rhs == null || BINARY_PRECEDENCE[symbol] >= minPrecedence) {
- if (rhs != null) lhs = new Binary(lastSymbol, lhs, rhs);
- minPrecedence = BINARY_PRECEDENCE[symbol];
- rhs = parseUnaryLow();
- lastSymbol = symbol;
- } else {
- Expression higher = parseBinary(BINARY_PRECEDENCE[symbol]);
- rhs = new Binary(symbol, rhs, higher);
- }
- }
- if (rhs == null) return lhs;
- return new Binary(lastSymbol, lhs, rhs);
- }
-
- Expression parseConditional() {
- Expression lhs = parseBinary(HIGHEST_PARSE_BINARY_PRECEDENCE);
- if (!acceptCategory(QUERY)) return lhs;
- Expression ifTrue = parseAssignment();
- expectCategory(COLON);
- Expression ifFalse = parseAssignment();
- return new Conditional(lhs, ifTrue, ifFalse);
- }
-
-
- Expression parseAssignment() {
- Expression lhs = parseConditional();
- String assignmentOperator = lastToken;
- if (acceptCategory(ASSIGNMENT)) {
- Expression rhs = parseAssignment();
- if (assignmentOperator == "=") {
- return new Assignment(lhs, rhs);
- } else {
- // Handle +=, -=, etc.
- String operator =
- assignmentOperator.substring(0, assignmentOperator.length - 1);
- return new Assignment.compound(lhs, operator, rhs);
- }
- }
- return lhs;
- }
-
- Expression parseExpression() {
- Expression expression = parseAssignment();
- while (acceptCategory(COMMA)) {
- Expression right = parseAssignment();
- expression = new Binary(',', expression, right);
- }
- return expression;
- }
-
- VariableDeclarationList parseVariableDeclarationList() {
- String firstVariable = lastToken;
- expectCategory(ALPHA);
- return finishVariableDeclarationList(firstVariable);
- }
-
- VariableDeclarationList finishVariableDeclarationList(String firstVariable) {
- var initialization = [];
-
- void declare(String variable) {
- Expression initializer = null;
- if (acceptString("=")) {
- initializer = parseAssignment();
- }
- var declaration = new VariableDeclaration(variable);
- initialization.add(new VariableInitialization(declaration, initializer));
- }
-
- declare(firstVariable);
- while (acceptCategory(COMMA)) {
- String variable = lastToken;
- expectCategory(ALPHA);
- declare(variable);
- }
- return new VariableDeclarationList(initialization);
- }
-
- Expression parseVarDeclarationOrExpression() {
- if (acceptString("var")) {
- return parseVariableDeclarationList();
- } else {
- return parseExpression();
- }
- }
-
- Expression expression() {
- Expression expression = parseVarDeclarationOrExpression();
- if (lastCategory != NONE || position != src.length) {
- error("Unparsed junk: ${categoryToString(lastCategory)}");
- }
- return expression;
- }
-
- Statement statement() {
- Statement statement = parseStatement();
- if (lastCategory != NONE || position != src.length) {
- error("Unparsed junk: ${categoryToString(lastCategory)}");
- }
- // TODO(sra): interpolated capture here?
- return statement;
- }
-
- Block parseBlock() {
- List<Statement> statements = <Statement>[];
-
- while (!acceptCategory(RBRACE)) {
- Statement statement = parseStatement();
- statements.add(statement);
- }
- return new Block(statements);
- }
-
- Statement parseStatement() {
- if (acceptCategory(LBRACE)) return parseBlock();
-
- if (acceptCategory(SEMICOLON)) return new EmptyStatement();
-
- if (lastCategory == ALPHA) {
- if (acceptString('return')) return parseReturn();
-
- if (acceptString('throw')) return parseThrow();
-
- if (acceptString('break')) {
- return parseBreakOrContinue((label) => new Break(label));
- }
-
- if (acceptString('continue')) {
- return parseBreakOrContinue((label) => new Continue(label));
- }
-
- if (acceptString('if')) return parseIfThenElse();
-
- if (acceptString('for')) return parseFor();
-
- if (acceptString('function')) return parseFunctionDeclaration();
-
- if (acceptString('try')) return parseTry();
-
- if (acceptString('var')) {
- Expression declarations = parseVariableDeclarationList();
- expectSemicolon();
- return new ExpressionStatement(declarations);
- }
-
- if (acceptString('while')) return parseWhile();
-
- if (acceptString('do')) return parseDo();
-
- if (acceptString('switch')) return parseSwitch();
-
- if (lastToken == 'case') error("Case outside switch.");
-
- if (lastToken == 'default') error("Default outside switch.");
-
- if (lastToken == 'yield') return parseYield();
-
- if (lastToken == 'with') {
- error('Not implemented in mini parser');
- }
-
- }
-
- bool checkForInterpolatedStatement = lastCategory == HASH;
-
- Expression expression = parseExpression();
-
- if (expression is VariableUse && acceptCategory(COLON)) {
- return new LabeledStatement(expression.name, parseStatement());
- }
-
- expectSemicolon();
-
- if (checkForInterpolatedStatement) {
- // 'Promote' the interpolated expression `#;` to an interpolated
- // statement.
- if (expression is InterpolatedExpression) {
- assert(identical(interpolatedValues.last, expression));
- InterpolatedStatement statement =
- new InterpolatedStatement(expression.nameOrPosition);
- interpolatedValues[interpolatedValues.length - 1] = statement;
- return statement;
- }
- }
-
- return new ExpressionStatement(expression);
- }
-
- Statement parseReturn() {
- if (acceptSemicolon()) return new Return();
- Expression expression = parseExpression();
- expectSemicolon();
- return new Return(expression);
- }
-
- Statement parseYield() {
- bool hasStar = acceptString('*');
- Expression expression = parseExpression();
- expectSemicolon();
- return new DartYield(expression, hasStar);
- }
-
- Statement parseThrow() {
- if (skippedNewline) error('throw expression must be on same line');
- Expression expression = parseExpression();
- expectSemicolon();
- return new Throw(expression);
- }
-
- Statement parseBreakOrContinue(constructor) {
- var identifier = lastToken;
- if (!skippedNewline && acceptCategory(ALPHA)) {
- expectSemicolon();
- return constructor(identifier);
- }
- expectSemicolon();
- return constructor(null);
- }
-
- Statement parseIfThenElse() {
- expectCategory(LPAREN);
- Expression condition = parseExpression();
- expectCategory(RPAREN);
- Statement thenStatement = parseStatement();
- if (acceptString('else')) {
- // Resolves dangling else by binding 'else' to closest 'if'.
- Statement elseStatement = parseStatement();
- return new If(condition, thenStatement, elseStatement);
- } else {
- return new If.noElse(condition, thenStatement);
- }
- }
-
- Statement parseFor() {
- // For-init-condition-increment style loops are fully supported.
- //
- // Only one for-in variant is currently implemented:
- //
- // for (var variable in Expression) Statement
- //
- Statement finishFor(Expression init) {
- Expression condition = null;
- if (!acceptCategory(SEMICOLON)) {
- condition = parseExpression();
- expectCategory(SEMICOLON);
- }
- Expression update = null;
- if (!acceptCategory(RPAREN)) {
- update = parseExpression();
- expectCategory(RPAREN);
- }
- Statement body = parseStatement();
- return new For(init, condition, update, body);
- }
-
- expectCategory(LPAREN);
- if (acceptCategory(SEMICOLON)) {
- return finishFor(null);
- }
-
- if (acceptString('var')) {
- String identifier = lastToken;
- expectCategory(ALPHA);
- if (acceptString('in')) {
- Expression objectExpression = parseExpression();
- expectCategory(RPAREN);
- Statement body = parseStatement();
- return new ForIn(
- new VariableDeclarationList([
- new VariableInitialization(
- new VariableDeclaration(identifier), null)]),
- objectExpression,
- body);
- }
- Expression declarations = finishVariableDeclarationList(identifier);
- expectCategory(SEMICOLON);
- return finishFor(declarations);
- }
-
- Expression init = parseExpression();
- expectCategory(SEMICOLON);
- return finishFor(init);
- }
-
- Statement parseFunctionDeclaration() {
- String name = lastToken;
- expectCategory(ALPHA);
- Expression fun = parseFun();
- return new FunctionDeclaration(new VariableDeclaration(name), fun);
- }
-
- Statement parseTry() {
- expectCategory(LBRACE);
- Block body = parseBlock();
- String token = lastToken;
- Catch catchPart = null;
- if (acceptString('catch')) catchPart = parseCatch();
- Block finallyPart = null;
- if (acceptString('finally')) {
- expectCategory(LBRACE);
- finallyPart = parseBlock();
- } else {
- if (catchPart == null) error("expected 'finally'");
- }
- return new Try(body, catchPart, finallyPart);
- }
-
- SwitchClause parseSwitchClause() {
- Expression expression = null;
- if (acceptString('case')) {
- expression = parseExpression();
- expectCategory(COLON);
- } else {
- if (!acceptString('default')) {
- error('expected case or default');
- }
- expectCategory(COLON);
- }
- List statements = new List<Statement>();
- while (lastCategory != RBRACE &&
- lastToken != 'case' &&
- lastToken != 'default') {
- statements.add(parseStatement());
- }
- return expression == null
- ? new Default(new Block(statements))
- : new Case(expression, new Block(statements));
- }
-
- Statement parseWhile() {
- expectCategory(LPAREN);
- Expression condition = parseExpression();
- expectCategory(RPAREN);
- Statement body = parseStatement();
- return new While(condition, body);
- }
-
- Statement parseDo() {
- Statement body = parseStatement();
- if (lastToken != "while") error("Missing while after do body.");
- getToken();
- expectCategory(LPAREN);
- Expression condition = parseExpression();
- expectCategory(RPAREN);
- expectSemicolon();
- return new Do(body, condition);
- }
-
- Statement parseSwitch() {
- expectCategory(LPAREN);
- Expression key = parseExpression();
- expectCategory(RPAREN);
- expectCategory(LBRACE);
- List<SwitchClause> clauses = new List<SwitchClause>();
- while(lastCategory != RBRACE) {
- clauses.add(parseSwitchClause());
- }
- expectCategory(RBRACE);
- return new Switch(key, clauses);
- }
-
- Catch parseCatch() {
- expectCategory(LPAREN);
- String identifier = lastToken;
- expectCategory(ALPHA);
- expectCategory(RPAREN);
- expectCategory(LBRACE);
- Block body = parseBlock();
- return new Catch(new VariableDeclaration(identifier), body);
- }
-}
diff --git a/pkg/compiler/lib/src/js/js.dart b/pkg/compiler/lib/src/js/js.dart
index a5bbec4..ec8766a 100644
--- a/pkg/compiler/lib/src/js/js.dart
+++ b/pkg/compiler/lib/src/js/js.dart
@@ -4,9 +4,8 @@
library js;
-// TODO(sra): This will become a package import.
-import 'js_ast.dart';
-export 'js_ast.dart';
+import 'package:js_ast/js_ast.dart';
+export 'package:js_ast/js_ast.dart';
import '../io/code_output.dart' show CodeBuffer;
import '../io/source_information.dart' show SourceInformation;
diff --git a/pkg/compiler/lib/src/js/js_ast.dart b/pkg/compiler/lib/src/js/js_ast.dart
deleted file mode 100644
index ee8289e..0000000
--- a/pkg/compiler/lib/src/js/js_ast.dart
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library js_ast;
-
-import 'precedence.dart';
-import 'characters.dart' as charCodes;
-
-part 'nodes.dart';
-part 'builder.dart';
-part 'printer.dart';
-part 'template.dart';
diff --git a/pkg/compiler/lib/src/js/nodes.dart b/pkg/compiler/lib/src/js/nodes.dart
deleted file mode 100644
index 92446fa..0000000
--- a/pkg/compiler/lib/src/js/nodes.dart
+++ /dev/null
@@ -1,1148 +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 js_ast;
-
-abstract class NodeVisitor<T> {
- T visitProgram(Program node);
-
- T visitBlock(Block node);
- T visitExpressionStatement(ExpressionStatement node);
- T visitEmptyStatement(EmptyStatement node);
- T visitIf(If node);
- T visitFor(For node);
- T visitForIn(ForIn node);
- T visitWhile(While node);
- T visitDo(Do node);
- T visitContinue(Continue node);
- T visitBreak(Break node);
- T visitReturn(Return node);
- T visitThrow(Throw node);
- T visitTry(Try node);
- T visitCatch(Catch node);
- T visitSwitch(Switch node);
- T visitCase(Case node);
- T visitDefault(Default node);
- T visitFunctionDeclaration(FunctionDeclaration node);
- T visitLabeledStatement(LabeledStatement node);
- T visitLiteralStatement(LiteralStatement node);
- T visitDartYield(DartYield node);
-
- T visitLiteralExpression(LiteralExpression node);
- T visitVariableDeclarationList(VariableDeclarationList node);
- T visitAssignment(Assignment node);
- T visitVariableInitialization(VariableInitialization node);
- T visitConditional(Conditional cond);
- T visitNew(New node);
- T visitCall(Call node);
- T visitBinary(Binary node);
- T visitPrefix(Prefix node);
- T visitPostfix(Postfix node);
-
- T visitVariableUse(VariableUse node);
- T visitThis(This node);
- T visitVariableDeclaration(VariableDeclaration node);
- T visitParameter(Parameter node);
- T visitAccess(PropertyAccess node);
-
- T visitNamedFunction(NamedFunction node);
- T visitFun(Fun node);
-
- T visitLiteralBool(LiteralBool node);
- T visitLiteralString(LiteralString node);
- T visitLiteralNumber(LiteralNumber node);
- T visitLiteralNull(LiteralNull node);
-
- T visitArrayInitializer(ArrayInitializer node);
- T visitArrayHole(ArrayHole node);
- T visitObjectInitializer(ObjectInitializer node);
- T visitProperty(Property node);
- T visitRegExpLiteral(RegExpLiteral node);
-
- T visitAwait(Await node);
-
- T visitComment(Comment node);
-
- T visitInterpolatedExpression(InterpolatedExpression node);
- T visitInterpolatedLiteral(InterpolatedLiteral node);
- T visitInterpolatedParameter(InterpolatedParameter node);
- T visitInterpolatedSelector(InterpolatedSelector node);
- T visitInterpolatedStatement(InterpolatedStatement node);
-}
-
-class BaseVisitor<T> implements NodeVisitor<T> {
- T visitNode(Node node) {
- node.visitChildren(this);
- return null;
- }
-
- T visitProgram(Program node) => visitNode(node);
-
- T visitStatement(Statement node) => visitNode(node);
- T visitLoop(Loop node) => visitStatement(node);
- T visitJump(Statement node) => visitStatement(node);
-
- T visitBlock(Block node) => visitStatement(node);
- T visitExpressionStatement(ExpressionStatement node)
- => visitStatement(node);
- T visitEmptyStatement(EmptyStatement node) => visitStatement(node);
- T visitIf(If node) => visitStatement(node);
- T visitFor(For node) => visitLoop(node);
- T visitForIn(ForIn node) => visitLoop(node);
- T visitWhile(While node) => visitLoop(node);
- T visitDo(Do node) => visitLoop(node);
- T visitContinue(Continue node) => visitJump(node);
- T visitBreak(Break node) => visitJump(node);
- T visitReturn(Return node) => visitJump(node);
- T visitThrow(Throw node) => visitJump(node);
- T visitTry(Try node) => visitStatement(node);
- T visitSwitch(Switch node) => visitStatement(node);
- T visitFunctionDeclaration(FunctionDeclaration node)
- => visitStatement(node);
- T visitLabeledStatement(LabeledStatement node) => visitStatement(node);
- T visitLiteralStatement(LiteralStatement node) => visitStatement(node);
-
- T visitCatch(Catch node) => visitNode(node);
- T visitCase(Case node) => visitNode(node);
- T visitDefault(Default node) => visitNode(node);
-
- T visitExpression(Expression node) => visitNode(node);
- T visitVariableReference(VariableReference node) => visitExpression(node);
-
- T visitLiteralExpression(LiteralExpression node) => visitExpression(node);
- T visitVariableDeclarationList(VariableDeclarationList node)
- => visitExpression(node);
- T visitAssignment(Assignment node) => visitExpression(node);
- T visitVariableInitialization(VariableInitialization node) {
- if (node.value != null) {
- return visitAssignment(node);
- } else {
- return visitExpression(node);
- }
- }
- T visitConditional(Conditional node) => visitExpression(node);
- T visitNew(New node) => visitExpression(node);
- T visitCall(Call node) => visitExpression(node);
- T visitBinary(Binary node) => visitExpression(node);
- T visitPrefix(Prefix node) => visitExpression(node);
- T visitPostfix(Postfix node) => visitExpression(node);
- T visitAccess(PropertyAccess node) => visitExpression(node);
-
- T visitVariableUse(VariableUse node) => visitVariableReference(node);
- T visitVariableDeclaration(VariableDeclaration node)
- => visitVariableReference(node);
- T visitParameter(Parameter node) => visitVariableDeclaration(node);
- T visitThis(This node) => visitParameter(node);
-
- T visitNamedFunction(NamedFunction node) => visitExpression(node);
- T visitFun(Fun node) => visitExpression(node);
-
- T visitLiteral(Literal node) => visitExpression(node);
-
- T visitLiteralBool(LiteralBool node) => visitLiteral(node);
- T visitLiteralString(LiteralString node) => visitLiteral(node);
- T visitLiteralNumber(LiteralNumber node) => visitLiteral(node);
- T visitLiteralNull(LiteralNull node) => visitLiteral(node);
-
- T visitArrayInitializer(ArrayInitializer node) => visitExpression(node);
- T visitArrayHole(ArrayHole node) => visitExpression(node);
- T visitObjectInitializer(ObjectInitializer node) => visitExpression(node);
- T visitProperty(Property node) => visitNode(node);
- T visitRegExpLiteral(RegExpLiteral node) => visitExpression(node);
-
- T visitInterpolatedNode(InterpolatedNode node) => visitNode(node);
-
- T visitInterpolatedExpression(InterpolatedExpression node)
- => visitInterpolatedNode(node);
- T visitInterpolatedLiteral(InterpolatedLiteral node)
- => visitInterpolatedNode(node);
- T visitInterpolatedParameter(InterpolatedParameter node)
- => visitInterpolatedNode(node);
- T visitInterpolatedSelector(InterpolatedSelector node)
- => visitInterpolatedNode(node);
- T visitInterpolatedStatement(InterpolatedStatement node)
- => visitInterpolatedNode(node);
-
- // Ignore comments by default.
- T visitComment(Comment node) => null;
-
- T visitAwait(Await node) => visitExpression(node);
- T visitDartYield(DartYield node) => visitStatement(node);
-}
-
-/// This tag interface has no behaviour but must be implemented by any class
-/// that is to be stored on a [Node] as source information.
-abstract class JavaScriptNodeSourceInformation {}
-
-abstract class Node {
- JavaScriptNodeSourceInformation get sourceInformation => _sourceInformation;
-
- JavaScriptNodeSourceInformation _sourceInformation;
-
- accept(NodeVisitor visitor);
- void visitChildren(NodeVisitor visitor);
-
- // Shallow clone of node. Does not clone positions since the only use of this
- // private method is create a copy with a new position.
- Node _clone();
-
- // Returns a node equivalent to [this], but with new source position and end
- // source position.
- Node withSourceInformation(
- JavaScriptNodeSourceInformation sourceInformation) {
- if (sourceInformation == _sourceInformation) {
- return this;
- }
- Node clone = _clone();
- // TODO(sra): Should existing data be 'sticky' if we try to overwrite with
- // `null`?
- clone._sourceInformation = sourceInformation;
- return clone;
- }
-
- VariableUse asVariableUse() => null;
-
- bool get isCommaOperator => false;
-
- Statement toStatement() {
- throw new UnsupportedError('toStatement');
- }
-}
-
-class Program extends Node {
- final List<Statement> body;
- Program(this.body);
-
- accept(NodeVisitor visitor) => visitor.visitProgram(this);
- void visitChildren(NodeVisitor visitor) {
- for (Statement statement in body) statement.accept(visitor);
- }
- Program _clone() => new Program(body);
-}
-
-abstract class Statement extends Node {
- Statement toStatement() => this;
-}
-
-class Block extends Statement {
- final List<Statement> statements;
- Block(this.statements);
- Block.empty() : this.statements = <Statement>[];
-
- accept(NodeVisitor visitor) => visitor.visitBlock(this);
- void visitChildren(NodeVisitor visitor) {
- for (Statement statement in statements) statement.accept(visitor);
- }
- Block _clone() => new Block(statements);
-}
-
-class ExpressionStatement extends Statement {
- final Expression expression;
- ExpressionStatement(this.expression);
-
- accept(NodeVisitor visitor) => visitor.visitExpressionStatement(this);
- void visitChildren(NodeVisitor visitor) { expression.accept(visitor); }
- ExpressionStatement _clone() => new ExpressionStatement(expression);
-}
-
-class EmptyStatement extends Statement {
- EmptyStatement();
-
- accept(NodeVisitor visitor) => visitor.visitEmptyStatement(this);
- void visitChildren(NodeVisitor visitor) {}
- EmptyStatement _clone() => new EmptyStatement();
-}
-
-class If extends Statement {
- final Expression condition;
- final Node then;
- final Node otherwise;
-
- If(this.condition, this.then, this.otherwise);
- If.noElse(this.condition, this.then) : this.otherwise = new EmptyStatement();
-
- bool get hasElse => otherwise is !EmptyStatement;
-
- accept(NodeVisitor visitor) => visitor.visitIf(this);
-
- void visitChildren(NodeVisitor visitor) {
- condition.accept(visitor);
- then.accept(visitor);
- otherwise.accept(visitor);
- }
-
- If _clone() => new If(condition, then, otherwise);
-}
-
-abstract class Loop extends Statement {
- final Statement body;
- Loop(this.body);
-}
-
-class For extends Loop {
- final Expression init;
- final Expression condition;
- final Expression update;
-
- For(this.init, this.condition, this.update, Statement body) : super(body);
-
- accept(NodeVisitor visitor) => visitor.visitFor(this);
-
- void visitChildren(NodeVisitor visitor) {
- if (init != null) init.accept(visitor);
- if (condition != null) condition.accept(visitor);
- if (update != null) update.accept(visitor);
- body.accept(visitor);
- }
-
- For _clone() => new For(init, condition, update, body);
-}
-
-class ForIn extends Loop {
- // Note that [VariableDeclarationList] is a subclass of [Expression].
- // Therefore we can type the leftHandSide as [Expression].
- final Expression leftHandSide;
- final Expression object;
-
- ForIn(this.leftHandSide, this.object, Statement body) : super(body);
-
- accept(NodeVisitor visitor) => visitor.visitForIn(this);
-
- void visitChildren(NodeVisitor visitor) {
- leftHandSide.accept(visitor);
- object.accept(visitor);
- body.accept(visitor);
- }
-
- ForIn _clone() => new ForIn(leftHandSide, object, body);
-}
-
-class While extends Loop {
- final Node condition;
-
- While(this.condition, Statement body) : super(body);
-
- accept(NodeVisitor visitor) => visitor.visitWhile(this);
-
- void visitChildren(NodeVisitor visitor) {
- condition.accept(visitor);
- body.accept(visitor);
- }
-
- While _clone() => new While(condition, body);
-}
-
-class Do extends Loop {
- final Expression condition;
-
- Do(Statement body, this.condition) : super(body);
-
- accept(NodeVisitor visitor) => visitor.visitDo(this);
-
- void visitChildren(NodeVisitor visitor) {
- body.accept(visitor);
- condition.accept(visitor);
- }
-
- Do _clone() => new Do(body, condition);
-}
-
-class Continue extends Statement {
- final String targetLabel; // Can be null.
-
- Continue(this.targetLabel);
-
- accept(NodeVisitor visitor) => visitor.visitContinue(this);
- void visitChildren(NodeVisitor visitor) {}
-
- Continue _clone() => new Continue(targetLabel);
-}
-
-class Break extends Statement {
- final String targetLabel; // Can be null.
-
- Break(this.targetLabel);
-
- accept(NodeVisitor visitor) => visitor.visitBreak(this);
- void visitChildren(NodeVisitor visitor) {}
-
- Break _clone() => new Break(targetLabel);
-}
-
-class Return extends Statement {
- final Expression value; // Can be null.
-
- Return([this.value = null]);
-
- accept(NodeVisitor visitor) => visitor.visitReturn(this);
-
- void visitChildren(NodeVisitor visitor) {
- if (value != null) value.accept(visitor);
- }
-
- Return _clone() => new Return(value);
-}
-
-class Throw extends Statement {
- final Expression expression;
-
- Throw(this.expression);
-
- accept(NodeVisitor visitor) => visitor.visitThrow(this);
-
- void visitChildren(NodeVisitor visitor) {
- expression.accept(visitor);
- }
-
- Throw _clone() => new Throw(expression);
-}
-
-class Try extends Statement {
- final Block body;
- final Catch catchPart; // Can be null if [finallyPart] is non-null.
- final Block finallyPart; // Can be null if [catchPart] is non-null.
-
- Try(this.body, this.catchPart, this.finallyPart) {
- assert(catchPart != null || finallyPart != null);
- }
-
- accept(NodeVisitor visitor) => visitor.visitTry(this);
-
- void visitChildren(NodeVisitor visitor) {
- body.accept(visitor);
- if (catchPart != null) catchPart.accept(visitor);
- if (finallyPart != null) finallyPart.accept(visitor);
- }
-
- Try _clone() => new Try(body, catchPart, finallyPart);
-}
-
-class Catch extends Node {
- final VariableDeclaration declaration;
- final Block body;
-
- Catch(this.declaration, this.body);
-
- accept(NodeVisitor visitor) => visitor.visitCatch(this);
-
- void visitChildren(NodeVisitor visitor) {
- declaration.accept(visitor);
- body.accept(visitor);
- }
-
- Catch _clone() => new Catch(declaration, body);
-}
-
-class Switch extends Statement {
- final Expression key;
- final List<SwitchClause> cases;
-
- Switch(this.key, this.cases);
-
- accept(NodeVisitor visitor) => visitor.visitSwitch(this);
-
- void visitChildren(NodeVisitor visitor) {
- key.accept(visitor);
- for (SwitchClause clause in cases) clause.accept(visitor);
- }
-
- Switch _clone() => new Switch(key, cases);
-}
-
-abstract class SwitchClause extends Node {
- final Block body;
-
- SwitchClause(this.body);
-}
-
-class Case extends SwitchClause {
- final Expression expression;
-
- Case(this.expression, Block body) : super(body);
-
- accept(NodeVisitor visitor) => visitor.visitCase(this);
-
- void visitChildren(NodeVisitor visitor) {
- expression.accept(visitor);
- body.accept(visitor);
- }
-
- Case _clone() => new Case(expression, body);
-}
-
-class Default extends SwitchClause {
- Default(Block body) : super(body);
-
- accept(NodeVisitor visitor) => visitor.visitDefault(this);
-
- void visitChildren(NodeVisitor visitor) {
- body.accept(visitor);
- }
-
- Default _clone() => new Default(body);
-}
-
-class FunctionDeclaration extends Statement {
- final VariableDeclaration name;
- final Fun function;
-
- FunctionDeclaration(this.name, this.function);
-
- accept(NodeVisitor visitor) => visitor.visitFunctionDeclaration(this);
-
- void visitChildren(NodeVisitor visitor) {
- name.accept(visitor);
- function.accept(visitor);
- }
-
- FunctionDeclaration _clone() => new FunctionDeclaration(name, function);
-}
-
-class LabeledStatement extends Statement {
- final String label;
- final Statement body;
-
- LabeledStatement(this.label, this.body);
-
- accept(NodeVisitor visitor) => visitor.visitLabeledStatement(this);
-
- void visitChildren(NodeVisitor visitor) {
- body.accept(visitor);
- }
-
- LabeledStatement _clone() => new LabeledStatement(label, body);
-}
-
-class LiteralStatement extends Statement {
- final String code;
-
- LiteralStatement(this.code);
-
- accept(NodeVisitor visitor) => visitor.visitLiteralStatement(this);
- void visitChildren(NodeVisitor visitor) { }
-
- LiteralStatement _clone() => new LiteralStatement(code);
-}
-
-// Not a real JavaScript node, but represents the yield statement from a dart
-// program translated to JavaScript.
-class DartYield extends Statement {
- final Expression expression;
-
- final bool hasStar;
-
- DartYield(this.expression, this.hasStar);
-
- accept(NodeVisitor visitor) => visitor.visitDartYield(this);
-
- void visitChildren(NodeVisitor visitor) {
- expression.accept(visitor);
- }
-
- DartYield _clone() => new DartYield(expression, hasStar);
-}
-
-abstract class Expression extends Node {
- int get precedenceLevel;
-
- Statement toStatement() => new ExpressionStatement(this);
-}
-
-class LiteralExpression extends Expression {
- final String template;
- final List<Expression> inputs;
-
- LiteralExpression(this.template) : inputs = const [];
- LiteralExpression.withData(this.template, this.inputs);
-
- accept(NodeVisitor visitor) => visitor.visitLiteralExpression(this);
-
- void visitChildren(NodeVisitor visitor) {
- if (inputs != null) {
- for (Expression expr in inputs) expr.accept(visitor);
- }
- }
-
- LiteralExpression _clone() =>
- new LiteralExpression.withData(template, inputs);
-
- // Code that uses JS must take care of operator precedences, and
- // put parenthesis if needed.
- int get precedenceLevel => PRIMARY;
-}
-
-/**
- * [VariableDeclarationList] is a subclass of [Expression] to simplify the
- * AST.
- */
-class VariableDeclarationList extends Expression {
- final List<VariableInitialization> declarations;
-
- VariableDeclarationList(this.declarations);
-
- accept(NodeVisitor visitor) => visitor.visitVariableDeclarationList(this);
-
- void visitChildren(NodeVisitor visitor) {
- for (VariableInitialization declaration in declarations) {
- declaration.accept(visitor);
- }
- }
-
- VariableDeclarationList _clone() => new VariableDeclarationList(declarations);
-
- int get precedenceLevel => EXPRESSION;
-}
-
-class Assignment extends Expression {
- final Expression leftHandSide;
- final String op; // Null, if the assignment is not compound.
- final Expression value; // May be null, for [VariableInitialization]s.
-
- Assignment(leftHandSide, value)
- : this.compound(leftHandSide, null, value);
- Assignment.compound(this.leftHandSide, this.op, this.value);
-
- int get precedenceLevel => ASSIGNMENT;
-
- bool get isCompound => op != null;
-
- accept(NodeVisitor visitor) => visitor.visitAssignment(this);
-
- void visitChildren(NodeVisitor visitor) {
- leftHandSide.accept(visitor);
- if (value != null) value.accept(visitor);
- }
-
- Assignment _clone() =>
- new Assignment.compound(leftHandSide, op, value);
-}
-
-class VariableInitialization extends Assignment {
- /** [value] may be null. */
- VariableInitialization(VariableDeclaration declaration, Expression value)
- : super(declaration, value);
-
- VariableDeclaration get declaration => leftHandSide;
-
- accept(NodeVisitor visitor) => visitor.visitVariableInitialization(this);
-
- VariableInitialization _clone() =>
- new VariableInitialization(declaration, value);
-}
-
-class Conditional extends Expression {
- final Expression condition;
- final Expression then;
- final Expression otherwise;
-
- Conditional(this.condition, this.then, this.otherwise);
-
- accept(NodeVisitor visitor) => visitor.visitConditional(this);
-
- void visitChildren(NodeVisitor visitor) {
- condition.accept(visitor);
- then.accept(visitor);
- otherwise.accept(visitor);
- }
-
- Conditional _clone() => new Conditional(condition, then, otherwise);
-
- int get precedenceLevel => ASSIGNMENT;
-}
-
-class Call extends Expression {
- Expression target;
- List<Expression> arguments;
-
- Call(this.target, this.arguments);
-
- accept(NodeVisitor visitor) => visitor.visitCall(this);
-
- void visitChildren(NodeVisitor visitor) {
- target.accept(visitor);
- for (Expression arg in arguments) arg.accept(visitor);
- }
-
- Call _clone() => new Call(target, arguments);
-
- int get precedenceLevel => CALL;
-}
-
-class New extends Call {
- New(Expression cls, List<Expression> arguments) : super(cls, arguments);
-
- accept(NodeVisitor visitor) => visitor.visitNew(this);
-
- New _clone() => new New(target, arguments);
-}
-
-class Binary extends Expression {
- final String op;
- final Expression left;
- final Expression right;
-
- Binary(this.op, this.left, this.right);
-
- accept(NodeVisitor visitor) => visitor.visitBinary(this);
-
- Binary _clone() => new Binary(op, left, right);
-
- void visitChildren(NodeVisitor visitor) {
- left.accept(visitor);
- right.accept(visitor);
- }
-
- bool get isCommaOperator => op == ',';
-
- int get precedenceLevel {
- // TODO(floitsch): switch to constant map.
- switch (op) {
- case "*":
- case "/":
- case "%":
- return MULTIPLICATIVE;
- case "+":
- case "-":
- return ADDITIVE;
- case "<<":
- case ">>":
- case ">>>":
- return SHIFT;
- case "<":
- case ">":
- case "<=":
- case ">=":
- case "instanceof":
- case "in":
- return RELATIONAL;
- case "==":
- case "===":
- case "!=":
- case "!==":
- return EQUALITY;
- case "&":
- return BIT_AND;
- case "^":
- return BIT_XOR;
- case "|":
- return BIT_OR;
- case "&&":
- return LOGICAL_AND;
- case "||":
- return LOGICAL_OR;
- case ',':
- return EXPRESSION;
- default:
- throw "Internal Error: Unhandled binary operator: $op";
- }
- }
-}
-
-class Prefix extends Expression {
- final String op;
- final Expression argument;
-
- Prefix(this.op, this.argument);
-
- accept(NodeVisitor visitor) => visitor.visitPrefix(this);
-
- Prefix _clone() => new Prefix(op, argument);
-
- void visitChildren(NodeVisitor visitor) {
- argument.accept(visitor);
- }
-
- int get precedenceLevel => UNARY;
-}
-
-class Postfix extends Expression {
- final String op;
- final Expression argument;
-
- Postfix(this.op, this.argument);
-
- accept(NodeVisitor visitor) => visitor.visitPostfix(this);
-
- Postfix _clone() => new Postfix(op, argument);
-
- void visitChildren(NodeVisitor visitor) {
- argument.accept(visitor);
- }
-
-
- int get precedenceLevel => UNARY;
-}
-
-abstract class VariableReference extends Expression {
- final String name;
-
- VariableReference(this.name) {
- assert(_identifierRE.hasMatch(name));
- }
- static RegExp _identifierRE = new RegExp(r'^[A-Za-z_$][A-Za-z_$0-9]*$');
-
- accept(NodeVisitor visitor);
- int get precedenceLevel => PRIMARY;
- void visitChildren(NodeVisitor visitor) {}
-}
-
-class VariableUse extends VariableReference {
- VariableUse(String name) : super(name);
-
- accept(NodeVisitor visitor) => visitor.visitVariableUse(this);
- VariableUse _clone() => new VariableUse(name);
-
- VariableUse asVariableUse() => this;
-
- toString() => 'VariableUse($name)';
-}
-
-class VariableDeclaration extends VariableReference {
- final bool allowRename;
- VariableDeclaration(String name, {this.allowRename: true}) : super(name);
-
- accept(NodeVisitor visitor) => visitor.visitVariableDeclaration(this);
- VariableDeclaration _clone() => new VariableDeclaration(name);
-}
-
-class Parameter extends VariableDeclaration {
- Parameter(String name) : super(name);
-
- accept(NodeVisitor visitor) => visitor.visitParameter(this);
- Parameter _clone() => new Parameter(name);
-}
-
-class This extends Parameter {
- This() : super("this");
-
- accept(NodeVisitor visitor) => visitor.visitThis(this);
- This _clone() => new This();
-}
-
-class NamedFunction extends Expression {
- final VariableDeclaration name;
- final Fun function;
-
- NamedFunction(this.name, this.function);
-
- accept(NodeVisitor visitor) => visitor.visitNamedFunction(this);
-
- void visitChildren(NodeVisitor visitor) {
- name.accept(visitor);
- function.accept(visitor);
- }
- NamedFunction _clone() => new NamedFunction(name, function);
-
- int get precedenceLevel => CALL;
-}
-
-class Fun extends Expression {
- final List<Parameter> params;
- final Block body;
- final AsyncModifier asyncModifier;
-
- Fun(this.params, this.body, {this.asyncModifier: const AsyncModifier.sync()});
-
- accept(NodeVisitor visitor) => visitor.visitFun(this);
-
- void visitChildren(NodeVisitor visitor) {
- for (Parameter param in params) param.accept(visitor);
- body.accept(visitor);
- }
-
- Fun _clone() => new Fun(params, body, asyncModifier: asyncModifier);
-
- int get precedenceLevel => CALL;
-}
-
-class AsyncModifier {
- final bool isAsync;
- final bool isYielding;
- final String description;
-
- const AsyncModifier.sync()
- : isAsync = false,
- isYielding = false,
- description = "sync";
- const AsyncModifier.async()
- : isAsync = true,
- isYielding = false,
- description = "async";
- const AsyncModifier.asyncStar()
- : isAsync = true,
- isYielding = true,
- description = "async*";
- const AsyncModifier.syncStar()
- : isAsync = false,
- isYielding = true,
- description = "sync*";
- toString() => description;
-}
-
-class PropertyAccess extends Expression {
- final Expression receiver;
- final Expression selector;
-
- PropertyAccess(this.receiver, this.selector);
- PropertyAccess.field(this.receiver, String fieldName)
- : selector = new LiteralString('"$fieldName"');
- PropertyAccess.indexed(this.receiver, int index)
- : selector = new LiteralNumber('$index');
-
- accept(NodeVisitor visitor) => visitor.visitAccess(this);
-
- void visitChildren(NodeVisitor visitor) {
- receiver.accept(visitor);
- selector.accept(visitor);
- }
-
- PropertyAccess _clone() => new PropertyAccess(receiver, selector);
-
- int get precedenceLevel => CALL;
-}
-
-abstract class Literal extends Expression {
- void visitChildren(NodeVisitor visitor) {}
-
- int get precedenceLevel => PRIMARY;
-}
-
-class LiteralBool extends Literal {
- final bool value;
-
- LiteralBool(this.value);
-
- accept(NodeVisitor visitor) => visitor.visitLiteralBool(this);
- // [visitChildren] inherited from [Literal].
- LiteralBool _clone() => new LiteralBool(value);
-}
-
-class LiteralNull extends Literal {
- LiteralNull();
-
- accept(NodeVisitor visitor) => visitor.visitLiteralNull(this);
- LiteralNull _clone() => new LiteralNull();
-}
-
-class LiteralString extends Literal {
- final String value;
-
- /**
- * Constructs a LiteralString from a string value.
- *
- * The constructor does not add the required quotes. If [value] is not
- * surrounded by quotes and property escaped, the resulting object is invalid
- * as a JS value.
- *
- * TODO(sra): Introduce variants for known valid strings that don't allocate a
- * new string just to add quotes.
- */
- LiteralString(this.value);
-
- accept(NodeVisitor visitor) => visitor.visitLiteralString(this);
- LiteralString _clone() => new LiteralString(value);
-}
-
-class LiteralNumber extends Literal {
- final String value; // Must be a valid JavaScript number literal.
-
- LiteralNumber(this.value);
-
- accept(NodeVisitor visitor) => visitor.visitLiteralNumber(this);
- LiteralNumber _clone() => new LiteralNumber(value);
-}
-
-class ArrayInitializer extends Expression {
- final List<Expression> elements;
-
- ArrayInitializer(this.elements);
-
- accept(NodeVisitor visitor) => visitor.visitArrayInitializer(this);
-
- void visitChildren(NodeVisitor visitor) {
- for (Expression element in elements) element.accept(visitor);
- }
-
- ArrayInitializer _clone() => new ArrayInitializer(elements);
-
- int get precedenceLevel => PRIMARY;
-}
-
-/**
- * An empty place in an [ArrayInitializer].
- * For example the list [1, , , 2] would contain two holes.
- */
-class ArrayHole extends Expression {
- accept(NodeVisitor visitor) => visitor.visitArrayHole(this);
-
- void visitChildren(NodeVisitor visitor) {}
-
- ArrayHole _clone() => new ArrayHole();
-
- int get precedenceLevel => PRIMARY;
-}
-
-class ObjectInitializer extends Expression {
- final List<Property> properties;
- final bool isOneLiner;
-
- /**
- * Constructs a new object-initializer containing the given [properties].
- *
- * [isOneLiner] describes the behaviour when pretty-printing (non-minified).
- * If true print all properties on the same line.
- * If false print each property on a seperate line.
- */
- ObjectInitializer(this.properties, {this.isOneLiner: true});
-
- accept(NodeVisitor visitor) => visitor.visitObjectInitializer(this);
-
- void visitChildren(NodeVisitor visitor) {
- for (Property init in properties) init.accept(visitor);
- }
-
- ObjectInitializer _clone() =>
- new ObjectInitializer(properties, isOneLiner: isOneLiner);
-
- int get precedenceLevel => PRIMARY;
-}
-
-class Property extends Node {
- final Literal name;
- final Expression value;
-
- Property(this.name, this.value);
-
- accept(NodeVisitor visitor) => visitor.visitProperty(this);
-
- void visitChildren(NodeVisitor visitor) {
- name.accept(visitor);
- value.accept(visitor);
- }
-
- Property _clone() => new Property(name, value);
-}
-
-/// Tag class for all interpolated positions.
-abstract class InterpolatedNode implements Node {
- get nameOrPosition;
-
- bool get isNamed => nameOrPosition is String;
- bool get isPositional => nameOrPosition is int;
-}
-
-class InterpolatedExpression extends Expression with InterpolatedNode {
- final nameOrPosition;
-
- InterpolatedExpression(this.nameOrPosition);
-
- accept(NodeVisitor visitor) => visitor.visitInterpolatedExpression(this);
- void visitChildren(NodeVisitor visitor) {}
- InterpolatedExpression _clone() =>
- new InterpolatedExpression(nameOrPosition);
-
- int get precedenceLevel => PRIMARY;
-}
-
-class InterpolatedLiteral extends Literal with InterpolatedNode {
- final nameOrPosition;
-
- InterpolatedLiteral(this.nameOrPosition);
-
- accept(NodeVisitor visitor) => visitor.visitInterpolatedLiteral(this);
- void visitChildren(NodeVisitor visitor) {}
- InterpolatedLiteral _clone() => new InterpolatedLiteral(nameOrPosition);
-}
-
-class InterpolatedParameter extends Expression with InterpolatedNode
- implements Parameter {
- final nameOrPosition;
-
- String get name { throw "InterpolatedParameter.name must not be invoked"; }
- bool get allowRename => false;
-
- InterpolatedParameter(this.nameOrPosition);
-
- accept(NodeVisitor visitor) => visitor.visitInterpolatedParameter(this);
- void visitChildren(NodeVisitor visitor) {}
- InterpolatedParameter _clone() => new InterpolatedParameter(nameOrPosition);
-
- int get precedenceLevel => PRIMARY;
-}
-
-class InterpolatedSelector extends Expression with InterpolatedNode {
- final nameOrPosition;
-
- InterpolatedSelector(this.nameOrPosition);
-
- accept(NodeVisitor visitor) => visitor.visitInterpolatedSelector(this);
- void visitChildren(NodeVisitor visitor) {}
- InterpolatedSelector _clone() => new InterpolatedSelector(nameOrPosition);
-
- int get precedenceLevel => PRIMARY;
-}
-
-class InterpolatedStatement extends Statement with InterpolatedNode {
- final nameOrPosition;
-
- InterpolatedStatement(this.nameOrPosition);
-
- accept(NodeVisitor visitor) => visitor.visitInterpolatedStatement(this);
- void visitChildren(NodeVisitor visitor) {}
- InterpolatedStatement _clone() => new InterpolatedStatement(nameOrPosition);
-}
-
-/**
- * [RegExpLiteral]s, despite being called "Literal", do not inherit from
- * [Literal]. Indeed, regular expressions in JavaScript have a side-effect and
- * are thus not in the same category as numbers or strings.
- */
-class RegExpLiteral extends Expression {
- /** Contains the pattern and the flags.*/
- final String pattern;
-
- RegExpLiteral(this.pattern);
-
- accept(NodeVisitor visitor) => visitor.visitRegExpLiteral(this);
- void visitChildren(NodeVisitor visitor) {}
- RegExpLiteral _clone() => new RegExpLiteral(pattern);
-
- int get precedenceLevel => PRIMARY;
-}
-
-/**
- * An asynchronous await.
- *
- * Not part of JavaScript. We desugar this expression before outputting.
- * Should only occur in a [Fun] with `asyncModifier` async or asyncStar.
- */
-class Await extends Expression {
- /** The awaited expression. */
- final Expression expression;
-
- Await(this.expression);
-
- int get precedenceLevel => UNARY;
- accept(NodeVisitor visitor) => visitor.visitAwait(this);
- void visitChildren(NodeVisitor visitor) => expression.accept(visitor);
- Await _clone() => new Await(expression);
-
-}
-
-/**
- * A comment.
- *
- * Extends [Statement] so we can add comments before statements in
- * [Block] and [Program].
- */
-class Comment extends Statement {
- final String comment;
-
- Comment(this.comment);
-
- accept(NodeVisitor visitor) => visitor.visitComment(this);
- Comment _clone() => new Comment(comment);
-
- void visitChildren(NodeVisitor visitor) {}
-}
diff --git a/pkg/compiler/lib/src/js/printer.dart b/pkg/compiler/lib/src/js/printer.dart
deleted file mode 100644
index 6ee3f3e..0000000
--- a/pkg/compiler/lib/src/js/printer.dart
+++ /dev/null
@@ -1,1247 +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 js_ast;
-
-
-class JavaScriptPrintingOptions {
- final bool shouldCompressOutput;
- final bool minifyLocalVariables;
- final bool preferSemicolonToNewlineInMinifiedOutput;
-
- JavaScriptPrintingOptions(
- {this.shouldCompressOutput: false,
- this.minifyLocalVariables: false,
- this.preferSemicolonToNewlineInMinifiedOutput: false});
-}
-
-
-/// An environment in which JavaScript printing is done. Provides emitting of
-/// text and pre- and post-visit callbacks.
-abstract class JavaScriptPrintingContext {
- /// Signals an error. This should happen only for serious internal errors.
- void error(String message) { throw message; }
-
- /// Adds [string] to the output.
- void emit(String string);
-
- /// Callback immediately before printing [node]. Whitespace may be printed
- /// after this callback before the first non-whitespace character for [node].
- void enterNode(Node node) {}
- /// Callback after printing the last character representing [node].
- void exitNode(Node node) {}
-}
-
-/// A simple implementation of [JavaScriptPrintingContext] suitable for tests.
-class SimpleJavaScriptPrintingContext extends JavaScriptPrintingContext {
- final StringBuffer buffer = new StringBuffer();
-
- void emit(String string) {
- buffer.write(string);
- }
-
- String getText() => buffer.toString();
-}
-
-
-class Printer implements NodeVisitor {
- final JavaScriptPrintingOptions options;
- final JavaScriptPrintingContext context;
- final bool shouldCompressOutput;
- final DanglingElseVisitor danglingElseVisitor;
- final LocalNamer localNamer;
-
- bool inForInit = false;
- bool atStatementBegin = false;
- bool pendingSemicolon = false;
- bool pendingSpace = false;
-
- // The current indentation level.
- int _indentLevel = 0;
- // A cache of all indentation strings used so far.
- List<String> _indentList = <String>[""];
-
- static final identifierCharacterRegExp = new RegExp(r'^[a-zA-Z_0-9$]');
- static final expressionContinuationRegExp = new RegExp(r'^[-+([]');
-
- Printer(JavaScriptPrintingOptions options,
- JavaScriptPrintingContext context)
- : options = options,
- context = context,
- shouldCompressOutput = options.shouldCompressOutput,
- danglingElseVisitor = new DanglingElseVisitor(context),
- localNamer = determineRenamer(options.shouldCompressOutput,
- options.minifyLocalVariables);
-
- static LocalNamer determineRenamer(bool shouldCompressOutput,
- bool allowVariableMinification) {
- return (shouldCompressOutput && allowVariableMinification)
- ? new MinifyRenamer() : new IdentityNamer();
- }
-
-
- // The current indentation string.
- String get indentation {
- // Lazily add new indentation strings as required.
- while (_indentList.length <= _indentLevel) {
- _indentList.add(_indentList.last + " ");
- }
- return _indentList[_indentLevel];
- }
-
- void indentMore() {
- _indentLevel++;
- }
-
- void indentLess() {
- _indentLevel--;
- }
-
-
- /// Always emit a newline, even under `enableMinification`.
- void forceLine() {
- out("\n");
- }
- /// Emits a newline for readability.
- void lineOut() {
- if (!shouldCompressOutput) forceLine();
- }
- void spaceOut() {
- if (!shouldCompressOutput) out(" ");
- }
-
- String lastAddedString = null;
- int get lastCharCode {
- if (lastAddedString == null) return 0;
- assert(lastAddedString.length != "");
- return lastAddedString.codeUnitAt(lastAddedString.length - 1);
- }
-
- void out(String str) {
- if (str != "") {
- if (pendingSemicolon) {
- if (!shouldCompressOutput) {
- context.emit(";");
- } else if (str != "}") {
- // We want to output newline instead of semicolon because it makes
- // the raw stack traces much easier to read and it also makes line-
- // based tools like diff work much better. JavaScript will
- // automatically insert the semicolon at the newline if it means a
- // parsing error is avoided, so we can only do this trick if the
- // next line is not something that can be glued onto a valid
- // expression to make a new valid expression.
-
- // If we're using the new emitter where most pretty printed code
- // is escaped in strings, it is a lot easier to deal with semicolons
- // than newlines because the former doesn't need escaping.
- if (options.preferSemicolonToNewlineInMinifiedOutput ||
- expressionContinuationRegExp.hasMatch(str)) {
- context.emit(";");
- } else {
- context.emit("\n");
- }
- }
- }
- if (pendingSpace &&
- (!shouldCompressOutput || identifierCharacterRegExp.hasMatch(str))) {
- context.emit(" ");
- }
- pendingSpace = false;
- pendingSemicolon = false;
- context.emit(str);
- lastAddedString = str;
- }
- }
-
- void outLn(String str) {
- out(str);
- lineOut();
- }
-
- void outSemicolonLn() {
- if (shouldCompressOutput) {
- pendingSemicolon = true;
- } else {
- out(";");
- forceLine();
- }
- }
-
- void outIndent(String str) { indent(); out(str); }
- void outIndentLn(String str) { indent(); outLn(str); }
- void indent() {
- if (!shouldCompressOutput) {
- out(indentation);
- }
- }
-
- visit(Node node) {
- context.enterNode(node);
- node.accept(this);
- context.exitNode(node);
- }
-
- visitCommaSeparated(List<Node> nodes, int hasRequiredType,
- {bool newInForInit, bool newAtStatementBegin}) {
- for (int i = 0; i < nodes.length; i++) {
- if (i != 0) {
- atStatementBegin = false;
- out(",");
- spaceOut();
- }
- visitNestedExpression(nodes[i], hasRequiredType,
- newInForInit: newInForInit,
- newAtStatementBegin: newAtStatementBegin);
- }
- }
-
- visitAll(List<Node> nodes) {
- nodes.forEach(visit);
- }
-
- visitProgram(Program program) {
- visitAll(program.body);
- }
-
- bool blockBody(Node body, {bool needsSeparation, bool needsNewline}) {
- if (body is Block) {
- spaceOut();
- blockOut(body, false, needsNewline);
- return true;
- }
- if (shouldCompressOutput && needsSeparation) {
- // If [shouldCompressOutput] is false, then the 'lineOut' will insert
- // the separation.
- out(" ");
- } else {
- lineOut();
- }
- indentMore();
- visit(body);
- indentLess();
- return false;
- }
-
- void blockOutWithoutBraces(Node node) {
- if (node is Block) {
- context.enterNode(node);
- Block block = node;
- block.statements.forEach(blockOutWithoutBraces);
- context.exitNode(node);
- } else {
- visit(node);
- }
- }
-
- void blockOut(Block node, bool shouldIndent, bool needsNewline) {
- if (shouldIndent) indent();
- context.enterNode(node);
- out("{");
- lineOut();
- indentMore();
- node.statements.forEach(blockOutWithoutBraces);
- indentLess();
- indent();
- out("}");
- context.exitNode(node);
- if (needsNewline) lineOut();
- }
-
- visitBlock(Block block) {
- blockOut(block, true, true);
- }
-
- visitExpressionStatement(ExpressionStatement expressionStatement) {
- indent();
- visitNestedExpression(expressionStatement.expression, EXPRESSION,
- newInForInit: false, newAtStatementBegin: true);
- outSemicolonLn();
- }
-
- visitEmptyStatement(EmptyStatement nop) {
- outIndentLn(";");
- }
-
- void ifOut(If node, bool shouldIndent) {
- Node then = node.then;
- Node elsePart = node.otherwise;
- bool hasElse = node.hasElse;
-
- // Handle dangling elses and a work-around for Android 4.0 stock browser.
- // Android 4.0 requires braces for a single do-while in the `then` branch.
- // See issue 10923.
- if (hasElse) {
- bool needsBraces = node.then.accept(danglingElseVisitor) || then is Do;
- if (needsBraces) {
- then = new Block(<Statement>[then]);
- }
- }
- if (shouldIndent) indent();
- out("if");
- spaceOut();
- out("(");
- visitNestedExpression(node.condition, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- out(")");
- bool thenWasBlock =
- blockBody(then, needsSeparation: false, needsNewline: !hasElse);
- if (hasElse) {
- if (thenWasBlock) {
- spaceOut();
- } else {
- indent();
- }
- out("else");
- if (elsePart is If) {
- pendingSpace = true;
- ifOut(elsePart, false);
- } else {
- blockBody(elsePart, needsSeparation: true, needsNewline: true);
- }
- }
- }
-
- visitIf(If node) {
- ifOut(node, true);
- }
-
- visitFor(For loop) {
- outIndent("for");
- spaceOut();
- out("(");
- if (loop.init != null) {
- visitNestedExpression(loop.init, EXPRESSION,
- newInForInit: true, newAtStatementBegin: false);
- }
- out(";");
- if (loop.condition != null) {
- spaceOut();
- visitNestedExpression(loop.condition, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- }
- out(";");
- if (loop.update != null) {
- spaceOut();
- visitNestedExpression(loop.update, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- }
- out(")");
- blockBody(loop.body, needsSeparation: false, needsNewline: true);
- }
-
- visitForIn(ForIn loop) {
- outIndent("for");
- spaceOut();
- out("(");
- visitNestedExpression(loop.leftHandSide, EXPRESSION,
- newInForInit: true, newAtStatementBegin: false);
- out(" in");
- pendingSpace = true;
- visitNestedExpression(loop.object, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- out(")");
- blockBody(loop.body, needsSeparation: false, needsNewline: true);
- }
-
- visitWhile(While loop) {
- outIndent("while");
- spaceOut();
- out("(");
- visitNestedExpression(loop.condition, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- out(")");
- blockBody(loop.body, needsSeparation: false, needsNewline: true);
- }
-
- visitDo(Do loop) {
- outIndent("do");
- if (blockBody(loop.body, needsSeparation: true, needsNewline: false)) {
- spaceOut();
- } else {
- indent();
- }
- out("while");
- spaceOut();
- out("(");
- visitNestedExpression(loop.condition, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- out(")");
- outSemicolonLn();
- }
-
- visitContinue(Continue node) {
- if (node.targetLabel == null) {
- outIndent("continue");
- } else {
- outIndent("continue ${node.targetLabel}");
- }
- outSemicolonLn();
- }
-
- visitBreak(Break node) {
- if (node.targetLabel == null) {
- outIndent("break");
- } else {
- outIndent("break ${node.targetLabel}");
- }
- outSemicolonLn();
- }
-
- visitReturn(Return node) {
- if (node.value == null) {
- outIndent("return");
- } else {
- outIndent("return");
- pendingSpace = true;
- visitNestedExpression(node.value, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- }
- outSemicolonLn();
- }
-
- visitDartYield(DartYield node) {
- if (node.hasStar) {
- outIndent("yield*");
- } else {
- outIndent("yield");
- }
- pendingSpace = true;
- visitNestedExpression(node.expression, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- outSemicolonLn();
- }
-
-
- visitThrow(Throw node) {
- outIndent("throw");
- pendingSpace = true;
- visitNestedExpression(node.expression, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- outSemicolonLn();
- }
-
- visitTry(Try node) {
- outIndent("try");
- blockBody(node.body, needsSeparation: true, needsNewline: false);
- if (node.catchPart != null) {
- visit(node.catchPart);
- }
- if (node.finallyPart != null) {
- spaceOut();
- out("finally");
- blockBody(node.finallyPart, needsSeparation: true, needsNewline: true);
- } else {
- lineOut();
- }
- }
-
- visitCatch(Catch node) {
- spaceOut();
- out("catch");
- spaceOut();
- out("(");
- visitNestedExpression(node.declaration, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- out(")");
- blockBody(node.body, needsSeparation: false, needsNewline: true);
- }
-
- visitSwitch(Switch node) {
- outIndent("switch");
- spaceOut();
- out("(");
- visitNestedExpression(node.key, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- out(")");
- spaceOut();
- outLn("{");
- indentMore();
- visitAll(node.cases);
- indentLess();
- outIndentLn("}");
- }
-
- visitCase(Case node) {
- outIndent("case");
- pendingSpace = true;
- visitNestedExpression(node.expression, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- outLn(":");
- if (!node.body.statements.isEmpty) {
- indentMore();
- blockOutWithoutBraces(node.body);
- indentLess();
- }
- }
-
- visitDefault(Default node) {
- outIndentLn("default:");
- if (!node.body.statements.isEmpty) {
- indentMore();
- blockOutWithoutBraces(node.body);
- indentLess();
- }
- }
-
- visitLabeledStatement(LabeledStatement node) {
- outIndent("${node.label}:");
- blockBody(node.body, needsSeparation: false, needsNewline: true);
- }
-
- void functionOut(Fun fun, Node name, VarCollector vars) {
- out("function");
- if (name != null) {
- out(" ");
- // Name must be a [Decl]. Therefore only test for primary expressions.
- visitNestedExpression(name, PRIMARY,
- newInForInit: false, newAtStatementBegin: false);
- }
- localNamer.enterScope(vars);
- out("(");
- if (fun.params != null) {
- visitCommaSeparated(fun.params, PRIMARY,
- newInForInit: false, newAtStatementBegin: false);
- }
- out(")");
- switch (fun.asyncModifier) {
- case const AsyncModifier.sync():
- break;
- case const AsyncModifier.async():
- out(' async');
- break;
- case const AsyncModifier.syncStar():
- out(' sync*');
- break;
- case const AsyncModifier.asyncStar():
- out(' async*');
- break;
- }
- blockBody(fun.body, needsSeparation: false, needsNewline: false);
- localNamer.leaveScope();
- }
-
- visitFunctionDeclaration(FunctionDeclaration declaration) {
- VarCollector vars = new VarCollector();
- vars.visitFunctionDeclaration(declaration);
- indent();
- functionOut(declaration.function, declaration.name, vars);
- lineOut();
- }
-
- visitNestedExpression(Expression node, int requiredPrecedence,
- {bool newInForInit, bool newAtStatementBegin}) {
- bool needsParentheses =
- // a - (b + c).
- (requiredPrecedence != EXPRESSION &&
- node.precedenceLevel < requiredPrecedence) ||
- // for (a = (x in o); ... ; ... ) { ... }
- (newInForInit && node is Binary && node.op == "in") ||
- // (function() { ... })().
- // ({a: 2, b: 3}.toString()).
- (newAtStatementBegin && (node is NamedFunction ||
- node is Fun ||
- node is ObjectInitializer));
- if (needsParentheses) {
- inForInit = false;
- atStatementBegin = false;
- out("(");
- visit(node);
- out(")");
- } else {
- inForInit = newInForInit;
- atStatementBegin = newAtStatementBegin;
- visit(node);
- }
- }
-
- visitVariableDeclarationList(VariableDeclarationList list) {
- out("var ");
- visitCommaSeparated(list.declarations, ASSIGNMENT,
- newInForInit: inForInit, newAtStatementBegin: false);
- }
-
- visitAssignment(Assignment assignment) {
- visitNestedExpression(assignment.leftHandSide, LEFT_HAND_SIDE,
- newInForInit: inForInit,
- newAtStatementBegin: atStatementBegin);
- if (assignment.value != null) {
- spaceOut();
- String op = assignment.op;
- if (op != null) out(op);
- out("=");
- spaceOut();
- visitNestedExpression(assignment.value, ASSIGNMENT,
- newInForInit: inForInit,
- newAtStatementBegin: false);
- }
- }
-
- visitVariableInitialization(VariableInitialization initialization) {
- visitAssignment(initialization);
- }
-
- visitConditional(Conditional cond) {
- visitNestedExpression(cond.condition, LOGICAL_OR,
- newInForInit: inForInit,
- newAtStatementBegin: atStatementBegin);
- spaceOut();
- out("?");
- spaceOut();
- // The then part is allowed to have an 'in'.
- visitNestedExpression(cond.then, ASSIGNMENT,
- newInForInit: false, newAtStatementBegin: false);
- spaceOut();
- out(":");
- spaceOut();
- visitNestedExpression(cond.otherwise, ASSIGNMENT,
- newInForInit: inForInit, newAtStatementBegin: false);
- }
-
- visitNew(New node) {
- out("new ");
- visitNestedExpression(node.target, CALL,
- newInForInit: inForInit, newAtStatementBegin: false);
- out("(");
- visitCommaSeparated(node.arguments, ASSIGNMENT,
- newInForInit: false, newAtStatementBegin: false);
- out(")");
- }
-
- visitCall(Call call) {
- visitNestedExpression(call.target, LEFT_HAND_SIDE,
- newInForInit: inForInit,
- newAtStatementBegin: atStatementBegin);
- out("(");
- visitCommaSeparated(call.arguments, ASSIGNMENT,
- newInForInit: false, newAtStatementBegin: false);
- out(")");
- }
-
- visitBinary(Binary binary) {
- Expression left = binary.left;
- Expression right = binary.right;
- String op = binary.op;
- int leftPrecedenceRequirement;
- int rightPrecedenceRequirement;
- bool leftSpace = true; // left<HERE>op right
- switch (op) {
- case ',':
- // x, (y, z) <=> (x, y), z.
- leftPrecedenceRequirement = EXPRESSION;
- rightPrecedenceRequirement = EXPRESSION;
- leftSpace = false;
- break;
- case "||":
- leftPrecedenceRequirement = LOGICAL_OR;
- // x || (y || z) <=> (x || y) || z.
- rightPrecedenceRequirement = LOGICAL_OR;
- break;
- case "&&":
- leftPrecedenceRequirement = LOGICAL_AND;
- // x && (y && z) <=> (x && y) && z.
- rightPrecedenceRequirement = LOGICAL_AND;
- break;
- case "|":
- leftPrecedenceRequirement = BIT_OR;
- // x | (y | z) <=> (x | y) | z.
- rightPrecedenceRequirement = BIT_OR;
- break;
- case "^":
- leftPrecedenceRequirement = BIT_XOR;
- // x ^ (y ^ z) <=> (x ^ y) ^ z.
- rightPrecedenceRequirement = BIT_XOR;
- break;
- case "&":
- leftPrecedenceRequirement = BIT_AND;
- // x & (y & z) <=> (x & y) & z.
- rightPrecedenceRequirement = BIT_AND;
- break;
- case "==":
- case "!=":
- case "===":
- case "!==":
- leftPrecedenceRequirement = EQUALITY;
- rightPrecedenceRequirement = RELATIONAL;
- break;
- case "<":
- case ">":
- case "<=":
- case ">=":
- case "instanceof":
- case "in":
- leftPrecedenceRequirement = RELATIONAL;
- rightPrecedenceRequirement = SHIFT;
- break;
- case ">>":
- case "<<":
- case ">>>":
- leftPrecedenceRequirement = SHIFT;
- rightPrecedenceRequirement = ADDITIVE;
- break;
- case "+":
- case "-":
- leftPrecedenceRequirement = ADDITIVE;
- // We cannot remove parenthesis for "+" because
- // x + (y + z) <!=> (x + y) + z:
- // Example:
- // "a" + (1 + 2) => "a3";
- // ("a" + 1) + 2 => "a12";
- rightPrecedenceRequirement = MULTIPLICATIVE;
- break;
- case "*":
- case "/":
- case "%":
- leftPrecedenceRequirement = MULTIPLICATIVE;
- // We cannot remove parenthesis for "*" because of precision issues.
- rightPrecedenceRequirement = UNARY;
- break;
- default:
- context.error("Forgot operator: $op");
- }
-
- visitNestedExpression(left, leftPrecedenceRequirement,
- newInForInit: inForInit,
- newAtStatementBegin: atStatementBegin);
-
- if (op == "in" || op == "instanceof") {
- // There are cases where the space is not required but without further
- // analysis we cannot know.
- out(" ");
- out(op);
- out(" ");
- } else {
- if (leftSpace) spaceOut();
- out(op);
- spaceOut();
- }
- visitNestedExpression(right, rightPrecedenceRequirement,
- newInForInit: inForInit,
- newAtStatementBegin: false);
- }
-
- visitPrefix(Prefix unary) {
- String op = unary.op;
- switch (op) {
- case "delete":
- case "void":
- case "typeof":
- // There are cases where the space is not required but without further
- // analysis we cannot know.
- out(op);
- out(" ");
- break;
- case "+":
- case "++":
- if (lastCharCode == charCodes.$PLUS) out(" ");
- out(op);
- break;
- case "-":
- case "--":
- if (lastCharCode == charCodes.$MINUS) out(" ");
- out(op);
- break;
- default:
- out(op);
- }
- visitNestedExpression(unary.argument, UNARY,
- newInForInit: inForInit, newAtStatementBegin: false);
- }
-
- visitPostfix(Postfix postfix) {
- visitNestedExpression(postfix.argument, LEFT_HAND_SIDE,
- newInForInit: inForInit,
- newAtStatementBegin: atStatementBegin);
- out(postfix.op);
- }
-
- visitVariableUse(VariableUse ref) {
- out(localNamer.getName(ref.name));
- }
-
- visitThis(This node) {
- out("this");
- }
-
- visitVariableDeclaration(VariableDeclaration decl) {
- out(localNamer.getName(decl.name));
- }
-
- visitParameter(Parameter param) {
- out(localNamer.getName(param.name));
- }
-
- bool isDigit(int charCode) {
- return charCodes.$0 <= charCode && charCode <= charCodes.$9;
- }
-
- bool isValidJavaScriptId(String field) {
- if (field.length < 3) return false;
- // Ignore the leading and trailing string-delimiter.
- for (int i = 1; i < field.length - 1; i++) {
- // TODO(floitsch): allow more characters.
- int charCode = field.codeUnitAt(i);
- if (!(charCodes.$a <= charCode && charCode <= charCodes.$z ||
- charCodes.$A <= charCode && charCode <= charCodes.$Z ||
- charCode == charCodes.$$ ||
- charCode == charCodes.$_ ||
- i != 1 && isDigit(charCode))) {
- return false;
- }
- }
- // TODO(floitsch): normally we should also check that the field is not a
- // reserved word. We don't generate fields with reserved word names except
- // for 'super'.
- if (field == '"super"') return false;
- return true;
- }
-
- visitAccess(PropertyAccess access) {
- visitNestedExpression(access.receiver, CALL,
- newInForInit: inForInit,
- newAtStatementBegin: atStatementBegin);
- Node selector = access.selector;
- if (selector is LiteralString) {
- LiteralString selectorString = selector;
- String fieldWithQuotes = selectorString.value;
- if (isValidJavaScriptId(fieldWithQuotes)) {
- if (access.receiver is LiteralNumber) out(" ");
- out(".");
- out(fieldWithQuotes.substring(1, fieldWithQuotes.length - 1));
- return;
- }
- }
- out("[");
- visitNestedExpression(selector, EXPRESSION,
- newInForInit: false, newAtStatementBegin: false);
- out("]");
- }
-
- visitNamedFunction(NamedFunction namedFunction) {
- VarCollector vars = new VarCollector();
- vars.visitNamedFunction(namedFunction);
- functionOut(namedFunction.function, namedFunction.name, vars);
- }
-
- visitFun(Fun fun) {
- VarCollector vars = new VarCollector();
- vars.visitFun(fun);
- functionOut(fun, null, vars);
- }
-
- visitLiteralBool(LiteralBool node) {
- out(node.value ? "true" : "false");
- }
-
- visitLiteralString(LiteralString node) {
- out(node.value);
- }
-
- visitLiteralNumber(LiteralNumber node) {
- int charCode = node.value.codeUnitAt(0);
- if (charCode == charCodes.$MINUS && lastCharCode == charCodes.$MINUS) {
- out(" ");
- }
- out(node.value);
- }
-
- visitLiteralNull(LiteralNull node) {
- out("null");
- }
-
- visitArrayInitializer(ArrayInitializer node) {
- out("[");
- List<Expression> elements = node.elements;
- for (int i = 0; i < elements.length; i++) {
- Expression element = elements[i];
- if (element is ArrayHole) {
- // Note that array holes must have a trailing "," even if they are
- // in last position. Otherwise `[,]` (having length 1) would become
- // equal to `[]` (the empty array)
- // and [1,,] (array with 1 and a hole) would become [1,] = [1].
- out(",");
- continue;
- }
- if (i != 0) spaceOut();
- visitNestedExpression(element, ASSIGNMENT,
- newInForInit: false, newAtStatementBegin: false);
- // We can skip the trailing "," for the last element (since it's not
- // an array hole).
- if (i != elements.length - 1) out(",");
- }
- out("]");
- }
-
- visitArrayHole(ArrayHole node) {
- throw "Unreachable";
- }
-
- visitObjectInitializer(ObjectInitializer node) {
- // Print all the properties on one line until we see a function-valued
- // property. Ideally, we would use a proper pretty-printer to make the
- // decision based on layout.
- List<Property> properties = node.properties;
- out("{");
- indentMore();
- for (int i = 0; i < properties.length; i++) {
- Expression value = properties[i].value;
- if (i != 0) {
- out(",");
- if (node.isOneLiner) spaceOut();
- }
- if (!node.isOneLiner) {
- forceLine();
- indent();
- }
- visit(properties[i]);
- }
- indentLess();
- if (!node.isOneLiner && !properties.isEmpty) {
- lineOut();
- indent();
- }
- out("}");
- }
-
- visitProperty(Property node) {
- if (node.name is LiteralString) {
- LiteralString nameString = node.name;
- String name = nameString.value;
- if (isValidJavaScriptId(name)) {
- out(name.substring(1, name.length - 1));
- } else {
- out(name);
- }
- } else {
- assert(node.name is LiteralNumber);
- LiteralNumber nameNumber = node.name;
- out(nameNumber.value);
- }
- out(":");
- spaceOut();
- visitNestedExpression(node.value, ASSIGNMENT,
- newInForInit: false, newAtStatementBegin: false);
- }
-
- visitRegExpLiteral(RegExpLiteral node) {
- out(node.pattern);
- }
-
- visitLiteralExpression(LiteralExpression node) {
- String template = node.template;
- List<Expression> inputs = node.inputs;
-
- List<String> parts = template.split('#');
- int inputsLength = inputs == null ? 0 : inputs.length;
- if (parts.length != inputsLength + 1) {
- context.error('Wrong number of arguments for JS: $template');
- }
- // Code that uses JS must take care of operator precedences, and
- // put parenthesis if needed.
- out(parts[0]);
- for (int i = 0; i < inputsLength; i++) {
- visit(inputs[i]);
- out(parts[i + 1]);
- }
- }
-
- visitLiteralStatement(LiteralStatement node) {
- outLn(node.code);
- }
-
- visitInterpolatedNode(InterpolatedNode node) {
- out('#${node.nameOrPosition}');
- }
-
- visitInterpolatedExpression(InterpolatedExpression node) =>
- visitInterpolatedNode(node);
-
- visitInterpolatedLiteral(InterpolatedLiteral node) =>
- visitInterpolatedNode(node);
-
- visitInterpolatedParameter(InterpolatedParameter node) =>
- visitInterpolatedNode(node);
-
- visitInterpolatedSelector(InterpolatedSelector node) =>
- visitInterpolatedNode(node);
-
- visitInterpolatedStatement(InterpolatedStatement node) {
- outLn('#${node.nameOrPosition}');
- }
-
- void visitComment(Comment node) {
- if (shouldCompressOutput) return;
- String comment = node.comment.trim();
- if (comment.isEmpty) return;
- for (var line in comment.split('\n')) {
- if (comment.startsWith('//')) {
- outIndentLn(line.trim());
- } else {
- outIndentLn('// ${line.trim()}');
- }
- }
- }
-
- void visitAwait(Await node) {
- out("await ");
- visit(node.expression);
- }
-}
-
-
-class OrderedSet<T> {
- final Set<T> set;
- final List<T> list;
-
- OrderedSet() : set = new Set<T>(), list = <T>[];
-
- void add(T x) {
- if (!set.contains(x)) {
- set.add(x);
- list.add(x);
- }
- }
-
- void forEach(void fun(T x)) {
- list.forEach(fun);
- }
-}
-
-// Collects all the var declarations in the function. We need to do this in a
-// separate pass because JS vars are lifted to the top of the function.
-class VarCollector extends BaseVisitor {
- bool nested;
- final OrderedSet<String> vars;
- final OrderedSet<String> params;
-
- VarCollector() : nested = false,
- vars = new OrderedSet<String>(),
- params = new OrderedSet<String>();
-
- void forEachVar(void fn(String v)) => vars.forEach(fn);
- void forEachParam(void fn(String p)) => params.forEach(fn);
-
- void collectVarsInFunction(Fun fun) {
- if (!nested) {
- nested = true;
- if (fun.params != null) {
- for (int i = 0; i < fun.params.length; i++) {
- params.add(fun.params[i].name);
- }
- }
- visitBlock(fun.body);
- nested = false;
- }
- }
-
- void visitFunctionDeclaration(FunctionDeclaration declaration) {
- // Note that we don't bother collecting the name of the function.
- collectVarsInFunction(declaration.function);
- }
-
- void visitNamedFunction(NamedFunction namedFunction) {
- // Note that we don't bother collecting the name of the function.
- collectVarsInFunction(namedFunction.function);
- }
-
- void visitFun(Fun fun) {
- collectVarsInFunction(fun);
- }
-
- void visitThis(This node) {}
-
- void visitVariableDeclaration(VariableDeclaration decl) {
- if (decl.allowRename) vars.add(decl.name);
- }
-}
-
-
-/**
- * Returns true, if the given node must be wrapped into braces when used
- * as then-statement in an [If] that has an else branch.
- */
-class DanglingElseVisitor extends BaseVisitor<bool> {
- JavaScriptPrintingContext context;
-
- DanglingElseVisitor(this.context);
-
- bool visitProgram(Program node) => false;
-
- bool visitNode(Statement node) {
- context.error("Forgot node: $node");
- return null;
- }
-
- bool visitBlock(Block node) => false;
- bool visitExpressionStatement(ExpressionStatement node) => false;
- bool visitEmptyStatement(EmptyStatement node) => false;
- bool visitIf(If node) {
- if (!node.hasElse) return true;
- return node.otherwise.accept(this);
- }
- bool visitFor(For node) => node.body.accept(this);
- bool visitForIn(ForIn node) => node.body.accept(this);
- bool visitWhile(While node) => node.body.accept(this);
- bool visitDo(Do node) => false;
- bool visitContinue(Continue node) => false;
- bool visitBreak(Break node) => false;
- bool visitReturn(Return node) => false;
- bool visitThrow(Throw node) => false;
- bool visitTry(Try node) {
- if (node.finallyPart != null) {
- return node.finallyPart.accept(this);
- } else {
- return node.catchPart.accept(this);
- }
- }
- bool visitCatch(Catch node) => node.body.accept(this);
- bool visitSwitch(Switch node) => false;
- bool visitCase(Case node) => false;
- bool visitDefault(Default node) => false;
- bool visitFunctionDeclaration(FunctionDeclaration node) => false;
- bool visitLabeledStatement(LabeledStatement node)
- => node.body.accept(this);
- bool visitLiteralStatement(LiteralStatement node) => true;
-
- bool visitExpression(Expression node) => false;
-}
-
-
-abstract class LocalNamer {
- String getName(String oldName);
- String declareVariable(String oldName);
- String declareParameter(String oldName);
- void enterScope(VarCollector vars);
- void leaveScope();
-}
-
-
-class IdentityNamer implements LocalNamer {
- String getName(String oldName) => oldName;
- String declareVariable(String oldName) => oldName;
- String declareParameter(String oldName) => oldName;
- void enterScope(VarCollector vars) {}
- void leaveScope() {}
-}
-
-
-class MinifyRenamer implements LocalNamer {
- final List<Map<String, String>> maps = [];
- final List<int> parameterNumberStack = [];
- final List<int> variableNumberStack = [];
- int parameterNumber = 0;
- int variableNumber = 0;
-
- MinifyRenamer();
-
- void enterScope(VarCollector vars) {
- maps.add(new Map<String, String>());
- variableNumberStack.add(variableNumber);
- parameterNumberStack.add(parameterNumber);
- vars.forEachVar(declareVariable);
- vars.forEachParam(declareParameter);
- }
-
- void leaveScope() {
- maps.removeLast();
- variableNumber = variableNumberStack.removeLast();
- parameterNumber = parameterNumberStack.removeLast();
- }
-
- String getName(String oldName) {
- // Go from inner scope to outer looking for mapping of name.
- for (int i = maps.length - 1; i >= 0; i--) {
- var map = maps[i];
- var replacement = map[oldName];
- if (replacement != null) return replacement;
- }
- return oldName;
- }
-
- static const LOWER_CASE_LETTERS = 26;
- static const LETTERS = LOWER_CASE_LETTERS;
- static const DIGITS = 10;
-
- static int nthLetter(int n) {
- return (n < LOWER_CASE_LETTERS) ?
- charCodes.$a + n :
- charCodes.$A + n - LOWER_CASE_LETTERS;
- }
-
- // Parameters go from a to z and variables go from z to a. This makes each
- // argument list and each top-of-function var declaration look similar and
- // helps gzip compress the file. If we have more than 26 arguments and
- // variables then we meet somewhere in the middle of the alphabet. After
- // that we give up trying to be nice to the compression algorithm and just
- // use the same namespace for arguments and variables, starting with A, and
- // moving on to a0, a1, etc.
- String declareVariable(String oldName) {
- if (avoidRenaming(oldName)) return oldName;
- var newName;
- if (variableNumber + parameterNumber < LOWER_CASE_LETTERS) {
- // Variables start from z and go backwards, for better gzipability.
- newName = getNameNumber(oldName, LOWER_CASE_LETTERS - 1 - variableNumber);
- } else {
- // After 26 variables and parameters we allocate them in the same order.
- newName = getNameNumber(oldName, variableNumber + parameterNumber);
- }
- variableNumber++;
- return newName;
- }
-
- String declareParameter(String oldName) {
- if (avoidRenaming(oldName)) return oldName;
- var newName;
- if (variableNumber + parameterNumber < LOWER_CASE_LETTERS) {
- newName = getNameNumber(oldName, parameterNumber);
- } else {
- newName = getNameNumber(oldName, variableNumber + parameterNumber);
- }
- parameterNumber++;
- return newName;
- }
-
- bool avoidRenaming(String oldName) {
- // Variables of this $form$ are used in pattern matching the message of JS
- // exceptions, so should not be renamed.
- // TODO(sra): Introduce a way for indicating in the JS text which variables
- // should not be renamed.
- return oldName.startsWith(r'$') && oldName.endsWith(r'$');
- }
-
- String getNameNumber(String oldName, int n) {
- if (maps.isEmpty) return oldName;
-
- String newName;
- if (n < LETTERS) {
- // Start naming variables a, b, c, ..., z, A, B, C, ..., Z.
- newName = new String.fromCharCodes([nthLetter(n)]);
- } else {
- // Then name variables a0, a1, a2, ..., a9, b0, b1, ..., Z9, aa0, aa1, ...
- // For all functions with fewer than 500 locals this is just as compact
- // as using aa, ab, etc. but avoids clashes with keywords.
- n -= LETTERS;
- int digit = n % DIGITS;
- n ~/= DIGITS;
- int alphaChars = 1;
- int nameSpaceSize = LETTERS;
- // Find out whether we should use the 1-character namespace (size 52), the
- // 2-character namespace (size 52*52), etc.
- while (n >= nameSpaceSize) {
- n -= nameSpaceSize;
- alphaChars++;
- nameSpaceSize *= LETTERS;
- }
- var codes = <int>[];
- for (var i = 0; i < alphaChars; i++) {
- nameSpaceSize ~/= LETTERS;
- codes.add(nthLetter((n ~/ nameSpaceSize) % LETTERS));
- }
- codes.add(charCodes.$0 + digit);
- newName = new String.fromCharCodes(codes);
- }
- assert(new RegExp(r'[a-zA-Z][a-zA-Z0-9]*').hasMatch(newName));
- maps.last[oldName] = newName;
- return newName;
- }
-}
diff --git a/pkg/compiler/lib/src/js/rewrite_async.dart b/pkg/compiler/lib/src/js/rewrite_async.dart
index 961ec7b..c2948bf 100644
--- a/pkg/compiler/lib/src/js/rewrite_async.dart
+++ b/pkg/compiler/lib/src/js/rewrite_async.dart
@@ -4,11 +4,6 @@
library rewrite_async;
-// TODO(sigurdm): Avoid using variables in templates. It could blow up memory
-// use.
-// TODO(sigurdm): Move the try/catch expression to a js_helper function.
-// That would also simplify the sync* case, where the error can just be thrown.
-
import "dart:math" show max;
import 'dart:collection';
@@ -365,9 +360,6 @@
/// True if the function has any try blocks containing await.
bool hasTryBlocks = false;
- /// True if any return, break or continue passes through a finally.
- bool hasJumpThroughFinally = false;
-
/// True if the traversion currently is inside a loop or switch for which
/// [shouldTransform] is false.
bool insideUntranslatedBreakable = false;
@@ -410,8 +402,7 @@
/// This should be followed by a break for the goto to be executed. Use
/// [gotoWithBreak] or [addGoto] for this.
js.Statement setGotoVariable(int label) {
- return new js.ExpressionStatement(
- new js.Assignment(new js.VariableUse(gotoName), js.number(label)));
+ return js.js.statement('# = #;', [gotoName, js.number(label)]);
}
/// Returns a block that has a goto to [label] including the break.
@@ -512,7 +503,7 @@
// [js.Literal]s.
if (result is js.Literal) return result;
js.Expression tempVar = useTempVar(allocateTempVar());
- addExpressionStatement(new js.Assignment(tempVar, result));
+ addStatement(js.js.statement('# = #;', [tempVar, result]));
return tempVar;
}
@@ -601,22 +592,25 @@
}
switch (async) {
case const js.AsyncModifier.async():
- String returnValue =
- analysis.hasExplicitReturns ? returnValueName : "null";
addStatement(js.js.statement(
- "return #thenHelper($returnValue, #successCode, "
- "$completerName, null)", {
- "thenHelper": asyncHelper,
- "successCode": js.number(error_codes.SUCCESS)}));
+ "return #runtimeHelper(#returnValue, #successCode, "
+ "#completer, null);", {
+ "runtimeHelper": asyncHelper,
+ "successCode": js.number(error_codes.SUCCESS),
+ "returnValue": analysis.hasExplicitReturns
+ ? returnValueName
+ : new js.LiteralNull(),
+ "completer": completerName}));
break;
case const js.AsyncModifier.syncStar():
- addStatement(new js.Return(new js.Call(endOfIteration, [])));
+ addStatement(js.js.statement('return #();', [endOfIteration]));
break;
case const js.AsyncModifier.asyncStar():
addStatement(js.js.statement(
- "return #streamHelper(null, #successCode, $controllerName)", {
+ "return #streamHelper(null, #successCode, #controller);", {
"streamHelper": streamHelper,
- "successCode": js.number(error_codes.SUCCESS)}));
+ "successCode": js.number(error_codes.SUCCESS),
+ "controller": controllerName}));
break;
default:
diagnosticListener.internalError(
@@ -625,15 +619,16 @@
if (isAsync || isAsyncStar) {
beginLabel(rethrowLabel);
addStatement(js.js.statement(
- "return #thenHelper($currentErrorName, #errorCode, "
- "${isAsync ? completerName : controllerName})", {
+ "return #thenHelper(#currentError, #errorCode, #controller);", {
"thenHelper": isAsync ? asyncHelper : streamHelper,
- "errorCode": js.number(error_codes.ERROR)}));
+ "errorCode": js.number(error_codes.ERROR),
+ "currentError": currentErrorName,
+ "controller": isAsync ? completerName : controllerName}));
} else {
assert(isSyncStar);
beginLabel(rethrowLabel);
- addStatement(new js.Return(new js.Call(uncaughtErrorExpression,
- [new js.VariableUse(currentErrorName)])));
+ addStatement(js.js.statement('return #(#);',
+ [uncaughtErrorExpression, currentErrorName]));
}
}
@@ -647,13 +642,16 @@
js.Statement generateInitializer() {
if (isAsync) {
return js.js.statement(
- "return #asyncHelper(null, $bodyName, $completerName, null);", {
- "asyncHelper": asyncHelper
+ "return #asyncHelper(null, #body, #completer, null);", {
+ "asyncHelper": asyncHelper,
+ "body": bodyName,
+ "completer": completerName,
});
} else if (isAsyncStar) {
return js.js.statement(
- "return #streamOfController($controllerName);", {
- "streamOfController": streamOfController
+ "return #streamOfController(#controller);", {
+ "streamOfController": streamOfController,
+ "controller": controllerName,
});
} else {
throw diagnosticListener.internalError(
@@ -696,7 +694,7 @@
///
/// function(x, y, z) {
/// var goto = 0, returnValue, completer = new Completer(), p;
- /// function helper(result) {
+ /// function body(result) {
/// while (true) {
/// switch (goto) {
/// case 0:
@@ -716,8 +714,9 @@
/// }
///
/// Try/catch is implemented by maintaining [handlerName] to contain the label
- /// of the current handler. The switch is nested inside a try/catch that will
- /// redirect the flow to the current handler.
+ /// of the current handler. If [bodyName] throws, the caller should catch the
+ /// error and recall [bodyName] with first argument [error_codes.ERROR] and
+ /// second argument the error.
///
/// A `finally` clause is compiled similar to normal code, with the additional
/// complexity that `finally` clauses need to know where to jump to after the
@@ -725,7 +724,7 @@
/// sets up the variable [nextName] with a stack of finally-blocks and a final
/// jump-target (exit, catch, ...).
///
- /// function (x, y, z) async {
+ /// function(x, y, z) async {
/// try {
/// try {
/// throw "error";
@@ -748,57 +747,52 @@
/// var completer = new Completer();
/// var handler = 8; // Outside try-blocks go to the rethrow label.
/// var p;
- /// var storedError;
+ /// var currentError;
/// // The result can be either the result of an awaited future, or an
/// // error if the future completed with an error.
- /// function helper(errorCode, result) {
+ /// function body(errorCode, result) {
/// if (errorCode == 1) {
- /// storedError = result;
+ /// currentError = result;
/// goto = handler;
/// }
/// while (true) {
- /// try {
- /// switch (goto) {
- /// case 0:
- /// handler = 4; // The outer catch-handler
- /// handler = 1; // The inner (implicit) catch-handler
- /// throw "error";
- /// next = [3];
- /// // After the finally (2) continue normally after the try.
- /// goto = 2;
- /// break;
- /// case 1: // (implicit) catch handler for inner try.
- /// next = [3]; // destination after the finally.
- /// // fall-though to the finally handler.
- /// case 2: // finally for inner try
- /// handler = 4; // catch-handler for outer try.
- /// finalize1();
- /// goto = next.pop();
- /// break;
- /// case 3: // exiting inner try.
- /// next = [6];
- /// goto = 5; // finally handler for outer try.
- /// break;
- /// case 4: // catch handler for outer try.
- /// handler = 5; // If the handler throws, do the finally ..
- /// next = [8] // ... and rethrow.
- /// e = storedError;
- /// handle(e);
- /// // Fall through to finally.
- /// case 5: // finally handler for outer try.
- /// handler = null;
- /// finalize2();
- /// goto = next.pop();
- /// break;
- /// case 6: // Exiting outer try.
- /// case 7: // return
- /// return thenHelper(returnValue, 0, completer);
- /// case 8: // Rethrow
- /// return thenHelper(storedError, 1, completer);
- /// }
- /// } catch (error) {
- /// storedError = error;
- /// goto = handler;
+ /// switch (goto) {
+ /// case 0:
+ /// handler = 4; // The outer catch-handler
+ /// handler = 1; // The inner (implicit) catch-handler
+ /// throw "error";
+ /// next = [3];
+ /// // After the finally (2) continue normally after the try.
+ /// goto = 2;
+ /// break;
+ /// case 1: // (implicit) catch handler for inner try.
+ /// next = [3]; // destination after the finally.
+ /// // fall-though to the finally handler.
+ /// case 2: // finally for inner try
+ /// handler = 4; // catch-handler for outer try.
+ /// finalize1();
+ /// goto = next.pop();
+ /// break;
+ /// case 3: // exiting inner try.
+ /// next = [6];
+ /// goto = 5; // finally handler for outer try.
+ /// break;
+ /// case 4: // catch handler for outer try.
+ /// handler = 5; // If the handler throws, do the finally ..
+ /// next = [8] // ... and rethrow.
+ /// e = storedError;
+ /// handle(e);
+ /// // Fall through to finally.
+ /// case 5: // finally handler for outer try.
+ /// handler = null;
+ /// finalize2();
+ /// goto = next.pop();
+ /// break;
+ /// case 6: // Exiting outer try.
+ /// case 7: // return
+ /// return thenHelper(returnValue, 0, completer);
+ /// case 8: // Rethrow
+ /// return thenHelper(currentError, 1, completer);
/// }
/// }
/// return thenHelper(null, helper, completer);
@@ -828,15 +822,9 @@
js.Statement helperBody =
new js.Switch(new js.VariableUse(gotoName), clauses);
if (hasJumpThoughOuterLabel) {
- helperBody = js.js.statement("$outerLabelName: #", [helperBody]);
+ helperBody = new js.LabeledStatement(outerLabelName, helperBody);
}
- helperBody = js.js.statement("""
- try {
- #body
- } catch ($errorName){
- $currentErrorName = $errorName;
- $gotoName = $handlerName;
- }""", {"body": helperBody});
+
List<js.VariableInitialization> inits = <js.VariableInitialization>[];
js.VariableInitialization makeInit(String name, js.Expression initValue) {
@@ -849,23 +837,23 @@
inits.add(makeInit(completerName, new js.New(newCompleter, [])));
} else if (isAsyncStar) {
inits.add(makeInit(controllerName,
- new js.Call(newController, [new js.VariableUse(bodyName)])));
+ js.js('#(#)', [newController, bodyName])));
}
inits.add(makeInit(handlerName, js.number(rethrowLabel)));
inits.add(makeInit(currentErrorName, null));
- if (hasJumpThroughFinally || analysis.hasYield) {
+ if (analysis.hasFinally || (isAsyncStar && analysis.hasYield)) {
inits.add(makeInit(nextName, null));
}
+ if (isAsyncStar && analysis.hasYield) {
+ inits.add(makeInit(nextWhenCanceledName, null));
+ }
if (analysis.hasExplicitReturns && isAsync) {
inits.add(makeInit(returnValueName, null));
}
- if (isSyncStar) {
- inits.add(makeInit(resultName, null));
- }
if (analysis.hasThis && !isSyncStar) {
// Sync* functions must remember `this` on the level of the outer
// function.
- inits.add(makeInit(selfName, new js.This()));
+ inits.add(makeInit(selfName, js.js('this')));
}
inits.addAll(localVariables.map((js.VariableDeclaration decl) {
return new js.VariableInitialization(decl, null);
@@ -878,10 +866,14 @@
return js.js("""
function (#params) {
if (#needsThis)
- var $selfName = this;
+ var #self = this;
return new #newIterable(function () {
#varDecl;
- return function $bodyName() {
+ return function #body(#errorCode, #result) {
+ if (#errorCode === #ERROR) {
+ #currentError = #result;
+ #goto = #handler;
+ }
while (true)
#helperBody;
};
@@ -892,27 +884,35 @@
"needsThis": analysis.hasThis,
"helperBody": helperBody,
"varDecl": varDecl,
- "newIterable": newIterable
+ "errorCode": errorCodeName,
+ "newIterable": newIterable,
+ "body": bodyName,
+ "self": selfName,
+ "result": resultName,
+ "goto": gotoName,
+ "handler": handlerName,
+ "currentError": currentErrorName,
+ "ERROR": js.number(error_codes.ERROR),
});
}
return js.js("""
function (#params) {
#varDecl;
- function $bodyName($errorCodeName, $resultName) {
+ function #bodyName(#errorCode, #result) {
if (#hasYield)
- switch ($errorCodeName) {
- case #streamWasCanceled:
- $nextName = $nextWhenCanceledName;
- $gotoName = $nextName.pop();
+ switch (#errorCode) {
+ case #STREAM_WAS_CANCELED:
+ #next = #nextWhenCanceled;
+ #goto = #next.pop();
break;
- case #errorCode:
- $currentErrorName = $resultName;
- $gotoName = $handlerName;
+ case #ERROR:
+ #currentError = #result;
+ #goto = #handler;
}
else
- if ($errorCodeName == #errorCode) {
- $currentErrorName = $resultName;
- $gotoName = $handlerName;
+ if (#errorCode === #ERROR) {
+ #currentError = #result;
+ #goto = #handler;
}
while (true)
#helperBody;
@@ -921,18 +921,26 @@
}""", {
"params": node.params,
"varDecl": varDecl,
- "streamWasCanceled": js.number(error_codes.STREAM_WAS_CANCELED),
- "errorCode": js.number(error_codes.ERROR),
+ "STREAM_WAS_CANCELED": js.number(error_codes.STREAM_WAS_CANCELED),
+ "ERROR": js.number(error_codes.ERROR),
"hasYield": analysis.hasYield,
"helperBody": helperBody,
- "init": generateInitializer()
+ "init": generateInitializer(),
+ "bodyName": bodyName,
+ "currentError": currentErrorName,
+ "goto": gotoName,
+ "handler": handlerName,
+ "next": nextName,
+ "nextWhenCanceled": nextWhenCanceledName,
+ "errorCode": errorCodeName,
+ "result": resultName,
});
}
@override
js.Expression visitAccess(js.PropertyAccess node) {
return withExpression2(node.receiver, node.selector,
- (receiver, selector) => new js.PropertyAccess(receiver, selector));
+ (receiver, selector) => js.js('#[#]', [receiver, selector]));
}
@override
@@ -984,11 +992,13 @@
addStatement(setGotoVariable(afterAwait));
addStatement(js.js.statement("""
return #asyncHelper(#value,
- $bodyName,
- ${isAsync ? completerName : controllerName});
+ #body,
+ #controller);
""", {
"asyncHelper": isAsync ? asyncHelper : streamHelper,
"value": value,
+ "body": bodyName,
+ "controller": isAsync ? completerName : controllerName,
}));
}, store: false);
beginLabel(afterAwait);
@@ -1015,21 +1025,21 @@
withExpression(node.left, (js.Expression left) {
js.Statement assignLeft = isResult(left)
? new js.Block.empty()
- : new js.ExpressionStatement(
- new js.Assignment(new js.VariableUse(resultName), left));
+ : js.js.statement('# = #;', [resultName, left]);
if (node.op == "||") {
- addStatement(new js.If(left, gotoAndBreak(thenLabel), assignLeft));
+ addStatement(js.js.statement('if (#) {#} else #',
+ [left, gotoAndBreak(thenLabel), assignLeft]));
} else {
assert(node.op == "&&");
- addStatement(new js.If(left, assignLeft, gotoAndBreak(thenLabel)));
+ addStatement(js.js.statement('if (#) {#} else #',
+ [left, assignLeft, gotoAndBreak(thenLabel)]));
}
}, store: true);
addGoto(joinLabel);
beginLabel(thenLabel);
withExpression(node.right, (js.Expression value) {
if (!isResult(value)) {
- addExpressionStatement(
- new js.Assignment(new js.VariableUse(resultName), value));
+ addStatement(js.js.statement('# = #;', [resultName, value]));
}
}, store: false);
beginLabel(joinLabel);
@@ -1086,31 +1096,28 @@
js.Expression visitConditional(js.Conditional node) {
if (!shouldTransform(node.then) && !shouldTransform(node.otherwise)) {
return withExpression(node.condition, (js.Expression condition) {
- return new js.Conditional(condition, node.then, node.otherwise);
+ return js.js('# ? # : #', [condition, node.then, node.otherwise]);
});
}
int thenLabel = newLabel("then");
int joinLabel = newLabel("join");
int elseLabel = newLabel("else");
withExpression(node.condition, (js.Expression condition) {
- addExpressionStatement(new js.Assignment(new js.VariableUse(gotoName),
- new js.Conditional(
- condition, js.number(thenLabel), js.number(elseLabel))));
+ addStatement(js.js.statement('# = # ? # : #;',
+ [gotoName, condition, js.number(thenLabel), js.number(elseLabel)]));
}, store: false);
addBreak();
beginLabel(thenLabel);
withExpression(node.then, (js.Expression value) {
if (!isResult(value)) {
- addExpressionStatement(
- new js.Assignment(new js.VariableUse(resultName), value));
+ addStatement(js.js.statement('# = #;', [resultName, value]));
}
}, store: false);
addGoto(joinLabel);
beginLabel(elseLabel);
withExpression(node.otherwise, (js.Expression value) {
if (!isResult(value)) {
- addExpressionStatement(
- new js.Assignment(new js.VariableUse(resultName), value));
+ addStatement(js.js.statement('# = #;', [resultName, value]));
}
}, store: false);
beginLabel(joinLabel);
@@ -1162,10 +1169,9 @@
// now.
int firstTarget = jumpStack.removeLast();
if (jumpStack.isNotEmpty) {
- hasJumpThroughFinally = true;
js.Expression jsJumpStack = new js.ArrayInitializer(
jumpStack.map((int label) => js.number(label)).toList());
- addStatement(js.js.statement("$nextName = #", [jsJumpStack]));
+ addStatement(js.js.statement("# = #;", [nextName, jsJumpStack]));
}
addGoto(firstTarget);
}
@@ -1179,7 +1185,7 @@
bool oldInsideUntranslatedBreakable = insideUntranslatedBreakable;
insideUntranslatedBreakable = true;
withExpression(node.condition, (js.Expression condition) {
- addStatement(new js.Do(translateInBlock(node.body), condition));
+ addStatement(js.js.statement('do {#} while (#)', [node.body, condition]));
}, store: false);
insideUntranslatedBreakable = oldInsideUntranslatedBreakable;
return;
@@ -1200,7 +1206,8 @@
beginLabel(continueLabel);
withExpression(node.condition, (js.Expression condition) {
- addStatement(new js.If.noElse(condition, gotoAndBreak(startLabel)));
+ addStatement(js.js.statement('if (#) #',
+ [condition, gotoAndBreak(startLabel)]));
}, store: false);
beginLabel(afterLabel);
}
@@ -1237,7 +1244,7 @@
node.update
], (List<js.Expression> transformed) {
addStatement(new js.For(transformed[0], transformed[1], transformed[2],
- translateInBlock(node.body)));
+ translateInBlock(node.body)));
});
insideUntranslatedBreakable = oldInsideUntranslated;
return;
@@ -1338,6 +1345,11 @@
}
@override
+ visitInterpolatedDeclaration(js.InterpolatedDeclaration node) {
+ return unsupported(node);
+ }
+
+ @override
visitInterpolatedLiteral(js.InterpolatedLiteral node) => unsupported(node);
@override
@@ -1485,7 +1497,7 @@
js.Node target = analysis.targets[node];
if (node.value != null) {
withExpression(node.value, (js.Expression value) {
- addStatement(js.js.statement("$returnValueName = #", [value]));
+ addStatement(js.js.statement("# = #;", [returnValueName, value]));
}, store: false);
}
translateJump(target, exitLabel);
@@ -1666,7 +1678,8 @@
} else {
// The handler is reset as the first thing in the finally block.
addStatement(
- js.js.statement("$nextName = [#];", [js.number(afterFinallyLabel)]));
+ js.js.statement("# = [#];",
+ [nextName, js.number(afterFinallyLabel)]));
addGoto(finallyLabel);
}
@@ -1692,8 +1705,8 @@
if (node.finallyPart != null) {
// The error has been caught, so after the finally, continue after the
// try.
- addStatement(js.js.statement("$nextName = [#];",
- [js.number(afterFinallyLabel)]));
+ addStatement(js.js.statement("# = [#];",
+ [nextName, js.number(afterFinallyLabel)]));
addGoto(finallyLabel);
} else {
addGoto(afterFinallyLabel);
@@ -1713,8 +1726,8 @@
// [enclosingFinallies] can be empty if there is no surrounding finally
// blocks. Then [nextLabel] will be [rethrowLabel].
addStatement(
- js.js.statement("$nextName = #;", new js.ArrayInitializer(
- enclosingFinallies.map(js.number).toList())));
+ js.js.statement("# = #;", [nextName, new js.ArrayInitializer(
+ enclosingFinallies.map(js.number).toList())]));
}
if (node.finallyPart == null) {
// The finally-block belonging to [node] will be visited because of
@@ -1729,7 +1742,7 @@
setErrorHandler();
visitStatement(node.finallyPart);
addStatement(new js.Comment("// goto the next finally handler"));
- addStatement(js.js.statement("$gotoName = $nextName.pop();"));
+ addStatement(js.js.statement("# = #.pop();", [gotoName, nextName]));
addBreak();
}
beginLabel(afterFinallyLabel);
@@ -1832,15 +1845,17 @@
enclosingFinallyLabels.addAll(jumpTargets
.where((js.Node node) => finallyLabels[node] != null)
.map((js.Block node) => finallyLabels[node]));
- addStatement(js.js.statement("$nextWhenCanceledName = #",
- [new js.ArrayInitializer(enclosingFinallyLabels.map(js.number)
- .toList())]));
+ addStatement(js.js.statement("# = #;",
+ [nextWhenCanceledName, new js.ArrayInitializer(
+ enclosingFinallyLabels.map(js.number).toList())]));
addStatement(js.js.statement("""
- return #streamHelper(#yieldExpression(#expression),
- $bodyName, $controllerName);""", {
+ return #streamHelper(#yieldExpression(#expression), #body,
+ #controller);""", {
"streamHelper": streamHelper,
"yieldExpression": node.hasStar ? yieldStarExpression : yieldExpression,
"expression": expression,
+ "body": bodyName,
+ "controller": controllerName,
}));
}
@@ -1883,6 +1898,8 @@
bool hasYield = false;
+ bool hasFinally = false;
+
// The function currently being analyzed.
js.Fun currentFunction;
@@ -2089,6 +2106,11 @@
}
@override
+ bool visitInterpolatedDeclaration(js.InterpolatedDeclaration node) {
+ return unsupported(node);
+ }
+
+ @override
bool visitInterpolatedLiteral(js.InterpolatedLiteral node) {
return unsupported(node);
}
@@ -2233,6 +2255,7 @@
bool catchPart = (node.catchPart == null) ? false : visit(node.catchPart);
bool finallyPart =
(node.finallyPart == null) ? false : visit(node.finallyPart);
+ if (finallyPart != null) hasFinally = true;
return body || catchPart || finallyPart;
}
diff --git a/pkg/compiler/lib/src/js/template.dart b/pkg/compiler/lib/src/js/template.dart
deleted file mode 100644
index 7740431..0000000
--- a/pkg/compiler/lib/src/js/template.dart
+++ /dev/null
@@ -1,739 +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.
-
-part of js_ast;
-
-class TemplateManager {
- Map<String, Template> expressionTemplates = new Map<String, Template>();
- Map<String, Template> statementTemplates = new Map<String, Template>();
-
- TemplateManager();
-
-
- Template lookupExpressionTemplate(String source) {
- return expressionTemplates[source];
- }
-
- Template defineExpressionTemplate(String source, Node ast) {
- Template template =
- new Template(source, ast, isExpression: true, forceCopy: false);
- expressionTemplates[source] = template;
- return template;
- }
-
- Template lookupStatementTemplate(String source) {
- return statementTemplates[source];
- }
-
- Template defineStatementTemplate(String source, Node ast) {
- Template template =
- new Template(source, ast, isExpression: false, forceCopy: false);
- statementTemplates[source] = template;
- return template;
- }
-}
-
-/**
- * A Template is created with JavaScript AST containing placeholders (interface
- * InterpolatedNode). The [instantiate] method creates an AST that looks like
- * the original with the placeholders replaced by the arguments to
- * [instantiate].
- */
-class Template {
- final String source;
- final bool isExpression;
- final bool forceCopy;
- final Node ast;
-
- Instantiator instantiator;
-
- int positionalArgumentCount = -1;
-
- // Null, unless there are named holes.
- List<String> holeNames;
- bool get isPositional => holeNames == null;
-
- Template(this.source, this.ast,
- {this.isExpression: true, this.forceCopy: false}) {
- _compile();
- }
-
- Template.withExpressionResult(this.ast)
- : source = null, isExpression = true, forceCopy = false {
- assert(ast is Expression);
- assert(_checkNoPlaceholders());
- positionalArgumentCount = 0;
- instantiator = (arguments) => ast;
- }
-
- Template.withStatementResult(this.ast)
- : source = null, isExpression = false, forceCopy = false {
- assert(ast is Statement);
- assert(_checkNoPlaceholders());
- positionalArgumentCount = 0;
- instantiator = (arguments) => ast;
- }
-
- bool _checkNoPlaceholders() {
- InstantiatorGeneratorVisitor generator =
- new InstantiatorGeneratorVisitor(false);
- generator.compile(ast);
- return generator.analysis.count == 0;
- }
-
- void _compile() {
- InstantiatorGeneratorVisitor generator =
- new InstantiatorGeneratorVisitor(forceCopy);
- instantiator = generator.compile(ast);
- positionalArgumentCount = generator.analysis.count;
- Set<String> names = generator.analysis.holeNames;
- holeNames = names.toList(growable:false);
- }
-
- /// Instantiates the template with the given [arguments].
- ///
- /// This method fills in the holes with the given arguments. The [arguments]
- /// must be either a [List] or a [Map].
- Node instantiate(var arguments) {
- if (arguments is List) {
- if (arguments.length != positionalArgumentCount) {
- throw 'Wrong number of template arguments, given ${arguments.length}, '
- 'expected $positionalArgumentCount';
- }
- return instantiator(arguments);
- }
- assert(arguments is Map);
- if (holeNames.length < arguments.length) {
- // This search is in O(n), but we only do it in case of an error, and the
- // number of holes should be quite limited.
- String unusedNames =
- arguments.keys.where((name) => !holeNames.contains(name)).join(", ");
- throw "Template arguments has unused mappings: $unusedNames";
- }
- if (!holeNames.every((String name) => arguments.containsKey(name))) {
- String notFound =
- holeNames.where((name) => !arguments.containsKey(name)).join(", ");
- throw "Template arguments is missing mappings for: $notFound";
- }
- return instantiator(arguments);
- }
-}
-
-/**
- * An Instantiator is a Function that generates a JS AST tree or List of
- * trees. [arguments] is a List for positional templates, or Map for
- * named templates.
- */
-typedef Node Instantiator(var arguments);
-
-
-/**
- * InstantiatorGeneratorVisitor compiles a template. This class compiles a tree
- * containing [InterpolatedNode]s into a function that will create a copy of the
- * tree with the interpolated nodes substituted with provided values.
- */
-class InstantiatorGeneratorVisitor implements NodeVisitor<Instantiator> {
-
- final bool forceCopy;
-
- InterpolatedNodeAnalysis analysis = new InterpolatedNodeAnalysis();
-
- /**
- * The entire tree is cloned if [forceCopy] is true.
- */
- InstantiatorGeneratorVisitor(this.forceCopy);
-
- Instantiator compile(Node node) {
- analysis.visit(node);
- Instantiator result = visit(node);
- return result;
- }
-
- static error(String message) {
- throw message;
- }
-
- static Instantiator same(Node node) => (arguments) => node;
- static Node makeNull(arguments) => null;
-
- Instantiator visit(Node node) {
- if (forceCopy || analysis.containsInterpolatedNodes(node)) {
- return node.accept(this);
- }
- return same(node);
- }
-
- Instantiator visitNullable(Node node) {
- if (node == null) return makeNull;
- return visit(node);
- }
-
- Instantiator visitSplayable(Node node) {
- // TODO(sra): Process immediate [InterpolatedNode]s, permitting splaying.
- return visit(node);
- }
-
- Instantiator visitNode(Node node) {
- throw 'Unimplemented InstantiatorGeneratorVisitor for $node';
- }
-
- static RegExp identiferRE = new RegExp(r'^[A-Za-z_$][A-Za-z_$0-9]*$');
-
- static Expression convertStringToVariableUse(String value) {
- assert(identiferRE.hasMatch(value));
- return new VariableUse(value);
- }
-
- Instantiator visitInterpolatedExpression(InterpolatedExpression node) {
- var nameOrPosition = node.nameOrPosition;
- return (arguments) {
- var value = arguments[nameOrPosition];
- if (value is Expression) return value;
- if (value is String) return convertStringToVariableUse(value);
- error('Interpolated value #$nameOrPosition is not an Expression: $value');
- };
- }
-
- Instantiator visitSplayableExpression(Node node) {
- if (node is InterpolatedExpression) {
- var nameOrPosition = node.nameOrPosition;
- return (arguments) {
- var value = arguments[nameOrPosition];
- Expression toExpression(item) {
- if (item is Expression) return item;
- if (item is String) return convertStringToVariableUse(item);
- return error('Interpolated value #$nameOrPosition is not '
- 'an Expression or List of Expressions: $value');
- }
- if (value is Iterable) return value.map(toExpression);
- return toExpression(value);
- };
- }
- return visit(node);
- }
-
- Instantiator visitInterpolatedLiteral(InterpolatedLiteral node) {
- var nameOrPosition = node.nameOrPosition;
- return (arguments) {
- var value = arguments[nameOrPosition];
- if (value is Literal) return value;
- error('Interpolated value #$nameOrPosition is not a Literal: $value');
- };
- }
-
- Instantiator visitInterpolatedParameter(InterpolatedParameter node) {
- var nameOrPosition = node.nameOrPosition;
- return (arguments) {
- var value = arguments[nameOrPosition];
-
- Parameter toParameter(item) {
- if (item is Parameter) return item;
- if (item is String) return new Parameter(item);
- return error('Interpolated value #$nameOrPosition is not a Parameter or'
- ' List of Parameters: $value');
- }
- if (value is Iterable) return value.map(toParameter);
- return toParameter(value);
- };
- }
-
- Instantiator visitInterpolatedSelector(InterpolatedSelector node) {
- // A selector is an expression, as in `a[selector]`.
- // A String argument converted into a LiteralString, so `a.#` with argument
- // 'foo' generates `a["foo"]` which prints as `a.foo`.
- var nameOrPosition = node.nameOrPosition;
- return (arguments) {
- var value = arguments[nameOrPosition];
- if (value is Expression) return value;
- if (value is String) return new LiteralString('"$value"');
- error('Interpolated value #$nameOrPosition is not a selector: $value');
- };
- }
-
- Instantiator visitInterpolatedStatement(InterpolatedStatement node) {
- var nameOrPosition = node.nameOrPosition;
- return (arguments) {
- var value = arguments[nameOrPosition];
- if (value is Node) return value.toStatement();
- error('Interpolated value #$nameOrPosition is not a Statement: $value');
- };
- }
-
- Instantiator visitSplayableStatement(Node node) {
- if (node is InterpolatedStatement) {
- var nameOrPosition = node.nameOrPosition;
- return (arguments) {
- var value = arguments[nameOrPosition];
- Statement toStatement(item) {
- if (item is Statement) return item;
- if (item is Expression) return item.toStatement();;
- return error('Interpolated value #$nameOrPosition is not '
- 'a Statement or List of Statements: $value');
- }
- if (value is Iterable) return value.map(toStatement);
- return toStatement(value);
- };
- }
- return visit(node);
- }
-
- Instantiator visitProgram(Program node) {
- List instantiators = node.body.map(visitSplayableStatement).toList();
- return (arguments) {
- List<Statement> statements = <Statement>[];
- void add(node) {
- if (node is EmptyStatement) return;
- if (node is Iterable) {
- statements.addAll(node);
- } else {
- statements.add(node.toStatement());
- }
- }
- for (Instantiator instantiator in instantiators) {
- add(instantiator(arguments));
- }
- return new Program(statements);
- };
- }
-
- Instantiator visitBlock(Block node) {
- List instantiators = node.statements.map(visitSplayableStatement).toList();
- return (arguments) {
- List<Statement> statements = <Statement>[];
- void add(node) {
- if (node is EmptyStatement) return;
- if (node is Iterable) {
- statements.addAll(node);
- } else if (node is Block) {
- statements.addAll(node.statements);
- } else {
- statements.add(node.toStatement());
- }
- }
- for (Instantiator instantiator in instantiators) {
- add(instantiator(arguments));
- }
- return new Block(statements);
- };
- }
-
- Instantiator visitExpressionStatement(ExpressionStatement node) {
- Instantiator buildExpression = visit(node.expression);
- return (arguments) {
- return buildExpression(arguments).toStatement();
- };
- }
-
- Instantiator visitEmptyStatement(EmptyStatement node) =>
- (arguments) => new EmptyStatement();
-
- Instantiator visitIf(If node) {
- if (node.condition is InterpolatedExpression) {
- return visitIfConditionalCompilation(node);
- } else {
- return visitIfNormal(node);
- }
- }
-
- Instantiator visitIfConditionalCompilation(If node) {
- // Special version of visitInterpolatedExpression that permits bools.
- compileCondition(InterpolatedExpression node) {
- var nameOrPosition = node.nameOrPosition;
- return (arguments) {
- var value = arguments[nameOrPosition];
- if (value is bool) return value;
- if (value is Expression) return value;
- if (value is String) return convertStringToVariableUse(value);;
- error('Interpolated value #$nameOrPosition '
- 'is not an Expression: $value');
- };
- }
- var makeCondition = compileCondition(node.condition);
- Instantiator makeThen = visit(node.then);
- Instantiator makeOtherwise = visit(node.otherwise);
- return (arguments) {
- var condition = makeCondition(arguments);
- if (condition is bool) {
- if (condition == true) {
- return makeThen(arguments);
- } else {
- return makeOtherwise(arguments);
- }
- }
- return new If(
- condition,
- makeThen(arguments),
- makeOtherwise(arguments));
- };
- }
-
- Instantiator visitIfNormal(If node) {
- Instantiator makeCondition = visit(node.condition);
- Instantiator makeThen = visit(node.then);
- Instantiator makeOtherwise = visit(node.otherwise);
- return (arguments) {
- return new If(
- makeCondition(arguments),
- makeThen(arguments),
- makeOtherwise(arguments));
- };
- }
-
- Instantiator visitFor(For node) {
- Instantiator makeInit = visitNullable(node.init);
- Instantiator makeCondition = visitNullable(node.condition);
- Instantiator makeUpdate = visitNullable(node.update);
- Instantiator makeBody = visit(node.body);
- return (arguments) {
- return new For(
- makeInit(arguments), makeCondition(arguments), makeUpdate(arguments),
- makeBody(arguments));
- };
- }
-
- Instantiator visitForIn(ForIn node) {
- Instantiator makeLeftHandSide = visit(node.leftHandSide);
- Instantiator makeObject = visit(node.object);
- Instantiator makeBody = visit(node.body);
- return (arguments) {
- return new ForIn(
- makeLeftHandSide(arguments),
- makeObject(arguments),
- makeBody(arguments));
- };
- }
-
- TODO(String name) {
- throw new UnimplementedError('$this.$name');
- }
-
- Instantiator visitWhile(While node) {
- Instantiator makeCondition = visit(node.condition);
- Instantiator makeBody = visit(node.body);
- return (arguments) {
- return new While(makeCondition(arguments), makeBody(arguments));
- };
- }
-
- Instantiator visitDo(Do node) {
- Instantiator makeBody = visit(node.body);
- Instantiator makeCondition = visit(node.condition);
- return (arguments) {
- return new Do(makeBody(arguments), makeCondition(arguments));
- };
- }
-
- Instantiator visitContinue(Continue node) =>
- (arguments) => new Continue(node.targetLabel);
-
- Instantiator visitBreak(Break node) =>
- (arguments) => new Break(node.targetLabel);
-
- Instantiator visitReturn(Return node) {
- Instantiator makeExpression = visitNullable(node.value);
- return (arguments) => new Return(makeExpression(arguments));
- }
-
- Instantiator visitDartYield(DartYield node) {
- Instantiator makeExpression = visit(node.expression);
- return (arguments) => new DartYield(makeExpression(arguments), node.hasStar);
- }
-
- Instantiator visitThrow(Throw node) {
- Instantiator makeExpression = visit(node.expression);
- return (arguments) => new Throw(makeExpression(arguments));
- }
-
- Instantiator visitTry(Try node) {
- Instantiator makeBody = visit(node.body);
- Instantiator makeCatch = visitNullable(node.catchPart);
- Instantiator makeFinally = visitNullable(node.finallyPart);
- return (arguments) => new Try(
- makeBody(arguments), makeCatch(arguments), makeFinally(arguments));
- }
-
- Instantiator visitCatch(Catch node) {
- Instantiator makeDeclaration = visit(node.declaration);
- Instantiator makeBody = visit(node.body);
- return (arguments) => new Catch(
- makeDeclaration(arguments), makeBody(arguments));
- }
-
- Instantiator visitSwitch(Switch node) {
- Instantiator makeKey = visit(node.key);
- Iterable<Instantiator> makeCases = node.cases.map(visit);
- return (arguments) {
- return new Switch(makeKey(arguments),
- makeCases.map((Instantiator makeCase) => makeCase(arguments))
- .toList());
- };
- }
-
- Instantiator visitCase(Case node) {
- Instantiator makeExpression = visit(node.expression);
- Instantiator makeBody = visit(node.body);
- return (arguments) {
- return new Case(makeExpression(arguments), makeBody(arguments));
- };
- }
-
- Instantiator visitDefault(Default node) {
- Instantiator makeBody = visit(node.body);
- return (arguments) {
- return new Default(makeBody(arguments));
- };
- }
-
- Instantiator visitFunctionDeclaration(FunctionDeclaration node) {
- Instantiator makeName = visit(node.name);
- Instantiator makeFunction = visit(node.function);
- return (arguments) =>
- new FunctionDeclaration(makeName(arguments), makeFunction(arguments));
- }
-
- Instantiator visitLabeledStatement(LabeledStatement node) {
- Instantiator makeBody = visit(node.body);
- return (arguments) => new LabeledStatement(node.label, makeBody(arguments));
- }
-
- Instantiator visitLiteralStatement(LiteralStatement node) =>
- TODO('visitLiteralStatement');
- Instantiator visitLiteralExpression(LiteralExpression node) =>
- TODO('visitLiteralExpression');
-
- Instantiator visitVariableDeclarationList(VariableDeclarationList node) {
- List<Instantiator> declarationMakers =
- node.declarations.map(visit).toList();
- return (arguments) {
- List<VariableInitialization> declarations = <VariableInitialization>[];
- for (Instantiator instantiator in declarationMakers) {
- var result = instantiator(arguments);
- declarations.add(result);
- }
- return new VariableDeclarationList(declarations);
- };
- }
-
- Instantiator visitAssignment(Assignment node) {
- Instantiator makeLeftHandSide = visit(node.leftHandSide);
- String op = node.op;
- Instantiator makeValue = visitNullable(node.value);
- return (arguments) {
- return new Assignment.compound(
- makeLeftHandSide(arguments),
- op,
- makeValue(arguments));
- };
- }
-
- Instantiator visitVariableInitialization(VariableInitialization node) {
- Instantiator makeDeclaration = visit(node.declaration);
- Instantiator makeValue = visitNullable(node.value);
- return (arguments) {
- return new VariableInitialization(
- makeDeclaration(arguments), makeValue(arguments));
- };
- }
-
- Instantiator visitConditional(Conditional cond) {
- Instantiator makeCondition = visit(cond.condition);
- Instantiator makeThen = visit(cond.then);
- Instantiator makeOtherwise = visit(cond.otherwise);
- return (arguments) => new Conditional(
- makeCondition(arguments),
- makeThen(arguments),
- makeOtherwise(arguments));
- }
-
- Instantiator visitNew(New node) =>
- handleCallOrNew(node, (target, arguments) => new New(target, arguments));
-
- Instantiator visitCall(Call node) =>
- handleCallOrNew(node, (target, arguments) => new Call(target, arguments));
-
- Instantiator handleCallOrNew(Call node, finish(target, arguments)) {
- Instantiator makeTarget = visit(node.target);
- Iterable<Instantiator> argumentMakers =
- node.arguments.map(visitSplayableExpression).toList();
-
- // TODO(sra): Avoid copying call arguments if no interpolation or forced
- // copying.
- return (arguments) {
- Node target = makeTarget(arguments);
- List<Expression> callArguments = <Expression>[];
- for (Instantiator instantiator in argumentMakers) {
- var result = instantiator(arguments);
- if (result is Iterable) {
- callArguments.addAll(result);
- } else {
- callArguments.add(result);
- }
- }
- return finish(target, callArguments.toList(growable: false));
- };
- }
-
- Instantiator visitBinary(Binary node) {
- Instantiator makeLeft = visit(node.left);
- Instantiator makeRight = visit(node.right);
- String op = node.op;
- return (arguments) =>
- new Binary(op, makeLeft(arguments), makeRight(arguments));
- }
-
- Instantiator visitPrefix(Prefix node) {
- Instantiator makeOperand = visit(node.argument);
- String op = node.op;
- return (arguments) => new Prefix(op, makeOperand(arguments));
- }
-
- Instantiator visitPostfix(Postfix node) {
- Instantiator makeOperand = visit(node.argument);
- String op = node.op;
- return (arguments) => new Postfix(op, makeOperand(arguments));
- }
-
- Instantiator visitVariableUse(VariableUse node) =>
- (arguments) => new VariableUse(node.name);
-
- Instantiator visitThis(This node) => (arguments) => new This();
-
- Instantiator visitVariableDeclaration(VariableDeclaration node) =>
- (arguments) => new VariableDeclaration(node.name);
-
- Instantiator visitParameter(Parameter node) =>
- (arguments) => new Parameter(node.name);
-
- Instantiator visitAccess(PropertyAccess node) {
- Instantiator makeReceiver = visit(node.receiver);
- Instantiator makeSelector = visit(node.selector);
- return (arguments) =>
- new PropertyAccess(makeReceiver(arguments), makeSelector(arguments));
- }
-
- Instantiator visitNamedFunction(NamedFunction node) {
- Instantiator makeDeclaration = visit(node.name);
- Instantiator makeFunction = visit(node.function);
- return (arguments) =>
- new NamedFunction(makeDeclaration(arguments), makeFunction(arguments));
- }
-
- Instantiator visitFun(Fun node) {
- List<Instantiator> paramMakers = node.params.map(visitSplayable).toList();
- Instantiator makeBody = visit(node.body);
- // TODO(sra): Avoid copying params if no interpolation or forced copying.
- return (arguments) {
- List<Parameter> params = <Parameter>[];
- for (Instantiator instantiator in paramMakers) {
- var result = instantiator(arguments);
- if (result is Iterable) {
- params.addAll(result);
- } else {
- params.add(result);
- }
- }
- Statement body = makeBody(arguments);
- return new Fun(params, body);
- };
- }
-
- Instantiator visitLiteralBool(LiteralBool node) =>
- (arguments) => new LiteralBool(node.value);
-
- Instantiator visitLiteralString(LiteralString node) =>
- (arguments) => new LiteralString(node.value);
-
- Instantiator visitLiteralNumber(LiteralNumber node) =>
- (arguments) => new LiteralNumber(node.value);
-
- Instantiator visitLiteralNull(LiteralNull node) =>
- (arguments) => new LiteralNull();
-
- Instantiator visitArrayInitializer(ArrayInitializer node) {
- // TODO(sra): Implement splicing?
- List<Instantiator> elementMakers = node.elements
- .map(visit)
- .toList(growable: false);
- return (arguments) {
- List<Expression> elements = elementMakers
- .map((Instantiator instantiator) => instantiator(arguments))
- .toList(growable: false);
- return new ArrayInitializer(elements);
- };
- }
-
- Instantiator visitArrayHole(ArrayHole node) {
- return (arguments) => new ArrayHole();
- }
-
- Instantiator visitObjectInitializer(ObjectInitializer node) {
- List<Instantiator> propertyMakers =
- node.properties.map(visitSplayable).toList();
- bool isOneLiner = node.isOneLiner;
- return (arguments) {
- List<Property> properties = <Property>[];
- for (Instantiator instantiator in propertyMakers) {
- var result = instantiator(arguments);
- if (result is Iterable) {
- properties.addAll(result);
- } else {
- properties.add(result);
- }
- }
- return new ObjectInitializer(properties, isOneLiner: isOneLiner);
- };
- }
-
- Instantiator visitProperty(Property node) {
- Instantiator makeName = visit(node.name);
- Instantiator makeValue = visit(node.value);
- return (arguments) {
- return new Property(makeName(arguments), makeValue(arguments));
- };
- }
-
- Instantiator visitRegExpLiteral(RegExpLiteral node) =>
- (arguments) => new RegExpLiteral(node.pattern);
-
- Instantiator visitComment(Comment node) => TODO('visitComment');
-
- Instantiator visitAwait(Await node) {
- Instantiator makeExpression = visit(node.expression);
- return (arguments) {
- return new Await(makeExpression(arguments));
- };
- }
-}
-
-/**
- * InterpolatedNodeAnalysis determines which AST trees contain
- * [InterpolatedNode]s, and the names of the named interpolated nodes.
- */
-class InterpolatedNodeAnalysis extends BaseVisitor {
- final Set<Node> containsInterpolatedNode = new Set<Node>();
- final Set<String> holeNames = new Set<String>();
- int count = 0;
-
- InterpolatedNodeAnalysis();
-
- bool containsInterpolatedNodes(Node node) =>
- containsInterpolatedNode.contains(node);
-
- void visit(Node node) {
- node.accept(this);
- }
-
- void visitNode(Node node) {
- int before = count;
- node.visitChildren(this);
- if (count != before) containsInterpolatedNode.add(node);
- return null;
- }
-
- visitInterpolatedNode(InterpolatedNode node) {
- containsInterpolatedNode.add(node);
- if (node.isNamed) holeNames.add(node.nameOrPosition);
- ++count;
- }
-}
diff --git a/pkg/compiler/lib/src/js_backend/backend.dart b/pkg/compiler/lib/src/js_backend/backend.dart
index 4f77f85..ee80103 100644
--- a/pkg/compiler/lib/src/js_backend/backend.dart
+++ b/pkg/compiler/lib/src/js_backend/backend.dart
@@ -88,7 +88,6 @@
/// size/complexity heuristics.
static const Map<String, List<String>> ALWAYS_INLINE =
const <String, List<String>> {
- 'IterableMixinWorkaround': const <String>['forEach'],
};
String get patchVersion => USE_NEW_EMITTER ? 'new' : 'old';
@@ -2311,6 +2310,10 @@
}
void onElementResolved(Element element, TreeElements elements) {
+ if (element.isFunction && annotations.noInline(element)) {
+ inlineCache.markAsNonInlinable(element);
+ }
+
LibraryElement library = element.library;
if (!library.isPlatformLibrary && !library.canUseNative) return;
bool hasNoInline = false;
@@ -2437,20 +2440,20 @@
static final Uri PACKAGE_EXPECT =
new Uri(scheme: 'package', path: 'expect/expect.dart');
- ClassElement expectNoInliningClass;
+ ClassElement expectNoInlineClass;
ClassElement expectTrustTypeAnnotationsClass;
ClassElement expectAssumeDynamicClass;
void onLibraryScanned(LibraryElement library) {
if (library.canonicalUri == PACKAGE_EXPECT) {
- expectNoInliningClass = library.find('NoInlining');
+ expectNoInlineClass = library.find('NoInline');
expectTrustTypeAnnotationsClass = library.find('TrustTypeAnnotations');
expectAssumeDynamicClass = library.find('AssumeDynamic');
- if (expectNoInliningClass == null ||
+ if (expectNoInlineClass == null ||
expectTrustTypeAnnotationsClass == null ||
expectAssumeDynamicClass == null) {
// This is not the package you're looking for.
- expectNoInliningClass = null;
+ expectNoInlineClass = null;
expectTrustTypeAnnotationsClass = null;
expectAssumeDynamicClass = null;
}
@@ -2458,8 +2461,9 @@
}
/// Returns `true` if inlining is disabled for [element].
- bool noInlining(Element element) {
- return _hasAnnotation(element, expectNoInliningClass);
+ bool noInline(Element element) {
+ // TODO(floitsch): restrict to test directory.
+ return _hasAnnotation(element, expectNoInlineClass);
}
/// Returns `true` if parameter and returns types should be trusted for
@@ -2581,7 +2585,7 @@
if (type.isMalformed) {
registerBackendStaticInvocation(backend.getThrowTypeError(), registry);
}
- if (!type.treatAsRaw || type.containsTypeVariables) {
+ if (!type.treatAsRaw || type.containsTypeVariables || type.isFunctionType) {
// TODO(johnniwinther): Investigate why this is needed.
registerBackendStaticInvocation(
backend.getSetRuntimeTypeInfo(), registry);
@@ -2665,17 +2669,23 @@
registerBackendInstantiation(backend.compiler.listClass, registry);
}
- void onConstantMap(Registry registry) {
+ void onMapLiteral(ResolutionRegistry registry,
+ DartType type,
+ bool isConstant) {
assert(registry.isForResolution);
void enqueue(String name) {
Element e = backend.find(backend.jsHelperLibrary, name);
registerBackendInstantiation(e, registry);
}
- enqueue(JavaScriptMapConstant.DART_CLASS);
- enqueue(JavaScriptMapConstant.DART_PROTO_CLASS);
- enqueue(JavaScriptMapConstant.DART_STRING_CLASS);
- enqueue(JavaScriptMapConstant.DART_GENERAL_CLASS);
+ if (isConstant) {
+ enqueue(JavaScriptMapConstant.DART_CLASS);
+ enqueue(JavaScriptMapConstant.DART_PROTO_CLASS);
+ enqueue(JavaScriptMapConstant.DART_STRING_CLASS);
+ enqueue(JavaScriptMapConstant.DART_GENERAL_CLASS);
+ } else {
+ registry.registerInstantiatedType(type);
+ }
}
/// Called when resolving the `Symbol` constructor.
diff --git a/pkg/compiler/lib/src/js_backend/codegen/codegen.dart b/pkg/compiler/lib/src/js_backend/codegen/codegen.dart
index b773f95..b1f03bf 100644
--- a/pkg/compiler/lib/src/js_backend/codegen/codegen.dart
+++ b/pkg/compiler/lib/src/js_backend/codegen/codegen.dart
@@ -95,9 +95,8 @@
/// Generates a name for the given variable. First trying with the name of
/// the [Variable.element] if it is non-null.
String getVariableName(tree_ir.Variable variable) {
- // TODO(sigurdm): Handle case where the variable belongs to an enclosing
- // function.
- if (variable.host != currentFunction) giveup(variable);
+ // Functions are not nested in the JS backend.
+ assert(variable.host == currentFunction);
// Get the name if we already have one.
String name = variableNames[variable];
@@ -176,12 +175,6 @@
return buildConstant(node.expression.value);
}
- @override
- js.Expression visitFunctionExpression(tree_ir.FunctionExpression node) {
- return giveup(node);
- // TODO: implement visitFunctionExpression
- }
-
js.Expression compileConstant(ParameterElement parameter) {
return buildConstant(glue.getConstantForVariable(parameter).value);
}
@@ -342,7 +335,6 @@
@override
js.Expression visitThis(tree_ir.This node) {
- // TODO(sigurdm): Inside a js closure this will not work.
return new js.This();
}
@@ -379,12 +371,6 @@
}
@override
- void visitFunctionDeclaration(tree_ir.FunctionDeclaration node) {
- giveup(node);
- // TODO: implement visitFunctionDeclaration
- }
-
- @override
void visitIf(tree_ir.If node) {
accumulator.add(new js.If(visitExpression(node.condition),
buildBody(node.thenStatement),
@@ -489,18 +475,6 @@
}
@override
- js.Expression visitFieldInitializer(tree_ir.FieldInitializer node) {
- return giveup(node);
- // TODO: implement FieldInitializer
- }
-
- @override
- js.Expression visitSuperInitializer(tree_ir.SuperInitializer node) {
- return giveup(node);
- // TODO: implement SuperInitializer
- }
-
- @override
js.Expression visitCreateBox(tree_ir.CreateBox node) {
return new js.ObjectInitializer([]);
}
@@ -529,4 +503,30 @@
accumulator.add(new js.ExpressionStatement(asn));
visitStatement(node.next);
}
+
+ // Dart-specific IR nodes
+
+ @override
+ visitFunctionExpression(tree_ir.FunctionExpression node) {
+ return errorUnsupportedNode(node);
+ }
+
+ @override
+ visitFunctionDeclaration(tree_ir.FunctionDeclaration node) {
+ return errorUnsupportedNode(node);
+ }
+
+ @override
+ visitFieldInitializer(tree_ir.FieldInitializer node) {
+ return errorUnsupportedNode(node);
+ }
+
+ @override
+ visitSuperInitializer(tree_ir.SuperInitializer node) {
+ return errorUnsupportedNode(node);
+ }
+
+ dynamic errorUnsupportedNode(tree_ir.DartSpecificNode node) {
+ throw "Unsupported node in JS backend: $node";
+ }
}
diff --git a/pkg/compiler/lib/src/js_backend/constant_emitter.dart b/pkg/compiler/lib/src/js_backend/constant_emitter.dart
index 2773144..58eedc0 100644
--- a/pkg/compiler/lib/src/js_backend/constant_emitter.dart
+++ b/pkg/compiler/lib/src/js_backend/constant_emitter.dart
@@ -200,9 +200,54 @@
return new jsAst.LiteralNull();
}
+ static final _exponentialRE = new RegExp(
+ '^'
+ '\([-+]?\)' // 1: sign
+ '\([0-9]+\)' // 2: leading digit(s)
+ '\(\.\([0-9]*\)\)?' // 4: fraction digits
+ 'e\([-+]?[0-9]+\)' // 5: exponent with sign
+ r'$');
+
+ /// Reduces the size of exponential representations when minification is
+ /// enabled.
+ ///
+ /// Removes the "+" after the exponential sign, and removes the "." before the
+ /// "e". For example `1.23e+5` is changed to `123e3`.
+ String _shortenExponentialRepresentation(String numberString) {
+ Match match = _exponentialRE.firstMatch(numberString);
+ if (match == null) return numberString;
+ String sign = match[1];
+ String leadingDigits = match[2];
+ String fractionDigits = match[4];
+ int exponent = int.parse(match[5]);
+ if (fractionDigits == null) fractionDigits = '';
+ exponent -= fractionDigits.length;
+ String result = '${sign}${leadingDigits}${fractionDigits}e${exponent}';
+ assert(double.parse(result) == double.parse(numberString));
+ return result;
+ }
+
@override
jsAst.Expression visitInt(IntConstantValue constant, [_]) {
- return new jsAst.LiteralNumber('${constant.primitiveValue}');
+ int primitiveValue = constant.primitiveValue;
+ // Since we are in JavaScript we can shorten long integers to their shorter
+ // exponential representation, for example: "1e4" is shorter than "10000".
+ //
+ // Note that this shortening apparently loses precision for big numbers
+ // (like 1234567890123456789012345 which becomes 12345678901234568e8).
+ // However, since JavaScript engines represent all numbers as doubles, these
+ // digits are lost anyway.
+ String representation = primitiveValue.toString();
+ String alternative = null;
+ int cutoff = compiler.enableMinification ? 10000 : 1e10.toInt();
+ if (primitiveValue.abs() >= cutoff) {
+ alternative = _shortenExponentialRepresentation(
+ primitiveValue.toStringAsExponential());
+ }
+ if (alternative != null && alternative.length < representation.length) {
+ representation = alternative;
+ }
+ return new jsAst.LiteralNumber(representation);
}
@override
@@ -215,7 +260,8 @@
} else if (value == -double.INFINITY) {
return js("-1/0");
} else {
- return new jsAst.LiteralNumber("$value");
+ String shortened = _shortenExponentialRepresentation("$value");
+ return new jsAst.LiteralNumber(shortened);
}
}
diff --git a/pkg/compiler/lib/src/js_backend/js_backend.dart b/pkg/compiler/lib/src/js_backend/js_backend.dart
index 2019f66..114ebd9 100644
--- a/pkg/compiler/lib/src/js_backend/js_backend.dart
+++ b/pkg/compiler/lib/src/js_backend/js_backend.dart
@@ -39,6 +39,7 @@
import '../js_backend/codegen/task.dart';
import 'patch_resolver.dart';
+import '../resolution/resolution.dart' show ResolutionRegistry;
part 'backend.dart';
part 'checked_mode_helpers.dart';
diff --git a/pkg/compiler/lib/src/js_backend/namer.dart b/pkg/compiler/lib/src/js_backend/namer.dart
index ac39658..9368968 100644
--- a/pkg/compiler/lib/src/js_backend/namer.dart
+++ b/pkg/compiler/lib/src/js_backend/namer.dart
@@ -25,7 +25,12 @@
];
static const reservedPropertySymbols =
- const <String>["__proto__", "prototype", "constructor", "call"];
+ const <String>[
+ "__proto__", "prototype", "constructor", "call",
+ // "use strict" disallows the use of "arguments" and "eval" as
+ // variable names or property names. See ECMA-262, Edition 5.1,
+ // section 11.1.5 (for the property names).
+ "eval", "arguments"];
// Symbols that we might be using in our JS snippets.
static const reservedGlobalSymbols = const <String>[
@@ -223,7 +228,8 @@
final String superPrefix = r'super$';
final String metadataField = '@';
final String callPrefix = 'call';
- final String callCatchAllName = r'call$catchAll';
+ final String callCatchAllName = r'call*';
+ final String callNameField = r'$callName';
final String reflectableField = r'$reflectable';
final String reflectionInfoField = r'$reflectionInfo';
final String reflectionNameField = r'$reflectionName';
@@ -233,6 +239,7 @@
r'$methodsWithOptionalArguments';
final String classDescriptorProperty = r'^';
+ final String requiredParameterField = r'$requiredArgCount';
// Name of property in a class description for the native dispatch metadata.
final String nativeSpecProperty = '%';
@@ -307,6 +314,9 @@
case 'CALL_CATCH_ALL': return callCatchAllName;
case 'REFLECTABLE': return reflectableField;
case 'CLASS_DESCRIPTOR_PROPERTY': return classDescriptorProperty;
+ case 'REQUIRED_PARAMETER_PROPERTY': return requiredParameterField;
+ case 'DEFAULT_VALUES_PROPERTY': return defaultValuesField;
+ case 'CALL_NAME_PROPERTY': return callNameField;
default:
compiler.reportError(
node, MessageKind.GENERIC,
diff --git a/pkg/compiler/lib/src/js_backend/runtime_types.dart b/pkg/compiler/lib/src/js_backend/runtime_types.dart
index f8aa7b1..eb4616c 100644
--- a/pkg/compiler/lib/src/js_backend/runtime_types.dart
+++ b/pkg/compiler/lib/src/js_backend/runtime_types.dart
@@ -257,11 +257,9 @@
void computeRequiredChecks() {
Set<DartType> isChecks = compiler.codegenWorld.isChecks;
- bool hasFunctionTypeCheck =
- isChecks.any((type) => identical(type.kind, TypeKind.FUNCTION));
- Set<DartType> instantiatedTypesAndClosures = hasFunctionTypeCheck
- ? computeInstantiatedTypesAndClosures(compiler.codegenWorld)
- : compiler.codegenWorld.instantiatedTypes;
+ // These types are needed for is-checks against function types.
+ Set<DartType> instantiatedTypesAndClosures =
+ computeInstantiatedTypesAndClosures(compiler.codegenWorld);
computeInstantiatedArguments(instantiatedTypesAndClosures, isChecks);
computeCheckedArguments(instantiatedTypesAndClosures, isChecks);
cachedRequiredChecks =
diff --git a/pkg/compiler/lib/src/js_emitter/code_emitter_task.dart b/pkg/compiler/lib/src/js_emitter/code_emitter_task.dart
index e384d93..7f64f57 100644
--- a/pkg/compiler/lib/src/js_emitter/code_emitter_task.dart
+++ b/pkg/compiler/lib/src/js_emitter/code_emitter_task.dart
@@ -283,24 +283,7 @@
.toSet();
neededClasses.addAll(mixinClasses);
- // 3. If we need noSuchMethod support, we run through all needed
- // classes to figure out if we need the support on any native
- // class. If so, we let the native emitter deal with it.
- if (compiler.enabledNoSuchMethod) {
- String noSuchMethodName = Compiler.NO_SUCH_METHOD;
- Selector noSuchMethodSelector = compiler.noSuchMethodSelector;
- for (ClassElement element in neededClasses) {
- if (!element.isNative) continue;
- Element member = element.lookupLocalMember(noSuchMethodName);
- if (member == null) continue;
- if (noSuchMethodSelector.applies(member, compiler.world)) {
- nativeEmitter.handleNoSuchMethod = true;
- break;
- }
- }
- }
-
- // 4. Find all classes needed for rti.
+ // 3. Find all classes needed for rti.
// It is important that this is the penultimate step, at this point,
// neededClasses must only contain classes that have been resolved and
// codegen'd. The rtiNeededClasses may contain additional classes, but
@@ -335,7 +318,7 @@
neededClasses.add(compiler.listClass);
}
- // 5. Finally, sort the classes.
+ // 4. Finally, sort the classes.
List<ClassElement> sortedClasses = Elements.sortedByPosition(neededClasses);
for (ClassElement element in sortedClasses) {
diff --git a/pkg/compiler/lib/src/js_emitter/model.dart b/pkg/compiler/lib/src/js_emitter/model.dart
index 96e0da9..8d3ba95 100644
--- a/pkg/compiler/lib/src/js_emitter/model.dart
+++ b/pkg/compiler/lib/src/js_emitter/model.dart
@@ -15,6 +15,7 @@
class Program {
final List<Fragment> fragments;
+ final List<Holder> holders;
final bool outputContainsConstantList;
final bool outputContainsNativeClasses;
final bool hasIsolateSupport;
@@ -30,6 +31,7 @@
final MetadataCollector _metadataCollector;
Program(this.fragments,
+ this.holders,
this.loadMap,
this.typeToInterceptorMap,
this._metadataCollector,
@@ -95,8 +97,7 @@
this.staticLazilyInitializedFields,
this.constants);
- bool get isMainFragment => mainFragment == this;
- MainFragment get mainFragment;
+ bool get isMainFragment;
}
/**
@@ -107,7 +108,6 @@
*/
class MainFragment extends Fragment {
final js.Statement invokeMain;
- final List<Holder> holders;
MainFragment(OutputUnit outputUnit,
String outputFileName,
@@ -115,8 +115,7 @@
List<Library> libraries,
List<StaticField> staticNonFinalFields,
List<StaticField> staticLazilyInitializedFields,
- List<Constant> constants,
- this.holders)
+ List<Constant> constants)
: super(outputUnit,
outputFileName,
libraries,
@@ -124,22 +123,18 @@
staticLazilyInitializedFields,
constants);
- MainFragment get mainFragment => this;
+ bool get isMainFragment => true;
}
/**
* An output (file) for deferred code.
*/
class DeferredFragment extends Fragment {
- final MainFragment mainFragment;
final String name;
- List<Holder> get holders => mainFragment.holders;
-
DeferredFragment(OutputUnit outputUnit,
String outputFileName,
this.name,
- this.mainFragment,
List<Library> libraries,
List<StaticField> staticNonFinalFields,
List<StaticField> staticLazilyInitializedFields,
@@ -150,6 +145,8 @@
staticNonFinalFields,
staticLazilyInitializedFields,
constants);
+
+ bool get isMainFragment => false;
}
class Constant {
@@ -350,7 +347,18 @@
final List<ParameterStubMethod> parameterStubs;
final bool canBeApplied;
final bool canBeReflected;
- final DartType type;
+
+ // Is non-null if [needsTearOff] or [canBeReflected].
+ //
+ // If the type is encoded in the metadata table this field contains an index
+ // into the table. Otherwise the type contains type variables in which case
+ // this field holds a function computing the function signature.
+ final js.Expression functionType;
+
+ // Signature information for this method. This is only required and stored
+ // here if the method [canBeApplied] or [canBeReflected]
+ final int requiredParameterCount;
+ final /* Map | List */ optionalParameterDefaultValues;
// If this method can be torn off, contains the name of the corresponding
// call method. For example, for the member `foo$1$name` it would be
@@ -358,14 +366,18 @@
final String callName;
DartMethod(Element element, String name, js.Expression code,
- this.parameterStubs, this.callName, this.type,
+ this.parameterStubs, this.callName,
{this.needsTearOff, this.tearOffName, this.canBeApplied,
- this.canBeReflected})
+ this.canBeReflected, this.requiredParameterCount,
+ this.optionalParameterDefaultValues, this.functionType})
: super(element, name, code) {
assert(needsTearOff != null);
assert(!needsTearOff || tearOffName != null);
assert(canBeApplied != null);
assert(canBeReflected != null);
+ assert((!canBeReflected && !canBeApplied) ||
+ (requiredParameterCount != null &&
+ optionalParameterDefaultValues != null));
}
}
@@ -380,18 +392,24 @@
InstanceMethod(Element element, String name, js.Expression code,
List<ParameterStubMethod> parameterStubs,
- String callName, DartType type,
+ String callName,
{bool needsTearOff,
String tearOffName,
this.aliasName,
bool canBeApplied,
bool canBeReflected,
- this.isClosure})
- : super(element, name, code, parameterStubs, callName, type,
+ int requiredParameterCount,
+ /* List | Map */ optionalParameterDefaultValues,
+ this.isClosure,
+ js.Expression functionType})
+ : super(element, name, code, parameterStubs, callName,
needsTearOff: needsTearOff,
tearOffName: tearOffName,
canBeApplied: canBeApplied,
- canBeReflected: canBeReflected) {
+ canBeReflected: canBeReflected,
+ requiredParameterCount: requiredParameterCount,
+ optionalParameterDefaultValues: optionalParameterDefaultValues,
+ functionType: functionType) {
assert(isClosure != null);
}
}
@@ -435,14 +453,19 @@
StaticDartMethod(Element element, String name, this.holder,
js.Expression code, List<ParameterStubMethod> parameterStubs,
- String callName, DartType type,
+ String callName,
{bool needsTearOff, String tearOffName, bool canBeApplied,
- bool canBeReflected})
- : super(element, name, code, parameterStubs, callName, type,
+ bool canBeReflected, int requiredParameterCount,
+ /* List | Map */ optionalParameterDefaultValues,
+ js.Expression functionType})
+ : super(element, name, code, parameterStubs, callName,
needsTearOff: needsTearOff,
tearOffName : tearOffName,
canBeApplied : canBeApplied,
- canBeReflected : canBeReflected);
+ canBeReflected : canBeReflected,
+ requiredParameterCount: requiredParameterCount,
+ optionalParameterDefaultValues: optionalParameterDefaultValues,
+ functionType: functionType);
}
class StaticStubMethod extends StubMethod implements StaticMethod {
diff --git a/pkg/compiler/lib/src/js_emitter/native_emitter.dart b/pkg/compiler/lib/src/js_emitter/native_emitter.dart
index ecde823..5749e79 100644
--- a/pkg/compiler/lib/src/js_emitter/native_emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/native_emitter.dart
@@ -22,11 +22,6 @@
// Caches the methods that have a native body.
Set<FunctionElement> nativeMethods;
- // Do we need the native emitter to take care of handling
- // noSuchMethod for us? This flag is set to true in the emitter if
- // it finds any native class that needs noSuchMethod handling.
- bool handleNoSuchMethod = false;
-
NativeEmitter(CodeEmitterTask emitterTask)
: this.emitterTask = emitterTask,
subtypes = new Map<ClassElement, List<ClassElement>>(),
diff --git a/pkg/compiler/lib/src/js_emitter/new_emitter/model_emitter.dart b/pkg/compiler/lib/src/js_emitter/new_emitter/model_emitter.dart
index de9ea11..3e913ab 100644
--- a/pkg/compiler/lib/src/js_emitter/new_emitter/model_emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/new_emitter/model_emitter.dart
@@ -4,6 +4,7 @@
library dart2js.new_js_emitter.model_emitter;
+import '../../constants/values.dart' show ConstantValue;
import '../../dart2jslib.dart' show Compiler;
import '../../dart_types.dart' show DartType;
import '../../elements/elements.dart' show ClassElement;
@@ -69,8 +70,7 @@
// deferred hash (which depends on the output) when emitting the main
// fragment.
fragments.skip(1).forEach((DeferredFragment deferredUnit) {
- js.Expression ast =
- emitDeferredFragment(deferredUnit, mainFragment.holders);
+ js.Expression ast = emitDeferredFragment(deferredUnit, program.holders);
String code = js.prettyPrint(ast, compiler).getText();
totalSize += code.length;
compiler.outputProvider(deferredUnit.outputFileName, deferredExtension)
@@ -111,18 +111,25 @@
Map<String, dynamic> holes =
{'deferredInitializer': emitDeferredInitializerGlobal(program.loadMap),
- 'holders': emitHolders(fragment.holders),
- 'tearOff': buildTearOffCode(backend),
- 'parseFunctionDescriptor':
- js.js.statement(parseFunctionDescriptorBoilerplate),
+ 'holders': emitHolders(program.holders),
+ 'tearOff': buildTearOffCode(backend),
+ 'parseFunctionDescriptor':
+ js.js.statement(parseFunctionDescriptorBoilerplate,
+ {'argumentCount': js.string(namer.requiredParameterField),
+ 'defaultArgumentValues': js.string(namer.defaultValuesField),
+ 'callName': js.string(namer.callNameField)}),
+
'cyclicThrow':
- backend.emitter.staticFunctionAccess(backend.getCyclicThrowHelper()),
+ backend.emitter.staticFunctionAccess(backend.getCyclicThrowHelper()),
'outputContainsConstantList': program.outputContainsConstantList,
'embeddedGlobals': emitEmbeddedGlobals(program),
'constants': emitConstants(fragment.constants),
'staticNonFinals':
- emitStaticNonFinalFields(fragment.staticNonFinalFields),
+ emitStaticNonFinalFields(fragment.staticNonFinalFields),
'operatorIsPrefix': js.string(namer.operatorIsPrefix),
+ 'callName': js.string(namer.callNameField),
+ 'argumentCount': js.string(namer.requiredParameterField),
+ 'defaultArgumentValues': js.string(namer.defaultValuesField),
'eagerClasses': emitEagerClassInitializations(fragment.libraries),
'invokeMain': fragment.invokeMain,
'code': code};
@@ -553,19 +560,27 @@
/// facilitate the generation of tearOffs at runtime. The format is an array
/// with the following fields:
///
- /// [InstanceMethod.aliasName] (optional).
- /// [Method.code]
- /// [DartMethod.callName]
- /// isInterceptedMethod (optional, present if [DartMethod.needsTearOff]).
- /// [DartMethod.tearOffName] (optional, present if [DartMethod.needsTearOff]).
- /// functionType (optional, present if [DartMethod.needsTearOff]).
+ /// * [InstanceMethod.aliasName] (optional).
+ /// * [Method.code]
+ /// * [DartMethod.callName]
+ /// * isInterceptedMethod (optional, present if [DartMethod.needsTearOff]).
+ /// * [DartMethod.tearOffName] (optional, present if
+ /// [DartMethod.needsTearOff]).
+ /// * functionType (optional, present if [DartMethod.needsTearOff]).
///
/// followed by
///
- /// [ParameterStubMethod.name]
- /// [ParameterStubMethod.code]
+ /// * [ParameterStubMethod.name]
+ /// * [ParameterStubMethod.callName]
+ /// * [ParameterStubMethod.code]
///
/// for each stub in [DartMethod.parameterStubs].
+ ///
+ /// If the closure could be used in `Function.apply` (i.e.
+ /// [DartMethod.canBeApplied] is true) then the following fields are appended:
+ ///
+ /// * [DartMethod.requiredParameterCount]
+ /// * [DartMethod.optionalParameterDefaultValues]
static final String parseFunctionDescriptorBoilerplate = r"""
function parseFunctionDescriptor(proto, name, descriptor) {
@@ -582,7 +597,7 @@
proto[name] = f;
var funs = [f];
- f.$callName = descriptor[++pos];
+ f[#callName] = descriptor[++pos];
var isInterceptedOrParameterStubName = descriptor[pos + 1];
var isIntercepted, tearOffName, reflectionInfo;
@@ -592,9 +607,12 @@
reflectionInfo = descriptor[++pos];
}
- for (++pos; pos < descriptor.length; pos += 3) {
+ // We iterate in blocks of 3 but have to stop before we reach the (optional)
+ // two trailing items. To accomplish this, we only iterate until we reach
+ // length - 2.
+ for (++pos; pos < descriptor.length - 2; pos += 3) {
var stub = descriptor[pos + 2];
- stub.$callName = descriptor[pos + 1];
+ stub[#callName] = descriptor[pos + 1];
proto[descriptor[pos]] = stub;
funs.push(stub);
}
@@ -603,19 +621,31 @@
proto[tearOffName] =
tearOff(funs, reflectionInfo, false, name, isIntercepted);
}
-
+ if (pos < descriptor.length) {
+ f[#argumentCount] = descriptor[pos];
+ f[#defaultArgumentValues] = descriptor[pos + 1];
+ }
} else {
proto[name] = descriptor;
}
}
""";
- js.Expression _generateFunctionType(DartType memberType) {
- if (memberType.containsTypeVariables) {
- js.Expression thisAccess = js.js(r'this.$receiver');
- return backend.rti.getSignatureEncoding(memberType, thisAccess);
+ js.Expression _encodeOptionalParameterDefaultValues(DartMethod method) {
+ js.Expression result;
+ // TODO(herhut): Replace [js.LiteralNull] with [js.ArrayHole].
+ if (method.optionalParameterDefaultValues is List) {
+ List<ConstantValue> defs = method.optionalParameterDefaultValues;
+ Iterable<js.Expression> elements = defs.map(constantEmitter.reference);
+ return new js.ArrayInitializer(elements.toList());
} else {
- return js.number(backend.emitter.metadataCollector.reifyType(memberType));
+ Map<String, ConstantValue> defs = method.optionalParameterDefaultValues;
+ List<js.Property> properties = <js.Property>[];
+ defs.forEach((String name, ConstantValue value) {
+ properties.add(new js.Property(js.string(name),
+ constantEmitter.reference(value)));
+ });
+ return new js.ObjectInitializer(properties);
}
}
@@ -649,10 +679,14 @@
bool isIntercepted = backend.isInterceptedMethod(method.element);
data.add(new js.LiteralBool(isIntercepted));
data.add(js.string(method.tearOffName));
- data.add(_generateFunctionType(method.type));
+ data.add((method.functionType));
}
data.addAll(method.parameterStubs.expand(makeNameCallNameCodeTriplet));
+ if (method.canBeApplied) {
+ data.add(js.number(method.requiredParameterCount));
+ data.add(_encodeOptionalParameterDefaultValues(method));
+ }
return [js.string(method.name), new js.ArrayInitializer(data)];
} else {
// TODO(floitsch): not the most efficient way...
@@ -694,8 +728,12 @@
var data = [unparse(compiler, method.code)];
data.add(js.string(method.callName));
data.add(js.string(method.tearOffName));
- data.add(_generateFunctionType(method.type));
+ data.add(method.functionType);
data.addAll(method.parameterStubs.expand(makeNameCallNameCodeTriplet));
+ if (method.canBeApplied) {
+ data.add(js.number(method.requiredParameterCount));
+ data.add(_encodeOptionalParameterDefaultValues(method));
+ }
return [js.string(method.name), holderIndex,
new js.ArrayInitializer(data)];
} else {
@@ -783,13 +821,16 @@
function compileAllStubs() {
var funs;
var fun = compile(name, descriptor[0]);
- fun.\$callName = descriptor[1];
+ fun[#callName] = descriptor[1];
holder[name] = fun;
funs = [fun];
- for (var pos = 4; pos < descriptor.length; pos += 3) {
+ // We iterate in blocks of 3 but have to stop before we reach the
+ // (optional) two trailing items. To accomplish this, we only iterate
+ // until we reach length - 2.
+ for (var pos = 4; pos < descriptor.length - 2; pos += 3) {
var stubName = descriptor[pos];
fun = compile(stubName, descriptor[pos + 2]);
- fun.\$callName = descriptor[pos + 1];
+ fun[#callName] = descriptor[pos + 1];
holder[stubName] = fun;
funs.push(fun);
}
@@ -798,6 +839,10 @@
holder[descriptor[2]] =
tearOff(funs, descriptor[3], true, name, false);
}
+ if (pos < descriptor.length) {
+ fun[#argumentCount] = descriptor[pos];
+ fun[#defaultArgumentValues] = descriptor[pos + 1];
+ }
}
function setupCompileAllAndDelegateStub(name) {
@@ -842,23 +887,19 @@
}
function setupClass(name, holder, descriptor) {
- var ensureResolved = function() {
+ var patch = function() {
var constructor = compileConstructor(name, descriptor);
holder[name] = constructor;
constructor.ensureResolved = function() { return this; };
- return constructor;
- };
-
- var patch = function() {
- var constructor = ensureResolved();
+ if (this === patch) return constructor; // Was used as "ensureResolved".
var object = new constructor();
constructor.apply(object, arguments);
return object;
};
- // We store the ensureResolved function on the patch function to make it
+ // We store the patch function on itself to make it
// possible to resolve superclass references without constructing instances.
- patch.ensureResolved = ensureResolved;
+ patch.ensureResolved = patch;
holder[name] = patch;
}
diff --git a/pkg/compiler/lib/src/js_emitter/old_emitter/class_emitter.dart b/pkg/compiler/lib/src/js_emitter/old_emitter/class_emitter.dart
index 0193ba2..064e35f 100644
--- a/pkg/compiler/lib/src/js_emitter/old_emitter/class_emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/old_emitter/class_emitter.dart
@@ -44,14 +44,6 @@
emitRuntimeTypeInformation(cls, builder);
emitNativeInfo(cls, builder);
- if (classElement == backend.closureClass) {
- // We add a special getter here to allow for tearing off a closure from
- // itself.
- String name = namer.getMappedInstanceName(Compiler.CALL_OPERATOR_NAME);
- jsAst.Fun function = js('function() { return this; }');
- builder.addProperty(namer.getterNameFromAccessorName(name), function);
- }
-
emitClassBuilderWithReflectionData(cls, builder, enclosingBuilder);
}
/**
@@ -248,9 +240,7 @@
// so that the code in the dynamicFunction helper can find
// them. Note that this helper is invoked before analyzing the
// full JS script.
- if (!emitter.nativeEmitter.handleNoSuchMethod) {
- emitter.nsmEmitter.emitNoSuchMethodHandlers(builder.addProperty);
- }
+ emitter.nsmEmitter.emitNoSuchMethodHandlers(builder.addProperty);
}
}
diff --git a/pkg/compiler/lib/src/js_emitter/old_emitter/container_builder.dart b/pkg/compiler/lib/src/js_emitter/old_emitter/container_builder.dart
index ac8fdf7..4624980 100644
--- a/pkg/compiler/lib/src/js_emitter/old_emitter/container_builder.dart
+++ b/pkg/compiler/lib/src/js_emitter/old_emitter/container_builder.dart
@@ -23,6 +23,7 @@
bool isClosure = method is InstanceMethod && method.isClosure;
String superAlias = method is InstanceMethod ? method.aliasName : null;
bool hasSuperAlias = superAlias != null;
+ jsAst.Expression memberTypeExpression = method.functionType;
bool needStructuredInfo =
canTearOff || canBeReflected || canBeApplied || hasSuperAlias;
@@ -126,28 +127,13 @@
tearOffInfo.add(new jsAst.LiteralString(callSelectorString));
}
- jsAst.Expression memberTypeExpression;
- if (canTearOff || canBeReflected) {
- DartType memberType = method.type;
- if (memberType.containsTypeVariables) {
- jsAst.Expression thisAccess = js(r'this.$receiver');
- memberTypeExpression =
- backend.rti.getSignatureEncoding(memberType, thisAccess);
- } else {
- memberTypeExpression =
- js.number(task.metadataCollector.reifyType(memberType));
- }
- } else {
- memberTypeExpression = js('null');
- }
-
expressions
..addAll(tearOffInfo)
..add((tearOffName == null || member.isAccessor)
? js("null") : js.string(tearOffName))
..add(js.number(requiredParameterCount))
..add(js.number(optionalParameterCount))
- ..add(memberTypeExpression)
+ ..add(memberTypeExpression == null ? js("null") : memberTypeExpression)
..addAll(task.metadataCollector
.reifyDefaultArguments(member).map(js.number));
diff --git a/pkg/compiler/lib/src/js_emitter/old_emitter/emitter.dart b/pkg/compiler/lib/src/js_emitter/old_emitter/emitter.dart
index a575e1c..bbce58a 100644
--- a/pkg/compiler/lib/src/js_emitter/old_emitter/emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/old_emitter/emitter.dart
@@ -420,10 +420,9 @@
/** Needs defineClass to be defined. */
jsAst.Expression buildInheritFrom() {
- jsAst.Expression result = js(r'''
+ jsAst.Expression result = js(r"""
function() {
function tmp() {}
- var hasOwnProperty = Object.prototype.hasOwnProperty;
return function (constructor, superConstructor) {
if (superConstructor == null) {
// Fix up the the Dart Object class' prototype.
@@ -435,10 +434,10 @@
tmp.prototype = superConstructor.prototype;
var object = new tmp();
var properties = constructor.prototype;
- for (var member in properties) {
- if (hasOwnProperty.call(properties, member)) {
- object[member] = properties[member];
- }
+ var members = Object.keys(properties);
+ for (var i = 0; i < members.length; i++) {
+ var member = members[i];
+ object[member] = properties[member];
}
// Use a function for `true` here, as functions are stored in the
// hidden class and not as properties in the object.
@@ -448,7 +447,7 @@
return object;
};
}()
- ''', { 'operatorIsPrefix' : js.string(namer.operatorIsPrefix),
+ """, { 'operatorIsPrefix' : js.string(namer.operatorIsPrefix),
'isObject' : namer.operatorIs(compiler.objectClass) });
if (compiler.hasIncrementalSupport) {
result = js(
@@ -498,9 +497,11 @@
var mixin = allClasses[mixinClass];
var mixinPrototype = mixin.prototype;
var clsPrototype = allClasses[cls].prototype;
- for (var d in mixinPrototype) {
- if (hasOwnProperty.call(mixinPrototype, d) &&
- !hasOwnProperty.call(clsPrototype, d))
+
+ var properties = Object.keys(mixinPrototype);
+ for (var i = 0; i < properties.length; i++) {
+ var d = properties[i];
+ if (!hasOwnProperty.call(clsPrototype, d))
clsPrototype[d] = mixinPrototype[d];
}
}
@@ -1014,10 +1015,12 @@
$finishIsolateConstructorName = function (oldIsolate) {
var isolateProperties = oldIsolate.#isolatePropertiesName;
function Isolate() {
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- for (var staticName in isolateProperties)
- if (hasOwnProperty.call(isolateProperties, staticName))
- this[staticName] = isolateProperties[staticName];
+
+ var staticNames = Object.keys(isolateProperties);
+ for (var i = 0; i < staticNames.length; i++) {
+ var staticName = staticNames[i];
+ this[staticName] = isolateProperties[staticName];
+ }
// Reset lazy initializers to null.
// When forcing the object to fast mode (below) v8 will consider
@@ -1025,8 +1028,9 @@
// (after the first call to the getter), we would have a map
// transition.
var lazies = init.lazies;
- for (var lazyInit in lazies) {
- this[lazies[lazyInit]] = null;
+ var lazyInitializers = lazies ? Object.keys(lazies) : [];
+ for (var i = 0; i < lazyInitializers.length; i++) {
+ this[lazies[lazyInitializers[i]]] = null;
}
// Use the newly created object as prototype. In Chrome,
@@ -1037,8 +1041,8 @@
new ForceEfficientMap();
// Now, after being a fast map we can set the lazies again.
- for (var lazyInit in lazies) {
- var lazyInitName = lazies[lazyInit];
+ for (var i = 0; i < lazyInitializers.length; i++) {
+ var lazyInitName = lazies[lazyInitializers[i]];
this[lazyInitName] = isolateProperties[lazyInitName];
}
}
diff --git a/pkg/compiler/lib/src/js_emitter/old_emitter/nsm_emitter.dart b/pkg/compiler/lib/src/js_emitter/old_emitter/nsm_emitter.dart
index 93f866b..a3e5a38 100644
--- a/pkg/compiler/lib/src/js_emitter/old_emitter/nsm_emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/old_emitter/nsm_emitter.dart
@@ -280,11 +280,6 @@
' objectClassObject = objectClassObject[1];'));
}
- // TODO(9631): This is no longer valid for native methods.
- String whatToPatch = emitter.nativeEmitter.handleNoSuchMethod ?
- "Object.prototype" :
- "objectClassObject";
-
List<jsAst.Expression> sliceOffsetArguments =
firstNormalSelector == 0
? []
@@ -309,8 +304,8 @@
// createInvocationMirror(String name, internalName, type,
// arguments, argumentNames)
//
- $whatToPatch[short] = (function(name, short,
- type, #sliceOffsetParams) {
+ objectClassObject[short] = (function(name, short,
+ type, #sliceOffsetParams) {
return function() {
return this.#noSuchMethodName(this,
#createInvocationMirror(name, short, type,
diff --git a/pkg/compiler/lib/src/js_emitter/old_emitter/reflection_data_parser.dart b/pkg/compiler/lib/src/js_emitter/old_emitter/reflection_data_parser.dart
index ae053a1..c595178 100644
--- a/pkg/compiler/lib/src/js_emitter/old_emitter/reflection_data_parser.dart
+++ b/pkg/compiler/lib/src/js_emitter/old_emitter/reflection_data_parser.dart
@@ -57,11 +57,12 @@
function processClassData(cls, descriptor, processedClasses) {
var newDesc = {};
var previousProperty;
- for (var property in descriptor) {
- if (!hasOwnProperty.call(descriptor, property)) continue;
+ var properties = Object.keys(descriptor);
+ for (var i = 0; i < properties.length; i++) {
+ var property = properties[i];
var firstChar = property.substring(0, 1);
if (property === "static") {
- processStatics(#embeddedStatics[cls] = descriptor[property],
+ processStatics(#embeddedStatics[cls] = descriptor[property],
processedClasses);
} else if (firstChar === "+") {
mangledNames[previousProperty] = property.substring(1);
@@ -135,8 +136,9 @@
// TODO(zarah): Remove empty else branches in output when if(#hole) is false.
jsAst.Statement processStatics = js.statement('''
function processStatics(descriptor, processedClasses) {
- for (var property in descriptor) {
- if (!hasOwnProperty.call(descriptor, property)) continue;
+ var properties = Object.keys(descriptor);
+ for (var i = 0; i < properties.length; i++) {
+ var property = properties[i];
if (property === "${namer.classDescriptorProperty}") continue;
var element = descriptor[property];
var firstChar = property.substring(0, 1);
@@ -407,7 +409,8 @@
#trivialNsmHandlers;
- for (var cls in processedClasses.pending) finishClass(cls);
+ var properties = Object.keys(processedClasses.pending);
+ for (var i = 0; i < properties.length; i++) finishClass(properties[i]);
}
}''', {'allClasses': allClassesAccess,
'debugFastObjects': DEBUG_FAST_OBJECTS,
diff --git a/pkg/compiler/lib/src/js_emitter/program_builder.dart b/pkg/compiler/lib/src/js_emitter/program_builder.dart
index 7036bb7..2d22ead 100644
--- a/pkg/compiler/lib/src/js_emitter/program_builder.dart
+++ b/pkg/compiler/lib/src/js_emitter/program_builder.dart
@@ -24,8 +24,11 @@
RuntimeTypeGenerator,
TypeTestProperties;
+import '../elements/elements.dart' show ParameterElement;
+
import '../universe/universe.dart' show Universe;
import '../deferred_load.dart' show DeferredLoadTask, OutputUnit;
+import '../constants/expressions.dart' show ConstantExpression, ConstantValue;
part 'registry.dart';
@@ -104,21 +107,24 @@
_unneededNativeClasses =
_task.nativeEmitter.prepareNativeClasses(nativeClasses);
- MainFragment mainOutput = _buildMainOutput(_registry.mainLibrariesMap);
- Iterable<Fragment> deferredOutputs = _registry.deferredLibrariesMap
- .map((librariesMap) => _buildDeferredOutput(mainOutput, librariesMap));
+ MainFragment mainFragment = _buildMainFragment(_registry.mainLibrariesMap);
+ Iterable<Fragment> deferredFragments =
+ _registry.deferredLibrariesMap.map(_buildDeferredFragment);
- List<Fragment> outputs = new List<Fragment>(_registry.librariesMapCount);
- outputs[0] = mainOutput;
- outputs.setAll(1, deferredOutputs);
+ List<Fragment> fragments = new List<Fragment>(_registry.librariesMapCount);
+ fragments[0] = mainFragment;
+ fragments.setAll(1, deferredFragments);
_markEagerClasses();
bool containsNativeClasses =
nativeClasses.length != _unneededNativeClasses.length;
+ List<Holder> holders = _registry.holders.toList(growable: false);
+
return new Program(
- outputs,
+ fragments,
+ holders,
_buildLoadMap(),
_buildTypeToInterceptorMap(),
_task.metadataCollector,
@@ -149,7 +155,7 @@
return stubGenerator.generateTypeToInterceptorMap();
}
- MainFragment _buildMainOutput(LibrariesMap librariesMap) {
+ MainFragment _buildMainFragment(LibrariesMap librariesMap) {
// Construct the main output from the libraries and the registered holders.
MainFragment result = new MainFragment(
librariesMap.outputUnit,
@@ -158,8 +164,7 @@
_buildLibraries(librariesMap),
_buildStaticNonFinalFields(librariesMap),
_buildStaticLazilyInitializedFields(librariesMap),
- _buildConstants(librariesMap),
- _registry.holders.toList(growable: false));
+ _buildConstants(librariesMap));
_outputs[librariesMap.outputUnit] = result;
return result;
}
@@ -170,13 +175,11 @@
return generator.generateInvokeMain();
}
- DeferredFragment _buildDeferredOutput(MainFragment mainOutput,
- LibrariesMap librariesMap) {
+ DeferredFragment _buildDeferredFragment(LibrariesMap librariesMap) {
DeferredFragment result = new DeferredFragment(
librariesMap.outputUnit,
backend.deferredPartFileName(librariesMap.name, addExtension: false),
librariesMap.name,
- mainOutput,
_buildLibraries(librariesMap),
_buildStaticNonFinalFields(librariesMap),
_buildStaticLazilyInitializedFields(librariesMap),
@@ -209,10 +212,17 @@
StaticField _buildStaticField(Element element) {
JavaScriptConstantCompiler handler = backend.constants;
ConstantValue initialValue = handler.getInitialValueFor(element).value;
+ // TODO(zarah): The holder should not be registered during building of
+ // a static field.
+ _registry.registerHolder(namer.globalObjectForConstant(initialValue));
js.Expression code = _task.emitter.constantReference(initialValue);
String name = namer.getNameOfGlobalField(element);
bool isFinal = false;
bool isLazy = false;
+
+ // TODO(floitsch): we shouldn't update the registry in the middle of
+ // building a static field. (Note that the $ holder is already registered
+ // earlier).
return new StaticField(element,
name, _registry.registerHolder(r'$'), code,
isFinal, isLazy);
@@ -245,6 +255,9 @@
String name = namer.getNameOfGlobalField(element);
bool isFinal = element.isFinal;
bool isLazy = true;
+ // TODO(floitsch): we shouldn't update the registry in the middle of
+ // building a static field. (Note that the $ holder is already registered
+ // earlier).
return new StaticField(element,
name, _registry.registerHolder(r'$'), code,
isFinal, isLazy);
@@ -353,6 +366,15 @@
});
}
+ if (element == backend.closureClass) {
+ // We add a special getter here to allow for tearing off a closure from
+ // itself.
+ String name = namer.getterNameFromAccessorName(
+ namer.getMappedInstanceName(Compiler.CALL_OPERATOR_NAME));
+ js.Fun function = js.js('function() { return this; }');
+ callStubs.add(_buildStubMethod(name, function));
+ }
+
ClassElement implementation = element.implementation;
// MixinApplications run through the members of their mixin. Here, we are
@@ -378,6 +400,8 @@
String name = namer.getNameOfClass(element);
String holderName = namer.globalObjectFor(element);
+ // TODO(floitsch): we shouldn't update the registry in the middle of
+ // building a class.
Holder holder = _registry.registerHolder(holderName);
bool isInstantiated =
_compiler.codegenWorld.directlyInstantiatedClasses.contains(element);
@@ -440,6 +464,26 @@
}
}
+ /* Map | List */ _computeParameterDefaultValues(FunctionSignature signature) {
+ var /* Map | List */ optionalParameterDefaultValues;
+ if (signature.optionalParametersAreNamed) {
+ optionalParameterDefaultValues = new Map<String, ConstantValue>();
+ signature.forEachOptionalParameter((ParameterElement parameter) {
+ ConstantExpression def =
+ backend.constants.getConstantForVariable(parameter);
+ optionalParameterDefaultValues[parameter.name] = def.value;
+ });
+ } else {
+ optionalParameterDefaultValues = <ConstantValue>[];
+ signature.forEachOptionalParameter((ParameterElement parameter) {
+ ConstantExpression def =
+ backend.constants.getConstantForVariable(parameter);
+ optionalParameterDefaultValues.add(def.value);
+ });
+ }
+ return optionalParameterDefaultValues;
+ }
+
DartMethod _buildMethod(FunctionElement element) {
String name = namer.getNameOfInstanceMember(element);
js.Expression code = backend.generatedCode[element];
@@ -500,11 +544,37 @@
memberType = element.type;
}
+ js.Expression functionType;
+ if (canTearOff || canBeReflected) {
+ functionType = _generateFunctionType(memberType);
+ }
+
+ int requiredParameterCount;
+ var /* List | Map */ optionalParameterDefaultValues;
+ if (canBeApplied || canBeReflected) {
+ FunctionSignature signature = element.functionSignature;
+ requiredParameterCount = signature.requiredParameterCount;
+ optionalParameterDefaultValues =
+ _computeParameterDefaultValues(signature);
+ }
+
return new InstanceMethod(element, name, code,
- _generateParameterStubs(element, canTearOff), callName, memberType,
+ _generateParameterStubs(element, canTearOff), callName,
needsTearOff: canTearOff, tearOffName: tearOffName,
isClosure: isClosure, aliasName: aliasName,
- canBeApplied: canBeApplied, canBeReflected: canBeReflected);
+ canBeApplied: canBeApplied, canBeReflected: canBeReflected,
+ requiredParameterCount: requiredParameterCount,
+ optionalParameterDefaultValues: optionalParameterDefaultValues,
+ functionType: functionType);
+ }
+
+ js.Expression _generateFunctionType(DartType type) {
+ if (type.containsTypeVariables) {
+ js.Expression thisAccess = js.js(r'this.$receiver');
+ return backend.rti.getSignatureEncoding(type, thisAccess);
+ } else {
+ return js.number(backend.emitter.metadataCollector.reifyType(type));
+ }
}
List<ParameterStubMethod> _generateParameterStubs(FunctionElement element,
@@ -545,6 +615,8 @@
new InterceptorStubGenerator(_compiler, namer, backend);
String holderName = namer.globalObjectFor(backend.interceptorsLibrary);
+ // TODO(floitsch): we shouldn't update the registry in the middle of
+ // generating the interceptor methods.
Holder holder = _registry.registerHolder(holderName);
Map<String, Set<ClassElement>> specializedGetInterceptors =
@@ -608,6 +680,8 @@
new InterceptorStubGenerator(_compiler, namer, backend);
String holderName = namer.globalObjectFor(backend.interceptorsLibrary);
+ // TODO(floitsch): we shouldn't update the registry in the middle of
+ // generating the interceptor methods.
Holder holder = _registry.registerHolder(holderName);
List<String> names = backend.oneShotInterceptors.keys.toList()..sort();
@@ -633,21 +707,42 @@
String tearOffName =
needsTearOff ? namer.getStaticClosureName(element) : null;
+
String callName = null;
if (needsTearOff) {
Selector callSelector =
new Selector.fromElement(element).toCallSelector();
callName = namer.invocationName(callSelector);
}
+ js.Expression functionType;
+ DartType type = element.type;
+ if (needsTearOff || canBeReflected) {
+ functionType = _generateFunctionType(type);
+ }
+ int requiredParameterCount;
+ var /* List | Map */ optionalParameterDefaultValues;
+ if (canBeApplied || canBeReflected) {
+ FunctionSignature signature = element.functionSignature;
+ requiredParameterCount = signature.requiredParameterCount;
+ optionalParameterDefaultValues =
+ _computeParameterDefaultValues(signature);
+ }
+
+ // TODO(floitsch): we shouldn't update the registry in the middle of
+ // building a static method.
return new StaticDartMethod(element,
name, _registry.registerHolder(holder), code,
_generateParameterStubs(element, needsTearOff),
- callName, element.type,
+ callName,
needsTearOff: needsTearOff,
tearOffName: tearOffName,
canBeApplied: canBeApplied,
- canBeReflected: canBeReflected);
+ canBeReflected: canBeReflected,
+ requiredParameterCount: requiredParameterCount,
+ optionalParameterDefaultValues:
+ optionalParameterDefaultValues,
+ functionType: functionType);
}
void _registerConstants(OutputUnit outputUnit,
diff --git a/pkg/compiler/lib/src/mirrors/dart2js_library_mirror.dart b/pkg/compiler/lib/src/mirrors/dart2js_library_mirror.dart
index 362ec6a..46c2a92 100644
--- a/pkg/compiler/lib/src/mirrors/dart2js_library_mirror.dart
+++ b/pkg/compiler/lib/src/mirrors/dart2js_library_mirror.dart
@@ -154,6 +154,14 @@
bool get isExport => _node.asExport() != null;
+ bool get isDeferred {
+ if (_node is Import) {
+ Import import = _node;
+ return import.isDeferred;
+ }
+ return false;
+ }
+
List<InstanceMirror> get metadata => const <InstanceMirror>[];
}
diff --git a/pkg/compiler/lib/src/resolution/members.dart b/pkg/compiler/lib/src/resolution/members.dart
index bd92e97..a4ddda5 100644
--- a/pkg/compiler/lib/src/resolution/members.dart
+++ b/pkg/compiler/lib/src/resolution/members.dart
@@ -530,22 +530,31 @@
}
}
+ bool _isNativeClassOrExtendsNativeClass(ClassElement classElement) {
+ assert(classElement != null);
+ while (classElement != null) {
+ if (classElement.isNative) return true;
+ classElement = classElement.superclass;
+ }
+ return false;
+ }
+
TreeElements resolveMethodElementImplementation(
FunctionElement element, FunctionExpression tree) {
return compiler.withCurrentElement(element, () {
if (element.isExternal && tree.hasBody()) {
- compiler.reportError(element,
+ error(element,
MessageKind.EXTERNAL_WITH_BODY,
{'functionName': element.name});
}
if (element.isConstructor) {
if (tree.returnType != null) {
- compiler.reportError(tree, MessageKind.CONSTRUCTOR_WITH_RETURN_TYPE);
+ error(tree, MessageKind.CONSTRUCTOR_WITH_RETURN_TYPE);
}
if (element.isConst &&
tree.hasBody() &&
!tree.isRedirectingFactory) {
- compiler.reportError(tree, MessageKind.CONST_CONSTRUCTOR_HAS_BODY);
+ error(tree, MessageKind.CONST_CONSTRUCTOR_HAS_BODY);
}
}
@@ -590,6 +599,14 @@
checkMixinSuperUses(resolutionTree, mixinApplication, mixin);
}
}
+
+ // TODO(9631): support noSuchMethod on native classes.
+ if (Elements.isInstanceMethod(element) &&
+ element.name == Compiler.NO_SUCH_METHOD &&
+ _isNativeClassOrExtendsNativeClass(enclosingClass)) {
+ error(tree, MessageKind.NO_SUCH_METHOD_IN_NATIVE);
+ }
+
return resolutionTree;
});
@@ -3699,11 +3716,7 @@
compiler.reportError(arguments,
MessageKind.TYPE_VARIABLE_IN_CONSTANT);
}
- registry.setType(node, mapType);
- registry.registerInstantiatedType(mapType);
- if (node.isConst) {
- registry.registerConstantMap();
- }
+ registry.registerMapLiteral(node, mapType, node.isConst);
registry.registerRequiredType(mapType, enclosingElement);
node.visitChildren(this);
if (node.isConst) {
diff --git a/pkg/compiler/lib/src/resolution/registry.dart b/pkg/compiler/lib/src/resolution/registry.dart
index 317efbb..15082856 100644
--- a/pkg/compiler/lib/src/resolution/registry.dart
+++ b/pkg/compiler/lib/src/resolution/registry.dart
@@ -262,6 +262,11 @@
world.registerInstantiatedClass(compiler.typeClass, this);
}
+ void registerMapLiteral(Node node, DartType type, bool isConstant) {
+ setType(node, type);
+ backend.resolutionCallbacks.onMapLiteral(this, type, isConstant);
+ }
+
// TODO(johnniwinther): Remove the [ResolverVisitor] dependency. Its only
// needed to lookup types in the current scope.
void registerJsCall(Node node, ResolverVisitor visitor) {
@@ -314,10 +319,6 @@
backend.resolutionCallbacks.onStringInterpolation(this);
}
- void registerConstantMap() {
- backend.resolutionCallbacks.onConstantMap(this);
- }
-
void registerFallThroughError() {
backend.resolutionCallbacks.onFallThroughError(this);
}
diff --git a/pkg/compiler/lib/src/scanner/keyword.dart b/pkg/compiler/lib/src/scanner/keyword.dart
index ffcf036..804a0ee 100644
--- a/pkg/compiler/lib/src/scanner/keyword.dart
+++ b/pkg/compiler/lib/src/scanner/keyword.dart
@@ -19,6 +19,7 @@
const Keyword("default"),
const Keyword("do"),
const Keyword("else"),
+ const Keyword("enum"),
const Keyword("extends"),
const Keyword("false"),
const Keyword("final"),
@@ -48,7 +49,6 @@
const Keyword("abstract", isBuiltIn: true),
const Keyword("as", info: AS_INFO, isBuiltIn: true),
const Keyword("dynamic", isBuiltIn: true),
- const Keyword("enum", isBuiltIn: true),
const Keyword("export", isBuiltIn: true),
const Keyword("external", isBuiltIn: true),
const Keyword("factory", isBuiltIn: true),
diff --git a/pkg/compiler/lib/src/source_file_provider.dart b/pkg/compiler/lib/src/source_file_provider.dart
index f254a5e..d0bd1b9 100644
--- a/pkg/compiler/lib/src/source_file_provider.dart
+++ b/pkg/compiler/lib/src/source_file_provider.dart
@@ -30,7 +30,7 @@
abstract class SourceFileProvider {
bool isWindows = (Platform.operatingSystem == 'windows');
Uri cwd = currentDirectory;
- Map<String, SourceFile> sourceFiles = <String, SourceFile>{};
+ Map<Uri, SourceFile> sourceFiles = <Uri, SourceFile>{};
int dartCharactersRead = 0;
Future<String> readStringFromUri(Uri resourceUri) {
@@ -62,8 +62,9 @@
"$detail");
}
dartCharactersRead += source.length;
- sourceFiles[resourceUri.toString()] =
- new CachingUtf8BytesSourceFile(relativizeUri(resourceUri), source);
+ sourceFiles[resourceUri] =
+ new CachingUtf8BytesSourceFile(
+ resourceUri, relativizeUri(resourceUri), source);
return new Future.value(source);
}
@@ -92,8 +93,9 @@
offset += contentPart.length;
}
dartCharactersRead += totalLength;
- sourceFiles[resourceUri.toString()] =
- new CachingUtf8BytesSourceFile(resourceUri.toString(), result);
+ sourceFiles[resourceUri] =
+ new CachingUtf8BytesSourceFile(
+ resourceUri, resourceUri.toString(), result);
return result;
});
}
@@ -202,7 +204,7 @@
if (uri == null) {
print('${color(message)}');
} else {
- SourceFile file = provider.sourceFiles[uri.toString()];
+ SourceFile file = provider.sourceFiles[uri];
if (file != null) {
print(file.getLocationMessage(
color(message), begin, end, colorize: color));
diff --git a/pkg/compiler/lib/src/ssa/builder.dart b/pkg/compiler/lib/src/ssa/builder.dart
index 1d4a274..c1d5d55 100644
--- a/pkg/compiler/lib/src/ssa/builder.dart
+++ b/pkg/compiler/lib/src/ssa/builder.dart
@@ -1155,8 +1155,8 @@
}
void checkValidSourceFileLocation(
- SourceFileLocation location, SourceFile sourceFile, int offset) {
- if (!location.isValid()) {
+ SourceLocation location, SourceFile sourceFile, int offset) {
+ if (!location.isValid) {
throw MessageKind.INVALID_SOURCE_FILE_LOCATION.message(
{'offset': offset,
'fileName': sourceFile.filename,
@@ -1340,7 +1340,7 @@
// The call is on a path which is executed rarely, so inline only if it
// does not make the program larger.
if (isCalledOnce(element)) {
- return InlineWeeder.canBeInlined(function.node, -1, false);
+ return InlineWeeder.canBeInlined(function, -1, false);
}
// TODO(sra): Measure if inlining would 'reduce' the size. One desirable
// case we miss my doing nothing is inlining very simple constructors
@@ -1367,7 +1367,7 @@
if (backend.functionsToAlwaysInline.contains(function)) {
// Inline this function regardless of it's size.
- assert(InlineWeeder.canBeInlined(function.node, -1, false,
+ assert(InlineWeeder.canBeInlined(function, -1, false,
allowLoops: true));
return true;
}
@@ -1390,9 +1390,8 @@
useMaxInliningNodes = false;
}
bool canInline;
- ast.FunctionExpression functionNode = function.node;
canInline = InlineWeeder.canBeInlined(
- functionNode, maxInliningNodes, useMaxInliningNodes);
+ function, maxInliningNodes, useMaxInliningNodes);
if (canInline) {
backend.inlineCache.markAsInlinable(element, insideLoop: insideLoop);
} else {
@@ -2518,16 +2517,16 @@
sourceFileLocationForEndToken(node));
}
- SourceFileLocation sourceFileLocationForBeginToken(ast.Node node) =>
+ SourceLocation sourceFileLocationForBeginToken(ast.Node node) =>
sourceFileLocationForToken(node, node.getBeginToken());
- SourceFileLocation sourceFileLocationForEndToken(ast.Node node) =>
+ SourceLocation sourceFileLocationForEndToken(ast.Node node) =>
sourceFileLocationForToken(node, node.getEndToken());
- SourceFileLocation sourceFileLocationForToken(ast.Node node, Token token) {
+ SourceLocation sourceFileLocationForToken(ast.Node node, Token token) {
SourceFile sourceFile = currentSourceFile();
- SourceFileLocation location =
- new TokenSourceFileLocation(sourceFile, token, sourceElement.name);
+ SourceLocation location =
+ new TokenSourceLocation(sourceFile, token, sourceElement.name);
checkValidSourceFileLocation(location, sourceFile, token.charOffset);
return location;
}
@@ -6454,12 +6453,13 @@
this.useMaxInliningNodes,
this.allowLoops);
- static bool canBeInlined(ast.FunctionExpression functionExpression,
+ static bool canBeInlined(FunctionElement function,
int maxInliningNodes,
bool useMaxInliningNodes,
{bool allowLoops: false}) {
InlineWeeder weeder =
new InlineWeeder(maxInliningNodes, useMaxInliningNodes, allowLoops);
+ ast.FunctionExpression functionExpression = function.node;
weeder.visit(functionExpression.initializers);
weeder.visit(functionExpression.body);
weeder.visit(functionExpression.asyncModifier);
diff --git a/pkg/compiler/lib/src/ssa/invoke_dynamic_specializers.dart b/pkg/compiler/lib/src/ssa/invoke_dynamic_specializers.dart
index 5511118..c5cdc94 100644
--- a/pkg/compiler/lib/src/ssa/invoke_dynamic_specializers.dart
+++ b/pkg/compiler/lib/src/ssa/invoke_dynamic_specializers.dart
@@ -564,7 +564,8 @@
HInstruction left = instruction.inputs[1];
HInstruction right = instruction.inputs[2];
JavaScriptBackend backend = compiler.backend;
- if (left.isUInt31(compiler) || right.isUInt31(compiler)) {
+ if (left.isPrimitiveOrNull(compiler) &&
+ (left.isUInt31(compiler) || right.isUInt31(compiler))) {
return backend.uint31Type;
}
return super.computeTypeFromInputTypes(instruction, compiler);
diff --git a/pkg/compiler/lib/src/tree_ir/optimization/statement_rewriter.dart b/pkg/compiler/lib/src/tree_ir/optimization/statement_rewriter.dart
index 3bb2206..768ecae 100644
--- a/pkg/compiler/lib/src/tree_ir/optimization/statement_rewriter.dart
+++ b/pkg/compiler/lib/src/tree_ir/optimization/statement_rewriter.dart
@@ -96,10 +96,21 @@
// available enclosing binding.
List<Assign> environment;
+ /// Binding environment for variables that are assigned to effectively
+ /// constant expressions (see [isEffectivelyConstant]).
+ final Map<Variable, Expression> constantEnvironment;
+
/// Substitution map for labels. Any break to a label L should be substituted
/// for a break to L' if L maps to L'.
Map<Label, Jump> labelRedirects = <Label, Jump>{};
+ /// Rewriter for methods.
+ StatementRewriter() : constantEnvironment = <Variable, Expression>{};
+
+ /// Rewriter for nested functions.
+ StatementRewriter.nested(StatementRewriter parent)
+ : constantEnvironment = parent.constantEnvironment;
+
/// Returns the redirect target of [label] or [label] itself if it should not
/// be redirected.
Jump redirect(Jump jump) {
@@ -107,9 +118,10 @@
return newJump != null ? newJump : jump;
}
-
rewriteExecutableDefinition(ExecutableDefinition definition) {
- definition.body = rewriteInEmptyEnvironment(definition.body);
+ inEmptyEnvironment(() {
+ definition.body = visitStatement(definition.body);
+ });
}
void rewriteConstructorDefinition(ConstructorDefinition definition) {
@@ -118,34 +130,38 @@
rewriteExecutableDefinition(definition);
}
- Statement rewriteInEmptyEnvironment(Statement body) {
+ void inEmptyEnvironment(void action()) {
List<Assign> oldEnvironment = environment;
environment = <Assign>[];
-
- Statement result = visitStatement(body);
- // TODO(kmillikin): Allow definitions that are not propagated. Here,
- // this means rebuilding the binding with a recursively unnamed definition,
- // or else introducing a variable definition and an assignment.
+ action();
assert(environment.isEmpty);
environment = oldEnvironment;
- return result;
}
Expression visitFieldInitializer(FieldInitializer node) {
- node.body = rewriteInEmptyEnvironment(node.body);
+ inEmptyEnvironment(() {
+ node.body = visitStatement(node.body);
+ });
return node;
}
Expression visitSuperInitializer(SuperInitializer node) {
- for (int i = node.arguments.length - 1; i >= 0; --i) {
- node.arguments[i] = rewriteInEmptyEnvironment(node.arguments[i]);
- }
+ inEmptyEnvironment(() {
+ for (int i = node.arguments.length - 1; i >= 0; --i) {
+ node.arguments[i] = visitStatement(node.arguments[i]);
+ assert(environment.isEmpty);
+ }
+ });
return node;
}
Expression visitExpression(Expression e) => e.processed ? e : e.accept(this);
Expression visitVariable(Variable node) {
+ // Propagate constant to use site.
+ Expression constant = constantEnvironment[node];
+ if (constant != null) return constant;
+
// Propagate a variable's definition to its use site if:
// 1. It has a single use, to avoid code growth and potential duplication
// of side effects, AND
@@ -160,20 +176,51 @@
return node;
}
+ /// Returns true if [exp] has no side effects and has a constant value within
+ /// any given activation of the enclosing method.
+ bool isEffectivelyConstant(Expression exp) {
+ // TODO(asgerf): Can be made more aggressive e.g. by checking conditional
+ // expressions recursively. Determine if that is a valuable optimization
+ // and/or if it is better handled at the CPS level.
+ return exp is Constant ||
+ exp is This ||
+ exp is ReifyTypeVar ||
+ exp is Variable && constantEnvironment.containsKey(exp);
+ }
Statement visitAssign(Assign node) {
- environment.add(node);
- Statement next = visitStatement(node.next);
-
- if (!environment.isEmpty && environment.last == node) {
- // The definition could not be propagated. Residualize the let binding.
- node.next = next;
- environment.removeLast();
- node.definition = visitExpression(node.definition);
- return node;
+ if (isEffectivelyConstant(node.definition) &&
+ node.variable.writeCount == 1) {
+ // Handle constant assignments specially.
+ // They are always safe to propagate (though we should avoid duplication).
+ // Moreover, they should not prevent other expressions from propagating.
+ if (node.variable.readCount <= 1) {
+ // A single-use constant should always be propagted to its use site.
+ constantEnvironment[node.variable] = visitExpression(node.definition);
+ return visitStatement(node.next);
+ } else {
+ // With more than one use, we cannot propagate the constant.
+ // Visit the following statement without polluting [environment] so
+ // that any preceding non-constant assignments might still propagate.
+ node.next = visitStatement(node.next);
+ node.definition = visitExpression(node.definition);
+ return node;
+ }
+ } else {
+ // Try to propagate assignment, and block previous assignment until this
+ // has propagated.
+ environment.add(node);
+ Statement next = visitStatement(node.next);
+ if (!environment.isEmpty && environment.last == node) {
+ // The definition could not be propagated. Residualize the let binding.
+ node.next = next;
+ environment.removeLast();
+ node.definition = visitExpression(node.definition);
+ return node;
+ }
+ assert(!environment.contains(node));
+ return next;
}
- assert(!environment.contains(node));
- return next;
}
Expression visitInvokeStatic(InvokeStatic node) {
@@ -217,13 +264,10 @@
Expression visitConditional(Conditional node) {
node.condition = visitExpression(node.condition);
- List<Assign> savedEnvironment = environment;
- environment = <Assign>[];
- node.thenExpression = visitExpression(node.thenExpression);
- assert(environment.isEmpty);
- node.elseExpression = visitExpression(node.elseExpression);
- assert(environment.isEmpty);
- environment = savedEnvironment;
+ inEmptyEnvironment(() {
+ node.thenExpression = visitExpression(node.thenExpression);
+ node.elseExpression = visitExpression(node.elseExpression);
+ });
return node;
}
@@ -231,9 +275,10 @@
Expression visitLogicalOperator(LogicalOperator node) {
node.left = visitExpression(node.left);
- environment.add(null); // impure expressions may not propagate across branch
- node.right = visitExpression(node.right);
- environment.removeLast();
+ // Impure expressions may not propagate across the branch.
+ inEmptyEnvironment(() {
+ node.right = visitExpression(node.right);
+ });
return node;
}
@@ -244,12 +289,12 @@
}
Expression visitFunctionExpression(FunctionExpression node) {
- new StatementRewriter().rewrite(node.definition);
+ new StatementRewriter.nested(this).rewrite(node.definition);
return node;
}
Statement visitFunctionDeclaration(FunctionDeclaration node) {
- new StatementRewriter().rewrite(node.definition);
+ new StatementRewriter.nested(this).rewrite(node.definition);
node.next = visitStatement(node.next);
return node;
}
@@ -301,10 +346,9 @@
// Do not propagate assignments into the successor statements, since they
// may be overwritten by assignments in the body.
- List<Assign> savedEnvironment = environment;
- environment = <Assign>[];
- node.next = visitStatement(node.next);
- environment = savedEnvironment;
+ inEmptyEnvironment(() {
+ node.next = visitStatement(node.next);
+ });
return node;
}
@@ -314,16 +358,13 @@
// Do not propagate assignments into branches. Doing so will lead to code
// duplication.
- // TODO(kmillikin): Rethink this. Propagating some assignments (e.g.,
- // constants or variables) is benign. If they can occur here, they should
+ // TODO(kmillikin): Rethink this. Propagating some assignments
+ // (e.g. variables) is benign. If they can occur here, they should
// be handled well.
- List<Assign> savedEnvironment = environment;
- environment = <Assign>[];
- node.thenStatement = visitStatement(node.thenStatement);
- assert(environment.isEmpty);
- node.elseStatement = visitStatement(node.elseStatement);
- assert(environment.isEmpty);
- environment = savedEnvironment;
+ inEmptyEnvironment(() {
+ node.thenStatement = visitStatement(node.thenStatement);
+ node.elseStatement = visitStatement(node.elseStatement);
+ });
tryCollapseIf(node);
@@ -345,11 +386,9 @@
Statement visitWhileTrue(WhileTrue node) {
// Do not propagate assignments into loops. Doing so is not safe for
// variables modified in the loop (the initial value will be propagated).
- List<Assign> savedEnvironment = environment;
- environment = <Assign>[];
- node.body = visitStatement(node.body);
- assert(environment.isEmpty);
- environment = savedEnvironment;
+ inEmptyEnvironment(() {
+ node.body = visitStatement(node.body);
+ });
return node;
}
@@ -396,15 +435,13 @@
node.expression = visitExpression(node.expression);
// Do not allow propagation of assignments past an expression evaluated
// for its side effects because it risks reordering side effects.
- // TODO(kmillikin): Rethink this. Some propagation is benign, e.g.,
- // constants, variables, or other pure values that are not destroyed by
+ // TODO(kmillikin): Rethink this. Some propagation is benign,
+ // e.g. variables, or other pure values that are not destroyed by
// the expression statement. If they can occur here they should be
// handled well.
- List<Assign> savedEnvironment = environment;
- environment = <Assign>[];
- node.next = visitStatement(node.next);
- assert(environment.isEmpty);
- environment = savedEnvironment;
+ inEmptyEnvironment(() {
+ node.next = visitStatement(node.next);
+ });
return node;
}
@@ -577,11 +614,9 @@
--innerElse.target.useCount;
// Try to inline the remaining break. Do not propagate assignments.
- List<Assign> savedEnvironment = environment;
- environment = <Assign>[];
- outerIf.elseStatement = visitStatement(outerElse);
- assert(environment.isEmpty);
- environment = savedEnvironment;
+ inEmptyEnvironment(() {
+ outerIf.elseStatement = visitStatement(outerElse);
+ });
return outerIf.elseStatement is If && innerThen is Break;
}
diff --git a/pkg/compiler/lib/src/tree_ir/tree_ir_builder.dart b/pkg/compiler/lib/src/tree_ir/tree_ir_builder.dart
index 2f7e5fe..3181b59 100644
--- a/pkg/compiler/lib/src/tree_ir/tree_ir_builder.dart
+++ b/pkg/compiler/lib/src/tree_ir/tree_ir_builder.dart
@@ -87,7 +87,9 @@
if (reference.definition.host != currentElement) {
return parent.getMutableVariableReference(reference);
}
- return local2mutable[reference.definition];
+ Variable variable = local2mutable[reference.definition];
+ ++variable.readCount;
+ return variable;
}
/// Obtains the variable representing the given primitive. Returns null for
diff --git a/pkg/compiler/lib/src/tree_ir/tree_ir_nodes.dart b/pkg/compiler/lib/src/tree_ir/tree_ir_nodes.dart
index 038ecf1..4312130 100644
--- a/pkg/compiler/lib/src/tree_ir/tree_ir_nodes.dart
+++ b/pkg/compiler/lib/src/tree_ir/tree_ir_nodes.dart
@@ -330,7 +330,7 @@
accept1(ExpressionVisitor1 visitor, arg) => visitor.visitNot(this, arg);
}
-class FunctionExpression extends Expression {
+class FunctionExpression extends Expression implements DartSpecificNode {
final FunctionDefinition definition;
FunctionExpression(this.definition) {
@@ -348,7 +348,7 @@
/// being recursive or having a return type.
/// The [variable] must not occur as the left-hand side of an [Assign] or
/// any other [FunctionDeclaration].
-class FunctionDeclaration extends Statement {
+class FunctionDeclaration extends Statement implements DartSpecificNode {
Variable variable;
final FunctionDefinition definition;
Statement next;
@@ -612,7 +612,7 @@
applyPass(Pass pass) => pass.rewriteFunctionDefinition(this);
}
-abstract class Initializer implements Expression {}
+abstract class Initializer implements Expression, DartSpecificNode {}
class FieldInitializer extends Initializer {
final FieldElement element;
@@ -657,6 +657,8 @@
abstract class JsSpecificNode implements Node {}
+abstract class DartSpecificNode implements Node {}
+
class CreateBox extends Expression implements JsSpecificNode {
accept(ExpressionVisitor visitor) => visitor.visitCreateBox(this);
accept1(ExpressionVisitor1 visitor, arg) => visitor.visitCreateBox(this, arg);
diff --git a/pkg/compiler/lib/src/tree_ir/tree_ir_tracer.dart b/pkg/compiler/lib/src/tree_ir/tree_ir_tracer.dart
index 38d9c6f..9828c94 100644
--- a/pkg/compiler/lib/src/tree_ir/tree_ir_tracer.dart
+++ b/pkg/compiler/lib/src/tree_ir/tree_ir_tracer.dart
@@ -238,7 +238,8 @@
visitAssign(Assign node) {
String name = names.varName(node.variable);
String rhs = expr(node.definition);
- String extra = node.hasExactlyOneUse ? "[single-use]" : "";
+ Variable v = node.variable;
+ String extra = "(r=${v.readCount}, w=${v.writeCount})";
printStatement(null, "assign $name = $rhs $extra");
}
diff --git a/pkg/compiler/lib/src/typechecker.dart b/pkg/compiler/lib/src/typechecker.dart
index 6bec813..321be25 100644
--- a/pkg/compiler/lib/src/typechecker.dart
+++ b/pkg/compiler/lib/src/typechecker.dart
@@ -47,6 +47,8 @@
abstract class ElementAccess {
Element get element;
+ String get name => element.name;
+
DartType computeType(Compiler compiler);
/// Returns [: true :] if the element can be access as an invocation.
@@ -82,6 +84,8 @@
Element get element => null;
+ String get name => 'dynamic';
+
DartType computeType(Compiler compiler) => const DynamicType();
bool isCallable(Compiler compiler) => true;
@@ -95,6 +99,8 @@
Element get element => null;
+ String get name => 'assert';
+
DartType computeType(Compiler compiler) {
return new FunctionType.synthesized(
const VoidType(),
@@ -181,6 +187,8 @@
Element get element => type.element;
+ String get name => type.name;
+
DartType computeType(Compiler compiler) => compiler.typeClass.rawType;
String toString() => 'TypeLiteralAccess($type)';
@@ -194,6 +202,8 @@
const FunctionCallAccess(this.element, this.type);
+ String get name => 'call';
+
DartType computeType(Compiler compiler) => type;
bool isCallable(Compiler compiler) => true;
@@ -931,7 +941,7 @@
analyzeArguments(node, elementAccess.element, type, argumentTypes);
} else {
reportTypeWarning(node, MessageKind.NOT_CALLABLE,
- {'elementName': elementAccess.element.name});
+ {'elementName': elementAccess.name});
analyzeArguments(node, elementAccess.element, const DynamicType(),
argumentTypes);
}
diff --git a/pkg/compiler/lib/src/use_unused_api.dart b/pkg/compiler/lib/src/use_unused_api.dart
index 77f0bc9..0ba3b3d 100644
--- a/pkg/compiler/lib/src/use_unused_api.dart
+++ b/pkg/compiler/lib/src/use_unused_api.dart
@@ -180,9 +180,6 @@
useJsBackend(js_backend.JavaScriptBackend backend) {
backend.assembleCode(null);
- backend.annotations.noInlining(null);
- backend.annotations.trustTypeAnnotations(null);
- backend.annotations.assumeDynamic(null);
}
useConcreteTypesInferrer(concrete_types_inferrer.ConcreteTypesInferrer c) {
diff --git a/pkg/compiler/lib/src/warnings.dart b/pkg/compiler/lib/src/warnings.dart
index 75334ea..6a78b8a 100644
--- a/pkg/compiler/lib/src/warnings.dart
+++ b/pkg/compiler/lib/src/warnings.dart
@@ -1271,6 +1271,11 @@
static const MessageKind MISSING_FACTORY_KEYWORD = const MessageKind(
"Did you forget a factory keyword here?");
+ static const MessageKind NO_SUCH_METHOD_IN_NATIVE =
+ const MessageKind(
+ "'NoSuchMethod' is not supported for classes that extend native "
+ "classes.");
+
static const MessageKind DEFERRED_LIBRARY_DART_2_DART =
const MessageKind(
"Deferred loading is not supported by the dart backend yet."
diff --git a/pkg/compiler/samples/darttags/darttags.dart b/pkg/compiler/samples/darttags/darttags.dart
index 3a29821..d675463 100644
--- a/pkg/compiler/samples/darttags/darttags.dart
+++ b/pkg/compiler/samples/darttags/darttags.dart
@@ -122,7 +122,7 @@
// felt it would make sense to keep the names.
Uri uri = compilationUnit.uri;
var buffer = new StringBuffer();
- SourceFile file = handler.provider.sourceFiles['$uri'];
+ SourceFile file = handler.provider.sourceFiles[uri];
String src_file = relativize(outputUri, uri, false);
compilationUnit.declarations.forEach((_, DeclarationMirror mirror) {
diff --git a/pkg/compiler/samples/jsonify/jsonify.dart b/pkg/compiler/samples/jsonify/jsonify.dart
index f09ad7f..54a6e18 100644
--- a/pkg/compiler/samples/jsonify/jsonify.dart
+++ b/pkg/compiler/samples/jsonify/jsonify.dart
@@ -70,7 +70,7 @@
BackDoor.compilationUnitsOf(library).forEach((compilationUnit) {
Uri uri = compilationUnit.uri;
String filename = relativize(sdkRoot, uri, false);
- SourceFile file = handler.provider.sourceFiles['$uri'];
+ SourceFile file = handler.provider.sourceFiles[uri];
map['sdk:/$filename'] = file.slowText();
});
});
@@ -80,7 +80,7 @@
if (patch != null) {
Uri uri = sdkRoot.resolve('sdk/lib/$patch');
String filename = relativize(sdkRoot, uri, false);
- SourceFile file = handler.provider.sourceFiles['$uri'];
+ SourceFile file = handler.provider.sourceFiles[uri];
map['sdk:/$filename'] = file.slowText();
}
});
diff --git a/pkg/dart2js_incremental/lib/library_updater.dart b/pkg/dart2js_incremental/lib/library_updater.dart
index bc269e2..003740c 100644
--- a/pkg/dart2js_incremental/lib/library_updater.dart
+++ b/pkg/dart2js_incremental/lib/library_updater.dart
@@ -290,10 +290,11 @@
}
return _readUri(before.resourceUri).then((bytes) {
+ Uri uri = before.file.uri;
String filename = before.file.filename;
SourceFile sourceFile = bytes is String
- ? new StringSourceFile(filename, bytes)
- : new CachingUtf8BytesSourceFile(filename, bytes);
+ ? new StringSourceFile(uri, filename, bytes)
+ : new CachingUtf8BytesSourceFile(uri, filename, bytes);
return before.copyWithFile(sourceFile);
});
}
diff --git a/pkg/docgen/lib/src/models/library.dart b/pkg/docgen/lib/src/models/library.dart
index ccd12a2..9403239 100644
--- a/pkg/docgen/lib/src/models/library.dart
+++ b/pkg/docgen/lib/src/models/library.dart
@@ -53,7 +53,7 @@
}
Library._(LibraryMirror libraryMirror) : super(libraryMirror) {
- var exported = calcExportedItems(libraryMirror);
+ var exported = calcExportedItems(libraryMirror, {});
var exportedClasses = addAll(exported['classes'],
dart2js_util.typesOf(libraryMirror.declarations));
updateLibraryPackage(mirror);
diff --git a/pkg/docgen/lib/src/models/model_helpers.dart b/pkg/docgen/lib/src/models/model_helpers.dart
index 3c4c430..f962e75 100644
--- a/pkg/docgen/lib/src/models/model_helpers.dart
+++ b/pkg/docgen/lib/src/models/model_helpers.dart
@@ -217,8 +217,9 @@
/// values of which point to a map of exported name identifiers with values
/// corresponding to the actual DeclarationMirror.
Map<String, Map<String, DeclarationMirror>> calcExportedItems(
- LibrarySourceMirror library) {
+ LibrarySourceMirror library, Map visited) {
var exports = {};
+ visited[library] = exports;
exports['classes'] = new SplayTreeMap();
exports['methods'] = new SplayTreeMap();
exports['variables'] = new SplayTreeMap();
@@ -226,7 +227,8 @@
// Determine the classes, variables and methods that are exported for a
// specific dependency.
void _populateExports(LibraryDependencyMirror export, bool showExport) {
- var transitiveExports = calcExportedItems(export.targetLibrary);
+ if (visited[export.targetLibrary] != null) return;
+ var transitiveExports = calcExportedItems(export.targetLibrary, visited);
exports['classes'].addAll(transitiveExports['classes']);
exports['methods'].addAll(transitiveExports['methods']);
exports['variables'].addAll(transitiveExports['variables']);
diff --git a/pkg/expect/lib/expect.dart b/pkg/expect/lib/expect.dart
index 2ca6ed3..82e604a 100644
--- a/pkg/expect/lib/expect.dart
+++ b/pkg/expect/lib/expect.dart
@@ -399,8 +399,8 @@
/// Annotation class for testing of dart2js. Use this as metadata on method
/// declarations to disable inlining of the annotated method.
-class NoInlining {
- const NoInlining();
+class NoInline {
+ const NoInline();
}
/// Annotation class for testing of dart2js. Use this as metadata on method
diff --git a/pkg/fixnum/lib/src/int64.dart b/pkg/fixnum/lib/src/int64.dart
index 603065c..9ccf059 100644
--- a/pkg/fixnum/lib/src/int64.dart
+++ b/pkg/fixnum/lib/src/int64.dart
@@ -99,7 +99,7 @@
d1 = d1 * radix + carry;
carry = d1 >> _BITS;
- d1 = _MASK & d1;;
+ d1 = _MASK & d1;
d2 = d2 * radix + carry;
d2 = _MASK2 & d2;
@@ -202,9 +202,9 @@
factory Int64.fromInts(int top, int bottom) {
top &= 0xffffffff;
bottom &= 0xffffffff;
- int d0 = bottom & _MASK;
- int d1 = ((top & 0xfff) << 10) | ((bottom >> _BITS) & 0x3ff);
- int d2 = (top >> 12) & _MASK2;
+ int d0 = _MASK & bottom;
+ int d1 = ((0xfff & top) << 10) | (0x3ff & (bottom >> _BITS));
+ int d2 = _MASK2 & (top >> 12);
return new Int64._bits(d0, d1, d2);
}
@@ -312,12 +312,9 @@
// Propagate high bits from c0 -> c1, c1 -> c2.
c1 += c0 >> _BITS;
- c0 &= _MASK;
c2 += c1 >> _BITS;
- c1 &= _MASK;
- c2 &= _MASK2;
- return new Int64._bits(c0, c1, c2);
+ return Int64._masked(c0, c1, c2);
}
Int64 operator %(other) => _divide(this, other, _RETURN_MOD);
@@ -347,7 +344,7 @@
int a0 = _l ^ o._l;
int a1 = _m ^ o._m;
int a2 = _h ^ o._h;
- return new Int64._bits(a0, a1, a2);
+ return Int64._masked(a0, a1, a2);
}
Int64 operator ~() {
@@ -1028,7 +1025,7 @@
}
if (!aNeg) {
- return new Int64._bits(_MASK & r0, r1, r2); // Masking for type inferrer.
+ return Int64._masked(r0, r1, r2); // Masking for type inferrer.
}
if (what == _RETURN_MOD) {
diff --git a/pkg/fixnum/pubspec.yaml b/pkg/fixnum/pubspec.yaml
index ac9418e..4b0662f 100644
--- a/pkg/fixnum/pubspec.yaml
+++ b/pkg/fixnum/pubspec.yaml
@@ -1,5 +1,5 @@
name: fixnum
-version: 0.10.0
+version: 0.10.1
author: Dart Team <misc@dartlang.org>
description: Library for 32- and 64-bit fixed size integers.
homepage: http://www.dartlang.org
diff --git a/pkg/js_ast/LICENSE b/pkg/js_ast/LICENSE
new file mode 100644
index 0000000..de31e1a
--- /dev/null
+++ b/pkg/js_ast/LICENSE
@@ -0,0 +1,26 @@
+Copyright 2015, the Dart project authors. All rights reserved.
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pkg/js_ast/README.md b/pkg/js_ast/README.md
new file mode 100644
index 0000000..1ce3be8
--- /dev/null
+++ b/pkg/js_ast/README.md
@@ -0,0 +1,4 @@
+js_ast
+======
+
+A library for creating JavaScript ASTs from templates.
diff --git a/pkg/js_ast/lib/js_ast.dart b/pkg/js_ast/lib/js_ast.dart
new file mode 100644
index 0000000..27773b5
--- /dev/null
+++ b/pkg/js_ast/lib/js_ast.dart
@@ -0,0 +1,13 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library js_ast;
+
+import 'src/precedence.dart';
+import 'src/characters.dart' as charCodes;
+
+part 'src/nodes.dart';
+part 'src/builder.dart';
+part 'src/printer.dart';
+part 'src/template.dart';
diff --git a/pkg/js_ast/lib/src/builder.dart b/pkg/js_ast/lib/src/builder.dart
new file mode 100644
index 0000000..5d8da87
--- /dev/null
+++ b/pkg/js_ast/lib/src/builder.dart
@@ -0,0 +1,1338 @@
+// Copyright (c) 2013, 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.
+
+// Utilities for building JS ASTs at runtime. Contains a builder class
+// and a parser that parses part of the language.
+
+part of js_ast;
+
+
+/**
+ * Global template manager. We should aim to have a fixed number of
+ * templates. This implies that we do not use js('xxx') to parse text that is
+ * constructed from values that depend on names in the Dart program.
+ *
+ * TODO(sra): Find the remaining places where js('xxx') used to parse an
+ * unbounded number of expression, or institute a cache policy.
+ */
+TemplateManager templateManager = new TemplateManager();
+
+
+/**
+
+[js] is a singleton instace of JsBuilder. JsBuilder is a set of conveniences
+for constructing JavaScript ASTs.
+
+[string] and [number] are used to create leaf AST nodes:
+
+ var s = js.string('hello'); // s = new LiteralString('"hello"')
+ var n = js.number(123); // n = new LiteralNumber(123)
+
+In the line above `a --> b` means Dart expression `a` evaluates to a JavaScript
+AST that would pretty-print as `b`.
+
+The [call] method constructs an Expression AST.
+
+No argument
+
+ js('window.alert("hello")') --> window.alert("hello")
+
+The input text can contain placeholders `#` that are replaced with provided
+arguments. A single argument can be passed directly:
+
+ js('window.alert(#)', s) --> window.alert("hello")
+
+Multiple arguments are passed as a list:
+
+ js('# + #', [s, s]) --> "hello" + "hello"
+
+The [statement] method constructs a Statement AST, but is otherwise like the
+[call] method. This constructs a Return AST:
+
+ var ret = js.statement('return #;', n); --> return 123;
+
+A placeholder in a Statement context must be followed by a semicolon ';'. You
+can think of a statement placeholder as being `#;` to explain why the output
+still has one semicolon:
+
+ js.statement('if (happy) #;', ret)
+ -->
+ if (happy)
+ return 123;
+
+If the placeholder is not followed by a semicolon, it is part of an expression.
+Here the paceholder is in the position of the function in a function call:
+
+ var vFoo = new VariableUse('foo');
+ js.statement('if (happy) #("Happy!")', vFoo)
+ -->
+ if (happy)
+ foo("Happy!");
+
+Generally, a placeholder in an expression position requires an Expression AST as
+an argument and a placeholder in a statement position requires a Statement AST.
+An expression will be converted to a Statement if needed by creating an
+ExpessionStatement. A String argument will be converted into a VariableUse and
+requires that the string is a JavaScript identifier.
+
+ js('# + 1', vFoo) --> foo + 1
+ js('# + 1', 'foo') --> foo + 1
+ js('# + 1', 'foo.bar') --> assertion failure
+
+Some placeholder positions are _splicing contexts_. A function argument list is
+a splicing expression context. A placeholder in a splicing expression context
+can take a single Expression (or String, converted to VariableUse) or an
+Iterable of Expressions (and/or Strings).
+
+ // non-splicing argument:
+ js('#(#)', ['say', s]) --> say("hello")
+ // splicing arguments:
+ js('#(#)', ['say', []]) --> say()
+ js('#(#)', ['say', [s]]) --> say("hello")
+ js('#(#)', ['say', [s, n]]) --> say("hello", 123)
+
+A splicing context can be used to append 'lists' and add extra elements:
+
+ js('foo(#, #, 1)', [ ['a', n], s]) --> foo(a, 123, "hello", 1)
+ js('foo(#, #, 1)', [ ['a', n], [s, n]]) --> foo(a, 123, "hello", 123, 1)
+ js('foo(#, #, 1)', [ [], [s, n]]) --> foo("hello", 123, 1)
+ js('foo(#, #, 1)', [ [], [] ]) --> foo(1)
+
+The generation of a compile-time optional argument expression can be chosen by
+providing an empty or singleton list.
+
+In addition to Expressions and Statements, there are Parameters, which occur
+only in the parameter list of a function expression or declaration.
+Placeholders in parameter positions behave like placeholders in Expression
+positions, except only Parameter AST nodes are permitted. String arguments for
+parameter placeholders are converted to Parameter AST nodes.
+
+ var pFoo = new Parameter('foo')
+ js('function(#) { return #; }', [pFoo, vFoo])
+ -->
+ function(foo) { return foo; }
+
+Expressions and Parameters are not compatible with each other's context:
+
+ js('function(#) { return #; }', [vFoo, vFoo]) --> error
+ js('function(#) { return #; }', [pFoo, pFoo]) --> error
+
+The parameter context is a splicing context. When combined with the
+context-sensitive conversion of Strings, this simplifies the construction of
+trampoline-like functions:
+
+ var args = ['a', 'b'];
+ js('function(#) { return f(this, #); }', [args, args])
+ -->
+ function(a, b) { return f(this, a, b); }
+
+A statement placeholder in a Block is also in a splicing context. In addition
+to splicing Iterables, statement placeholders in a Block will also splice a
+Block or an EmptyStatement. This flattens nested blocks and allows blocks to be
+appended.
+
+ var b1 = js.statement('{ 1; 2; }');
+ var sEmpty = new Emptystatement();
+ js.statement('{ #; #; #; #; }', [sEmpty, b1, b1, sEmpty])
+ -->
+ { 1; 2; 1; 2; }
+
+A placeholder in the context of an if-statement condition also accepts a Dart
+bool argument, which selects the then-part or else-part of the if-statement:
+
+ js.statement('if (#) return;', vFoo) --> if (foo) return;
+ js.statement('if (#) return;', true) --> return;
+ js.statement('if (#) return;', false) --> ; // empty statement
+ var eTrue = new LiteralBool(true);
+ js.statement('if (#) return;', eTrue) --> if (true) return;
+
+Combined with block splicing, if-statement condition context placeholders allows
+the creation of tenplates that select code depending on variables.
+
+ js.statement('{ 1; if (#) 2; else { 3; 4; } 5;}', true)
+ --> { 1; 2; 5; }
+
+ js.statement('{ 1; if (#) 2; else { 3; 4; } 5;}', false)
+ --> { 1; 3; 4; 5; }
+
+A placeholder following a period in a property access is in a property access
+context. This is just like an expression context, except String arguments are
+converted to JavaScript property accesses. In JavaScript, `a.b` is short-hand
+for `a["b"]`:
+
+ js('a[#]', vFoo) --> a[foo]
+ js('a[#]', s) --> a.hello (i.e. a["hello"]).
+ js('a[#]', 'x') --> a[x]
+
+ js('a.#', vFoo) --> a[foo]
+ js('a.#', s) --> a.hello (i.e. a["hello"])
+ js('a.#', 'x') --> a.x (i.e. a["x"])
+
+(Question - should `.#` be restricted to permit only String arguments? The
+template should probably be writted with `[]` if non-strings are accepted.)
+
+
+Object initialiers allow placeholders in the key property name position:
+
+ js('{#:1, #:2}', [s, 'bye']) --> {hello: 1, bye: 2}
+
+
+What is not implemented:
+
+ - Array initializers and object initializers could support splicing. In the
+ array case, we would need some way to know if an ArrayInitializer argument
+ should be splice or is intended as a single value.
+
+*/
+const JsBuilder js = const JsBuilder();
+
+
+class JsBuilder {
+ const JsBuilder();
+
+ /**
+ * Parses a bit of JavaScript, and returns an expression.
+ *
+ * See the MiniJsParser class.
+ *
+ * [arguments] can be a single [Node] (e.g. an [Expression] or [Statement]) or
+ * a list of [Node]s, which will be interpolated into the source at the '#'
+ * signs.
+ */
+ Expression call(String source, [var arguments]) {
+ Template template = _findExpressionTemplate(source);
+ if (arguments == null) return template.instantiate([]);
+ // We allow a single argument to be given directly.
+ if (arguments is! List && arguments is! Map) arguments = [arguments];
+ return template.instantiate(arguments);
+ }
+
+ /**
+ * Parses a JavaScript Statement, otherwise just like [call].
+ */
+ Statement statement(String source, [var arguments]) {
+ Template template = _findStatementTemplate(source);
+ if (arguments == null) return template.instantiate([]);
+ // We allow a single argument to be given directly.
+ if (arguments is! List && arguments is! Map) arguments = [arguments];
+ return template.instantiate(arguments);
+ }
+
+ /**
+ * Parses JavaScript written in the `JS` foreign instruction.
+ *
+ * The [source] must be a JavaScript expression or a JavaScript throw
+ * statement.
+ */
+ Template parseForeignJS(String source) {
+ // TODO(sra): Parse with extra validation to forbid `#` interpolation in
+ // functions, as this leads to unanticipated capture of temporaries that are
+ // reused after capture.
+ if (source.startsWith("throw ")) {
+ return _findStatementTemplate(source);
+ } else {
+ return _findExpressionTemplate(source);
+ }
+ }
+
+ Template _findExpressionTemplate(String source) {
+ Template template = templateManager.lookupExpressionTemplate(source);
+ if (template == null) {
+ MiniJsParser parser = new MiniJsParser(source);
+ Expression expression = parser.expression();
+ template = templateManager.defineExpressionTemplate(source, expression);
+ }
+ return template;
+ }
+
+ Template _findStatementTemplate(String source) {
+ Template template = templateManager.lookupStatementTemplate(source);
+ if (template == null) {
+ MiniJsParser parser = new MiniJsParser(source);
+ Statement statement = parser.statement();
+ template = templateManager.defineStatementTemplate(source, statement);
+ }
+ return template;
+ }
+
+ /**
+ * Creates an Expression template without caching the result.
+ */
+ Template uncachedExpressionTemplate(String source) {
+ MiniJsParser parser = new MiniJsParser(source);
+ Expression expression = parser.expression();
+ return new Template(
+ source, expression, isExpression: true, forceCopy: false);
+ }
+
+ /**
+ * Creates a Statement template without caching the result.
+ */
+ Template uncachedStatementTemplate(String source) {
+ MiniJsParser parser = new MiniJsParser(source);
+ Statement statement = parser.statement();
+ return new Template(
+ source, statement, isExpression: false, forceCopy: false);
+ }
+
+ /**
+ * Create an Expression template which has [ast] as the result. This is used
+ * to wrap a generated AST in a zero-argument Template so it can be passed to
+ * context that expects a template.
+ */
+ Template expressionTemplateYielding(Node ast) {
+ return new Template.withExpressionResult(ast);
+ }
+
+ Template statementTemplateYielding(Node ast) {
+ return new Template.withStatementResult(ast);
+ }
+
+ /// Creates a literal js string from [value].
+ LiteralString escapedString(String value) {
+ // Start by escaping the backslashes.
+ String escaped = value.replaceAll('\\', '\\\\');
+ // Do not escape unicode characters and ' because they are allowed in the
+ // string literal anyway.
+ escaped = escaped.replaceAllMapped(new RegExp('\n|"|\b|\t|\v'), (match) {
+ switch (match.group(0)) {
+ case "\n" : return r"\n";
+ case "\"" : return r'\"';
+ case "\b" : return r"\b";
+ case "\t" : return r"\t";
+ case "\f" : return r"\f";
+ case "\v" : return r"\v";
+ }
+ });
+ LiteralString result = string(escaped);
+ // We don't escape ' under the assumption that the string is wrapped
+ // into ". Verify that assumption.
+ assert(result.value.codeUnitAt(0) == '"'.codeUnitAt(0));
+ return result;
+ }
+
+ /// Creates a literal js string from [value].
+ ///
+ /// Note that this function only puts quotes around [value]. It does not do
+ /// any escaping, so use only when you can guarantee that [value] does not
+ /// contain newlines or backslashes. For escaping the string use
+ /// [escapedString].
+ LiteralString string(String value) => new LiteralString('"$value"');
+
+ LiteralNumber number(num value) => new LiteralNumber('$value');
+
+ LiteralBool boolean(bool value) => new LiteralBool(value);
+
+ ArrayInitializer numArray(Iterable<int> list) =>
+ new ArrayInitializer(list.map(number).toList());
+
+ ArrayInitializer stringArray(Iterable<String> list) =>
+ new ArrayInitializer(list.map(string).toList());
+
+ Comment comment(String text) => new Comment(text);
+
+ Call propertyCall(Expression receiver,
+ String fieldName,
+ List<Expression> arguments) {
+ return new Call(new PropertyAccess.field(receiver, fieldName), arguments);
+ }
+}
+
+LiteralString string(String value) => js.string(value);
+LiteralNumber number(num value) => js.number(value);
+ArrayInitializer numArray(Iterable<int> list) => js.numArray(list);
+ArrayInitializer stringArray(Iterable<String> list) => js.stringArray(list);
+Call propertyCall(Expression receiver,
+ String fieldName,
+ List<Expression> arguments) {
+ return js.propertyCall(receiver, fieldName, arguments);
+}
+
+class MiniJsParserError {
+ MiniJsParserError(this.parser, this.message) { }
+
+ final MiniJsParser parser;
+ final String message;
+
+ String toString() {
+ int pos = parser.lastPosition;
+
+ // Discard lines following the line containing lastPosition.
+ String src = parser.src;
+ int newlinePos = src.indexOf('\n', pos);
+ if (newlinePos >= pos) src = src.substring(0, newlinePos);
+
+ // Extract the prefix of the error line before lastPosition.
+ String line = src;
+ int lastLineStart = line.lastIndexOf('\n');
+ if (lastLineStart >= 0) line = line.substring(lastLineStart + 1);
+ String prefix = line.substring(0, pos - (src.length - line.length));
+
+ // Replace non-tabs with spaces, giving a print indent that matches the text
+ // for tabbing.
+ String spaces = prefix.replaceAll(new RegExp(r'[^\t]'), ' ');
+ return 'Error in MiniJsParser:\n${src}\n$spaces^\n$spaces$message\n';
+ }
+}
+
+/// Mini JavaScript parser for tiny snippets of code that we want to make into
+/// AST nodes. Handles:
+/// * identifiers.
+/// * dot access.
+/// * method calls.
+/// * [] access.
+/// * array, string, regexp, boolean, null and numeric literals.
+/// * most operators.
+/// * brackets.
+/// * var declarations.
+/// * operator precedence.
+/// * anonymous funtions and named function expressions and declarations.
+/// Notable things it can't do yet include:
+/// * some statements are still missing (do-while, while, switch).
+///
+/// It's a fairly standard recursive descent parser.
+///
+/// Literal strings are passed through to the final JS source code unchanged,
+/// including the choice of surrounding quotes, so if you parse
+/// r'var x = "foo\n\"bar\""' you will end up with
+/// var x = "foo\n\"bar\"" in the final program. \x and \u escapes are not
+/// allowed in string and regexp literals because the machinery for checking
+/// their correctness is rather involved.
+class MiniJsParser {
+ MiniJsParser(this.src)
+ : lastCategory = NONE,
+ lastToken = null,
+ lastPosition = 0,
+ position = 0 {
+ getToken();
+ }
+
+ int lastCategory = NONE;
+ String lastToken = null;
+ int lastPosition = 0;
+ int position = 0;
+ bool skippedNewline = false; // skipped newline in last getToken?
+ final String src;
+
+ final List<InterpolatedNode> interpolatedValues = <InterpolatedNode>[];
+ bool get hasNamedHoles =>
+ interpolatedValues.isNotEmpty && interpolatedValues.first.isNamed;
+ bool get hasPositionalHoles =>
+ interpolatedValues.isNotEmpty && interpolatedValues.first.isPositional;
+
+ static const NONE = -1;
+ static const ALPHA = 0;
+ static const NUMERIC = 1;
+ static const STRING = 2;
+ static const SYMBOL = 3;
+ static const ASSIGNMENT = 4;
+ static const DOT = 5;
+ static const LPAREN = 6;
+ static const RPAREN = 7;
+ static const LBRACE = 8;
+ static const RBRACE = 9;
+ static const LSQUARE = 10;
+ static const RSQUARE = 11;
+ static const COMMA = 12;
+ static const QUERY = 13;
+ static const COLON = 14;
+ static const SEMICOLON = 15;
+ static const HASH = 16;
+ static const WHITESPACE = 17;
+ static const OTHER = 18;
+
+ // Make sure that ]] is two symbols.
+ bool singleCharCategory(int category) => category >= DOT;
+
+ static String categoryToString(int cat) {
+ switch (cat) {
+ case NONE: return "NONE";
+ case ALPHA: return "ALPHA";
+ case NUMERIC: return "NUMERIC";
+ case SYMBOL: return "SYMBOL";
+ case ASSIGNMENT: return "ASSIGNMENT";
+ case DOT: return "DOT";
+ case LPAREN: return "LPAREN";
+ case RPAREN: return "RPAREN";
+ case LBRACE: return "LBRACE";
+ case RBRACE: return "RBRACE";
+ case LSQUARE: return "LSQUARE";
+ case RSQUARE: return "RSQUARE";
+ case STRING: return "STRING";
+ case COMMA: return "COMMA";
+ case QUERY: return "QUERY";
+ case COLON: return "COLON";
+ case SEMICOLON: return "SEMICOLON";
+ case HASH: return "HASH";
+ case WHITESPACE: return "WHITESPACE";
+ case OTHER: return "OTHER";
+ }
+ return "Unknown: $cat";
+ }
+
+ static const CATEGORIES = const <int>[
+ OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, // 0-7
+ OTHER, WHITESPACE, WHITESPACE, OTHER, OTHER, WHITESPACE, // 8-13
+ OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, // 14-21
+ OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, OTHER, // 22-29
+ OTHER, OTHER, WHITESPACE, // 30-32
+ SYMBOL, OTHER, HASH, ALPHA, SYMBOL, SYMBOL, OTHER, // !"#$%&´
+ LPAREN, RPAREN, SYMBOL, SYMBOL, COMMA, SYMBOL, DOT, SYMBOL, // ()*+,-./
+ NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, // 01234
+ NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, // 56789
+ COLON, SEMICOLON, SYMBOL, SYMBOL, SYMBOL, QUERY, OTHER, // :;<=>?@
+ ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // ABCDEFGH
+ ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // IJKLMNOP
+ ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // QRSTUVWX
+ ALPHA, ALPHA, LSQUARE, OTHER, RSQUARE, SYMBOL, ALPHA, OTHER, // YZ[\]^_'
+ ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // abcdefgh
+ ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // ijklmnop
+ ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, // qrstuvwx
+ ALPHA, ALPHA, LBRACE, SYMBOL, RBRACE, SYMBOL]; // yz{|}~
+
+ // This must be a >= the highest precedence number handled by parseBinary.
+ static var HIGHEST_PARSE_BINARY_PRECEDENCE = 16;
+ static bool isAssignment(String symbol) => BINARY_PRECEDENCE[symbol] == 17;
+
+ // From https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence
+ static final BINARY_PRECEDENCE = {
+ '+=': 17, '-=': 17, '*=': 17, '/=': 17, '%=': 17, '^=': 17, '|=': 17,
+ '&=': 17, '<<=': 17, '>>=': 17, '>>>=': 17, '=': 17,
+ '||': 14,
+ '&&': 13,
+ '|': 12,
+ '^': 11,
+ '&': 10,
+ '!=': 9, '==': 9, '!==': 9, '===': 9,
+ '<': 8, '<=': 8, '>=': 8, '>': 8, 'in': 8, 'instanceof': 8,
+ '<<': 7, '>>': 7, '>>>': 7,
+ '+': 6, '-': 6,
+ '*': 5, '/': 5, '%': 5
+ };
+ static final UNARY_OPERATORS =
+ ['++', '--', '+', '-', '~', '!', 'typeof', 'void', 'delete', 'await']
+ .toSet();
+
+ static final OPERATORS_THAT_LOOK_LIKE_IDENTIFIERS =
+ ['typeof', 'void', 'delete', 'in', 'instanceof', 'await'].toSet();
+
+ static int category(int code) {
+ if (code >= CATEGORIES.length) return OTHER;
+ return CATEGORIES[code];
+ }
+
+ String getDelimited(int startPosition) {
+ position = startPosition;
+ int delimiter = src.codeUnitAt(startPosition);
+ int currentCode;
+ do {
+ position++;
+ if (position >= src.length) error("Unterminated literal");
+ currentCode = src.codeUnitAt(position);
+ if (currentCode == charCodes.$LF) error("Unterminated literal");
+ if (currentCode == charCodes.$BACKSLASH) {
+ if (++position >= src.length) error("Unterminated literal");
+ int escaped = src.codeUnitAt(position);
+ if (escaped == charCodes.$x || escaped == charCodes.$X ||
+ escaped == charCodes.$u || escaped == charCodes.$U ||
+ category(escaped) == NUMERIC) {
+ error('Numeric and hex escapes are not allowed in literals');
+ }
+ }
+ } while (currentCode != delimiter);
+ position++;
+ return src.substring(lastPosition, position);
+ }
+
+ void getToken() {
+ skippedNewline = false;
+ for (;;) {
+ if (position >= src.length) break;
+ int code = src.codeUnitAt(position);
+ // Skip '//' and '/*' style comments.
+ if (code == charCodes.$SLASH &&
+ position + 1 < src.length) {
+ if (src.codeUnitAt(position + 1) == charCodes.$SLASH) {
+ int nextPosition = src.indexOf('\n', position);
+ if (nextPosition == -1) nextPosition = src.length;
+ position = nextPosition;
+ continue;
+ } else if (src.codeUnitAt(position + 1) == charCodes.$STAR) {
+ int nextPosition = src.indexOf('*/', position + 2);
+ if (nextPosition == -1) error('Unterminated comment');
+ position = nextPosition + 2;
+ continue;
+ }
+ }
+ if (category(code) != WHITESPACE) break;
+ if (code == charCodes.$LF) skippedNewline = true;
+ ++position;
+ }
+
+ if (position == src.length) {
+ lastCategory = NONE;
+ lastToken = null;
+ lastPosition = position;
+ return;
+ }
+ int code = src.codeUnitAt(position);
+ lastPosition = position;
+ if (code == charCodes.$SQ || code == charCodes.$DQ) {
+ // String literal.
+ lastCategory = STRING;
+ lastToken = getDelimited(position);
+ } else if (code == charCodes.$0 &&
+ position + 2 < src.length &&
+ src.codeUnitAt(position + 1) == charCodes.$x) {
+ // Hex literal.
+ for (position += 2; position < src.length; position++) {
+ int cat = category(src.codeUnitAt(position));
+ if (cat != NUMERIC && cat != ALPHA) break;
+ }
+ lastCategory = NUMERIC;
+ lastToken = src.substring(lastPosition, position);
+ int.parse(lastToken, onError: (_) {
+ error("Unparseable number");
+ });
+ } else if (code == charCodes.$SLASH) {
+ // Tokens that start with / are special due to regexp literals.
+ lastCategory = SYMBOL;
+ position++;
+ if (position < src.length && src.codeUnitAt(position) == charCodes.$EQ) {
+ position++;
+ }
+ lastToken = src.substring(lastPosition, position);
+ } else {
+ // All other tokens handled here.
+ int cat = category(src.codeUnitAt(position));
+ int newCat;
+ do {
+ position++;
+ if (position == src.length) break;
+ int code = src.codeUnitAt(position);
+ // Special code to disallow ! and / in non-first position in token, so
+ // that !! parses as two tokens and != parses as one, while =/ parses
+ // as a an equals token followed by a regexp literal start.
+ newCat = (code == charCodes.$BANG || code == charCodes.$SLASH)
+ ? NONE
+ : category(code);
+ } while (!singleCharCategory(cat) &&
+ (cat == newCat ||
+ (cat == ALPHA && newCat == NUMERIC) || // eg. level42.
+ (cat == NUMERIC && newCat == DOT))); // eg. 3.1415
+ lastCategory = cat;
+ lastToken = src.substring(lastPosition, position);
+ if (cat == NUMERIC) {
+ double.parse(lastToken, (_) {
+ error("Unparseable number");
+ });
+ } else if (cat == SYMBOL) {
+ int binaryPrecendence = BINARY_PRECEDENCE[lastToken];
+ if (binaryPrecendence == null && !UNARY_OPERATORS.contains(lastToken)) {
+ error("Unknown operator");
+ }
+ if (isAssignment(lastToken)) lastCategory = ASSIGNMENT;
+ } else if (cat == ALPHA) {
+ if (OPERATORS_THAT_LOOK_LIKE_IDENTIFIERS.contains(lastToken)) {
+ lastCategory = SYMBOL;
+ }
+ }
+ }
+ }
+
+ void expectCategory(int cat) {
+ if (cat != lastCategory) error("Expected ${categoryToString(cat)}");
+ getToken();
+ }
+
+ bool acceptCategory(int cat) {
+ if (cat == lastCategory) {
+ getToken();
+ return true;
+ }
+ return false;
+ }
+
+ void expectSemicolon() {
+ if (acceptSemicolon()) return;
+ error('Expected SEMICOLON');
+ }
+
+ bool acceptSemicolon() {
+ // Accept semicolon or automatically inserted semicolon before close brace.
+ // Miniparser forbids other kinds of semicolon insertion.
+ if (RBRACE == lastCategory) return true;
+ if (NONE == lastCategory) return true; // end of input
+ if (skippedNewline) {
+ error('No automatic semicolon insertion at preceding newline');
+ }
+ return acceptCategory(SEMICOLON);
+ }
+
+ bool acceptString(String string) {
+ if (lastToken == string) {
+ getToken();
+ return true;
+ }
+ return false;
+ }
+
+ void error(message) {
+ throw new MiniJsParserError(this, message);
+ }
+
+ /// Returns either the name for the hole, or its integer position.
+ parseHash() {
+ String holeName = lastToken;
+ if (acceptCategory(ALPHA)) {
+ // Named hole. Example: 'function #funName() { ... }'
+ if (hasPositionalHoles) {
+ error('Holes must all be positional or named. $holeName');
+ }
+ return holeName;
+ } else {
+ if (hasNamedHoles) {
+ error('Holes must all be positional or named. $holeName');
+ }
+ int position = interpolatedValues.length;
+ return position;
+ }
+ }
+
+ Expression parsePrimary() {
+ String last = lastToken;
+ if (acceptCategory(ALPHA)) {
+ if (last == "true") {
+ return new LiteralBool(true);
+ } else if (last == "false") {
+ return new LiteralBool(false);
+ } else if (last == "null") {
+ return new LiteralNull();
+ } else if (last == "function") {
+ return parseFunctionExpression();
+ } else if (last == "this") {
+ return new This();
+ } else {
+ return new VariableUse(last);
+ }
+ } else if (acceptCategory(LPAREN)) {
+ Expression expression = parseExpression();
+ expectCategory(RPAREN);
+ return expression;
+ } else if (acceptCategory(STRING)) {
+ return new LiteralString(last);
+ } else if (acceptCategory(NUMERIC)) {
+ return new LiteralNumber(last);
+ } else if (acceptCategory(LBRACE)) {
+ return parseObjectInitializer();
+ } else if (acceptCategory(LSQUARE)) {
+ var values = <Expression>[];
+
+ while (true) {
+ if (acceptCategory(COMMA)) {
+ values.add(new ArrayHole());
+ continue;
+ }
+ if (acceptCategory(RSQUARE)) break;
+ values.add(parseAssignment());
+ if (acceptCategory(RSQUARE)) break;
+ expectCategory(COMMA);
+ }
+ return new ArrayInitializer(values);
+ } else if (last != null && last.startsWith("/")) {
+ String regexp = getDelimited(lastPosition);
+ getToken();
+ String flags = lastToken;
+ if (!acceptCategory(ALPHA)) flags = "";
+ Expression expression = new RegExpLiteral(regexp + flags);
+ return expression;
+ } else if (acceptCategory(HASH)) {
+ var nameOrPosition = parseHash();
+ InterpolatedExpression expression =
+ new InterpolatedExpression(nameOrPosition);
+ interpolatedValues.add(expression);
+ return expression;
+ } else {
+ error("Expected primary expression");
+ return null;
+ }
+ }
+
+ Expression parseFunctionExpression() {
+ String last = lastToken;
+ if (lastCategory == ALPHA || lastCategory == HASH) {
+ Declaration name = parseVariableDeclaration();
+ return new NamedFunction(name, parseFun());
+ }
+ return parseFun();
+ }
+
+ Expression parseFun() {
+ List<Parameter> params = <Parameter>[];
+
+ expectCategory(LPAREN);
+ if (!acceptCategory(RPAREN)) {
+ for (;;) {
+ if (acceptCategory(HASH)) {
+ var nameOrPosition = parseHash();
+ InterpolatedParameter parameter =
+ new InterpolatedParameter(nameOrPosition);
+ interpolatedValues.add(parameter);
+ params.add(parameter);
+ } else {
+ String argumentName = lastToken;
+ expectCategory(ALPHA);
+ params.add(new Parameter(argumentName));
+ }
+ if (acceptCategory(COMMA)) continue;
+ expectCategory(RPAREN);
+ break;
+ }
+ }
+ AsyncModifier asyncModifier;
+ if (acceptString('async')) {
+ if (acceptString('*')) {
+ asyncModifier = const AsyncModifier.asyncStar();
+ } else {
+ asyncModifier = const AsyncModifier.async();
+ }
+ } else if (acceptString('sync')) {
+ if (!acceptString('*')) error("Only sync* is valid - sync is implied");
+ asyncModifier = const AsyncModifier.syncStar();
+ } else {
+ asyncModifier = const AsyncModifier.sync();
+ }
+ expectCategory(LBRACE);
+ Block block = parseBlock();
+ return new Fun(params, block, asyncModifier: asyncModifier);
+ }
+
+ Expression parseObjectInitializer() {
+ List<Property> properties = <Property>[];
+ for (;;) {
+ if (acceptCategory(RBRACE)) break;
+ // Limited subset: keys are identifiers, no 'get' or 'set' properties.
+ Literal propertyName;
+ String identifier = lastToken;
+ if (acceptCategory(ALPHA)) {
+ propertyName = new LiteralString('"$identifier"');
+ } else if (acceptCategory(STRING)) {
+ propertyName = new LiteralString(identifier);
+ } else if (acceptCategory(SYMBOL)) { // e.g. void
+ propertyName = new LiteralString('"$identifier"');
+ } else if (acceptCategory(HASH)) {
+ var nameOrPosition = parseHash();
+ InterpolatedLiteral interpolatedLiteral =
+ new InterpolatedLiteral(nameOrPosition);
+ interpolatedValues.add(interpolatedLiteral);
+ propertyName = interpolatedLiteral;
+ } else {
+ error('Expected property name');
+ }
+ expectCategory(COLON);
+ Expression value = parseAssignment();
+ properties.add(new Property(propertyName, value));
+ if (acceptCategory(RBRACE)) break;
+ expectCategory(COMMA);
+ }
+ return new ObjectInitializer(properties);
+ }
+
+ Expression parseMember() {
+ Expression receiver = parsePrimary();
+ while (true) {
+ if (acceptCategory(DOT)) {
+ receiver = getDotRhs(receiver);
+ } else if (acceptCategory(LSQUARE)) {
+ Expression inBraces = parseExpression();
+ expectCategory(RSQUARE);
+ receiver = new PropertyAccess(receiver, inBraces);
+ } else {
+ break;
+ }
+ }
+ return receiver;
+ }
+
+ Expression parseCall() {
+ bool constructor = acceptString("new");
+ Expression receiver = parseMember();
+ while (true) {
+ if (acceptCategory(LPAREN)) {
+ final arguments = <Expression>[];
+ if (!acceptCategory(RPAREN)) {
+ while (true) {
+ Expression argument = parseAssignment();
+ arguments.add(argument);
+ if (acceptCategory(RPAREN)) break;
+ expectCategory(COMMA);
+ }
+ }
+ receiver = constructor ?
+ new New(receiver, arguments) :
+ new Call(receiver, arguments);
+ constructor = false;
+ } else if (!constructor && acceptCategory(LSQUARE)) {
+ Expression inBraces = parseExpression();
+ expectCategory(RSQUARE);
+ receiver = new PropertyAccess(receiver, inBraces);
+ } else if (!constructor && acceptCategory(DOT)) {
+ receiver = getDotRhs(receiver);
+ } else {
+ // JS allows new without (), but we don't.
+ if (constructor) error("Parentheses are required for new");
+ break;
+ }
+ }
+ return receiver;
+ }
+
+ Expression getDotRhs(Expression receiver) {
+ if (acceptCategory(HASH)) {
+ var nameOrPosition = parseHash();
+ InterpolatedSelector property = new InterpolatedSelector(nameOrPosition);
+ interpolatedValues.add(property);
+ return new PropertyAccess(receiver, property);
+ }
+ String identifier = lastToken;
+ // In ES5 keywords like delete and continue are allowed as property
+ // names, and the IndexedDB API uses that, so we need to allow it here.
+ if (acceptCategory(SYMBOL)) {
+ if (!OPERATORS_THAT_LOOK_LIKE_IDENTIFIERS.contains(identifier)) {
+ error("Expected alphanumeric identifier");
+ }
+ } else {
+ expectCategory(ALPHA);
+ }
+ return new PropertyAccess.field(receiver, identifier);
+ }
+
+ Expression parsePostfix() {
+ Expression expression = parseCall();
+ String operator = lastToken;
+ // JavaScript grammar is:
+ // LeftHandSideExpression [no LineTerminator here] ++
+ if (lastCategory == SYMBOL &&
+ !skippedNewline &&
+ (acceptString("++") || acceptString("--"))) {
+ return new Postfix(operator, expression);
+ }
+ // If we don't accept '++' or '--' due to skippedNewline a newline, no other
+ // part of the parser will accept the token and we will get an error at the
+ // whole expression level.
+ return expression;
+ }
+
+ Expression parseUnaryHigh() {
+ String operator = lastToken;
+ if (lastCategory == SYMBOL && UNARY_OPERATORS.contains(operator) &&
+ (acceptString("++") || acceptString("--") || acceptString('await'))) {
+ if (operator == "await") return new Await(parsePostfix());
+ return new Prefix(operator, parsePostfix());
+ }
+ return parsePostfix();
+ }
+
+ Expression parseUnaryLow() {
+ String operator = lastToken;
+ if (lastCategory == SYMBOL && UNARY_OPERATORS.contains(operator) &&
+ operator != "++" && operator != "--") {
+ expectCategory(SYMBOL);
+ if (operator == "await") return new Await(parsePostfix());
+ return new Prefix(operator, parseUnaryLow());
+ }
+ return parseUnaryHigh();
+ }
+
+ Expression parseBinary(int maxPrecedence) {
+ Expression lhs = parseUnaryLow();
+ int minPrecedence;
+ String lastSymbol;
+ Expression rhs; // This is null first time around.
+ while (true) {
+ String symbol = lastToken;
+ if (lastCategory != SYMBOL ||
+ !BINARY_PRECEDENCE.containsKey(symbol) ||
+ BINARY_PRECEDENCE[symbol] > maxPrecedence) {
+ break;
+ }
+ expectCategory(SYMBOL);
+ if (rhs == null || BINARY_PRECEDENCE[symbol] >= minPrecedence) {
+ if (rhs != null) lhs = new Binary(lastSymbol, lhs, rhs);
+ minPrecedence = BINARY_PRECEDENCE[symbol];
+ rhs = parseUnaryLow();
+ lastSymbol = symbol;
+ } else {
+ Expression higher = parseBinary(BINARY_PRECEDENCE[symbol]);
+ rhs = new Binary(symbol, rhs, higher);
+ }
+ }
+ if (rhs == null) return lhs;
+ return new Binary(lastSymbol, lhs, rhs);
+ }
+
+ Expression parseConditional() {
+ Expression lhs = parseBinary(HIGHEST_PARSE_BINARY_PRECEDENCE);
+ if (!acceptCategory(QUERY)) return lhs;
+ Expression ifTrue = parseAssignment();
+ expectCategory(COLON);
+ Expression ifFalse = parseAssignment();
+ return new Conditional(lhs, ifTrue, ifFalse);
+ }
+
+
+ Expression parseAssignment() {
+ Expression lhs = parseConditional();
+ String assignmentOperator = lastToken;
+ if (acceptCategory(ASSIGNMENT)) {
+ Expression rhs = parseAssignment();
+ if (assignmentOperator == "=") {
+ return new Assignment(lhs, rhs);
+ } else {
+ // Handle +=, -=, etc.
+ String operator =
+ assignmentOperator.substring(0, assignmentOperator.length - 1);
+ return new Assignment.compound(lhs, operator, rhs);
+ }
+ }
+ return lhs;
+ }
+
+ Expression parseExpression() {
+ Expression expression = parseAssignment();
+ while (acceptCategory(COMMA)) {
+ Expression right = parseAssignment();
+ expression = new Binary(',', expression, right);
+ }
+ return expression;
+ }
+
+ VariableDeclarationList parseVariableDeclarationList() {
+ Declaration firstVariable = parseVariableDeclaration();
+ return finishVariableDeclarationList(firstVariable);
+ }
+
+ VariableDeclarationList finishVariableDeclarationList(
+ Declaration firstVariable) {
+ var initialization = [];
+
+ void declare(Declaration declaration) {
+ Expression initializer = null;
+ if (acceptString("=")) {
+ initializer = parseAssignment();
+ }
+ initialization.add(new VariableInitialization(declaration, initializer));
+ }
+
+ declare(firstVariable);
+ while (acceptCategory(COMMA)) {
+ Declaration variable = parseVariableDeclaration();
+ declare(variable);
+ }
+ return new VariableDeclarationList(initialization);
+ }
+
+ Expression parseVarDeclarationOrExpression() {
+ if (acceptString("var")) {
+ return parseVariableDeclarationList();
+ } else {
+ return parseExpression();
+ }
+ }
+
+ Expression expression() {
+ Expression expression = parseVarDeclarationOrExpression();
+ if (lastCategory != NONE || position != src.length) {
+ error("Unparsed junk: ${categoryToString(lastCategory)}");
+ }
+ return expression;
+ }
+
+ Statement statement() {
+ Statement statement = parseStatement();
+ if (lastCategory != NONE || position != src.length) {
+ error("Unparsed junk: ${categoryToString(lastCategory)}");
+ }
+ // TODO(sra): interpolated capture here?
+ return statement;
+ }
+
+ Block parseBlock() {
+ List<Statement> statements = <Statement>[];
+
+ while (!acceptCategory(RBRACE)) {
+ Statement statement = parseStatement();
+ statements.add(statement);
+ }
+ return new Block(statements);
+ }
+
+ Statement parseStatement() {
+ if (acceptCategory(LBRACE)) return parseBlock();
+
+ if (acceptCategory(SEMICOLON)) return new EmptyStatement();
+
+ if (lastCategory == ALPHA) {
+ if (acceptString('return')) return parseReturn();
+
+ if (acceptString('throw')) return parseThrow();
+
+ if (acceptString('break')) {
+ return parseBreakOrContinue((label) => new Break(label));
+ }
+
+ if (acceptString('continue')) {
+ return parseBreakOrContinue((label) => new Continue(label));
+ }
+
+ if (acceptString('if')) return parseIfThenElse();
+
+ if (acceptString('for')) return parseFor();
+
+ if (acceptString('function')) return parseFunctionDeclaration();
+
+ if (acceptString('try')) return parseTry();
+
+ if (acceptString('var')) {
+ Expression declarations = parseVariableDeclarationList();
+ expectSemicolon();
+ return new ExpressionStatement(declarations);
+ }
+
+ if (acceptString('while')) return parseWhile();
+
+ if (acceptString('do')) return parseDo();
+
+ if (acceptString('switch')) return parseSwitch();
+
+ if (lastToken == 'case') error("Case outside switch.");
+
+ if (lastToken == 'default') error("Default outside switch.");
+
+ if (lastToken == 'yield') return parseYield();
+
+ if (lastToken == 'with') {
+ error('Not implemented in mini parser');
+ }
+
+ }
+
+ bool checkForInterpolatedStatement = lastCategory == HASH;
+
+ Expression expression = parseExpression();
+
+ if (expression is VariableUse && acceptCategory(COLON)) {
+ return new LabeledStatement(expression.name, parseStatement());
+ }
+
+ expectSemicolon();
+
+ if (checkForInterpolatedStatement) {
+ // 'Promote' the interpolated expression `#;` to an interpolated
+ // statement.
+ if (expression is InterpolatedExpression) {
+ assert(identical(interpolatedValues.last, expression));
+ InterpolatedStatement statement =
+ new InterpolatedStatement(expression.nameOrPosition);
+ interpolatedValues[interpolatedValues.length - 1] = statement;
+ return statement;
+ }
+ }
+
+ return new ExpressionStatement(expression);
+ }
+
+ Statement parseReturn() {
+ if (acceptSemicolon()) return new Return();
+ Expression expression = parseExpression();
+ expectSemicolon();
+ return new Return(expression);
+ }
+
+ Statement parseYield() {
+ bool hasStar = acceptString('*');
+ Expression expression = parseExpression();
+ expectSemicolon();
+ return new DartYield(expression, hasStar);
+ }
+
+ Statement parseThrow() {
+ if (skippedNewline) error('throw expression must be on same line');
+ Expression expression = parseExpression();
+ expectSemicolon();
+ return new Throw(expression);
+ }
+
+ Statement parseBreakOrContinue(constructor) {
+ var identifier = lastToken;
+ if (!skippedNewline && acceptCategory(ALPHA)) {
+ expectSemicolon();
+ return constructor(identifier);
+ }
+ expectSemicolon();
+ return constructor(null);
+ }
+
+ Statement parseIfThenElse() {
+ expectCategory(LPAREN);
+ Expression condition = parseExpression();
+ expectCategory(RPAREN);
+ Statement thenStatement = parseStatement();
+ if (acceptString('else')) {
+ // Resolves dangling else by binding 'else' to closest 'if'.
+ Statement elseStatement = parseStatement();
+ return new If(condition, thenStatement, elseStatement);
+ } else {
+ return new If.noElse(condition, thenStatement);
+ }
+ }
+
+ Statement parseFor() {
+ // For-init-condition-increment style loops are fully supported.
+ //
+ // Only one for-in variant is currently implemented:
+ //
+ // for (var variable in Expression) Statement
+ //
+ Statement finishFor(Expression init) {
+ Expression condition = null;
+ if (!acceptCategory(SEMICOLON)) {
+ condition = parseExpression();
+ expectCategory(SEMICOLON);
+ }
+ Expression update = null;
+ if (!acceptCategory(RPAREN)) {
+ update = parseExpression();
+ expectCategory(RPAREN);
+ }
+ Statement body = parseStatement();
+ return new For(init, condition, update, body);
+ }
+
+ expectCategory(LPAREN);
+ if (acceptCategory(SEMICOLON)) {
+ return finishFor(null);
+ }
+
+ if (acceptString('var')) {
+ Declaration declaration = parseVariableDeclaration();
+ if (acceptString('in')) {
+ Expression objectExpression = parseExpression();
+ expectCategory(RPAREN);
+ Statement body = parseStatement();
+ return new ForIn(
+ new VariableDeclarationList([
+ new VariableInitialization(declaration, null)]),
+ objectExpression,
+ body);
+ }
+ Expression declarations = finishVariableDeclarationList(declaration);
+ expectCategory(SEMICOLON);
+ return finishFor(declarations);
+ }
+
+ Expression init = parseExpression();
+ expectCategory(SEMICOLON);
+ return finishFor(init);
+ }
+
+ Declaration parseVariableDeclaration() {
+ if (acceptCategory(HASH)) {
+ var nameOrPosition = parseHash();
+ InterpolatedDeclaration declaration =
+ new InterpolatedDeclaration(nameOrPosition);
+ interpolatedValues.add(declaration);
+ return declaration;
+ } else {
+ String token = lastToken;
+ expectCategory(ALPHA);
+ return new VariableDeclaration(token);
+ }
+ }
+
+ Statement parseFunctionDeclaration() {
+ Declaration name = parseVariableDeclaration();
+ Expression fun = parseFun();
+ return new FunctionDeclaration(name, fun);
+ }
+
+ Statement parseTry() {
+ expectCategory(LBRACE);
+ Block body = parseBlock();
+ String token = lastToken;
+ Catch catchPart = null;
+ if (acceptString('catch')) catchPart = parseCatch();
+ Block finallyPart = null;
+ if (acceptString('finally')) {
+ expectCategory(LBRACE);
+ finallyPart = parseBlock();
+ } else {
+ if (catchPart == null) error("expected 'finally'");
+ }
+ return new Try(body, catchPart, finallyPart);
+ }
+
+ SwitchClause parseSwitchClause() {
+ Expression expression = null;
+ if (acceptString('case')) {
+ expression = parseExpression();
+ expectCategory(COLON);
+ } else {
+ if (!acceptString('default')) {
+ error('expected case or default');
+ }
+ expectCategory(COLON);
+ }
+ List statements = new List<Statement>();
+ while (lastCategory != RBRACE &&
+ lastToken != 'case' &&
+ lastToken != 'default') {
+ statements.add(parseStatement());
+ }
+ return expression == null
+ ? new Default(new Block(statements))
+ : new Case(expression, new Block(statements));
+ }
+
+ Statement parseWhile() {
+ expectCategory(LPAREN);
+ Expression condition = parseExpression();
+ expectCategory(RPAREN);
+ Statement body = parseStatement();
+ return new While(condition, body);
+ }
+
+ Statement parseDo() {
+ Statement body = parseStatement();
+ if (lastToken != "while") error("Missing while after do body.");
+ getToken();
+ expectCategory(LPAREN);
+ Expression condition = parseExpression();
+ expectCategory(RPAREN);
+ expectSemicolon();
+ return new Do(body, condition);
+ }
+
+ Statement parseSwitch() {
+ expectCategory(LPAREN);
+ Expression key = parseExpression();
+ expectCategory(RPAREN);
+ expectCategory(LBRACE);
+ List<SwitchClause> clauses = new List<SwitchClause>();
+ while(lastCategory != RBRACE) {
+ clauses.add(parseSwitchClause());
+ }
+ expectCategory(RBRACE);
+ return new Switch(key, clauses);
+ }
+
+ Catch parseCatch() {
+ expectCategory(LPAREN);
+ Declaration errorName = parseVariableDeclaration();
+ expectCategory(RPAREN);
+ expectCategory(LBRACE);
+ Block body = parseBlock();
+ return new Catch(errorName, body);
+ }
+}
diff --git a/pkg/compiler/lib/src/js/characters.dart b/pkg/js_ast/lib/src/characters.dart
similarity index 100%
rename from pkg/compiler/lib/src/js/characters.dart
rename to pkg/js_ast/lib/src/characters.dart
diff --git a/pkg/js_ast/lib/src/nodes.dart b/pkg/js_ast/lib/src/nodes.dart
new file mode 100644
index 0000000..cc758ba
--- /dev/null
+++ b/pkg/js_ast/lib/src/nodes.dart
@@ -0,0 +1,1176 @@
+// 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 js_ast;
+
+abstract class NodeVisitor<T> {
+ T visitProgram(Program node);
+
+ T visitBlock(Block node);
+ T visitExpressionStatement(ExpressionStatement node);
+ T visitEmptyStatement(EmptyStatement node);
+ T visitIf(If node);
+ T visitFor(For node);
+ T visitForIn(ForIn node);
+ T visitWhile(While node);
+ T visitDo(Do node);
+ T visitContinue(Continue node);
+ T visitBreak(Break node);
+ T visitReturn(Return node);
+ T visitThrow(Throw node);
+ T visitTry(Try node);
+ T visitCatch(Catch node);
+ T visitSwitch(Switch node);
+ T visitCase(Case node);
+ T visitDefault(Default node);
+ T visitFunctionDeclaration(FunctionDeclaration node);
+ T visitLabeledStatement(LabeledStatement node);
+ T visitLiteralStatement(LiteralStatement node);
+ T visitDartYield(DartYield node);
+
+ T visitLiteralExpression(LiteralExpression node);
+ T visitVariableDeclarationList(VariableDeclarationList node);
+ T visitAssignment(Assignment node);
+ T visitVariableInitialization(VariableInitialization node);
+ T visitConditional(Conditional cond);
+ T visitNew(New node);
+ T visitCall(Call node);
+ T visitBinary(Binary node);
+ T visitPrefix(Prefix node);
+ T visitPostfix(Postfix node);
+
+ T visitVariableUse(VariableUse node);
+ T visitThis(This node);
+ T visitVariableDeclaration(VariableDeclaration node);
+ T visitParameter(Parameter node);
+ T visitAccess(PropertyAccess node);
+
+ T visitNamedFunction(NamedFunction node);
+ T visitFun(Fun node);
+
+ T visitLiteralBool(LiteralBool node);
+ T visitLiteralString(LiteralString node);
+ T visitLiteralNumber(LiteralNumber node);
+ T visitLiteralNull(LiteralNull node);
+
+ T visitArrayInitializer(ArrayInitializer node);
+ T visitArrayHole(ArrayHole node);
+ T visitObjectInitializer(ObjectInitializer node);
+ T visitProperty(Property node);
+ T visitRegExpLiteral(RegExpLiteral node);
+
+ T visitAwait(Await node);
+
+ T visitComment(Comment node);
+
+ T visitInterpolatedExpression(InterpolatedExpression node);
+ T visitInterpolatedLiteral(InterpolatedLiteral node);
+ T visitInterpolatedParameter(InterpolatedParameter node);
+ T visitInterpolatedSelector(InterpolatedSelector node);
+ T visitInterpolatedStatement(InterpolatedStatement node);
+ T visitInterpolatedDeclaration(InterpolatedDeclaration node);
+}
+
+class BaseVisitor<T> implements NodeVisitor<T> {
+ T visitNode(Node node) {
+ node.visitChildren(this);
+ return null;
+ }
+
+ T visitProgram(Program node) => visitNode(node);
+
+ T visitStatement(Statement node) => visitNode(node);
+ T visitLoop(Loop node) => visitStatement(node);
+ T visitJump(Statement node) => visitStatement(node);
+
+ T visitBlock(Block node) => visitStatement(node);
+ T visitExpressionStatement(ExpressionStatement node)
+ => visitStatement(node);
+ T visitEmptyStatement(EmptyStatement node) => visitStatement(node);
+ T visitIf(If node) => visitStatement(node);
+ T visitFor(For node) => visitLoop(node);
+ T visitForIn(ForIn node) => visitLoop(node);
+ T visitWhile(While node) => visitLoop(node);
+ T visitDo(Do node) => visitLoop(node);
+ T visitContinue(Continue node) => visitJump(node);
+ T visitBreak(Break node) => visitJump(node);
+ T visitReturn(Return node) => visitJump(node);
+ T visitThrow(Throw node) => visitJump(node);
+ T visitTry(Try node) => visitStatement(node);
+ T visitSwitch(Switch node) => visitStatement(node);
+ T visitFunctionDeclaration(FunctionDeclaration node)
+ => visitStatement(node);
+ T visitLabeledStatement(LabeledStatement node) => visitStatement(node);
+ T visitLiteralStatement(LiteralStatement node) => visitStatement(node);
+
+ T visitCatch(Catch node) => visitNode(node);
+ T visitCase(Case node) => visitNode(node);
+ T visitDefault(Default node) => visitNode(node);
+
+ T visitExpression(Expression node) => visitNode(node);
+ T visitVariableReference(VariableReference node) => visitExpression(node);
+
+ T visitLiteralExpression(LiteralExpression node) => visitExpression(node);
+ T visitVariableDeclarationList(VariableDeclarationList node)
+ => visitExpression(node);
+ T visitAssignment(Assignment node) => visitExpression(node);
+ T visitVariableInitialization(VariableInitialization node) {
+ if (node.value != null) {
+ return visitAssignment(node);
+ } else {
+ return visitExpression(node);
+ }
+ }
+ T visitConditional(Conditional node) => visitExpression(node);
+ T visitNew(New node) => visitExpression(node);
+ T visitCall(Call node) => visitExpression(node);
+ T visitBinary(Binary node) => visitExpression(node);
+ T visitPrefix(Prefix node) => visitExpression(node);
+ T visitPostfix(Postfix node) => visitExpression(node);
+ T visitAccess(PropertyAccess node) => visitExpression(node);
+
+ T visitVariableUse(VariableUse node) => visitVariableReference(node);
+ T visitVariableDeclaration(VariableDeclaration node)
+ => visitVariableReference(node);
+ T visitParameter(Parameter node) => visitVariableDeclaration(node);
+ T visitThis(This node) => visitParameter(node);
+
+ T visitNamedFunction(NamedFunction node) => visitExpression(node);
+ T visitFun(Fun node) => visitExpression(node);
+
+ T visitLiteral(Literal node) => visitExpression(node);
+
+ T visitLiteralBool(LiteralBool node) => visitLiteral(node);
+ T visitLiteralString(LiteralString node) => visitLiteral(node);
+ T visitLiteralNumber(LiteralNumber node) => visitLiteral(node);
+ T visitLiteralNull(LiteralNull node) => visitLiteral(node);
+
+ T visitArrayInitializer(ArrayInitializer node) => visitExpression(node);
+ T visitArrayHole(ArrayHole node) => visitExpression(node);
+ T visitObjectInitializer(ObjectInitializer node) => visitExpression(node);
+ T visitProperty(Property node) => visitNode(node);
+ T visitRegExpLiteral(RegExpLiteral node) => visitExpression(node);
+
+ T visitInterpolatedNode(InterpolatedNode node) => visitNode(node);
+
+ T visitInterpolatedExpression(InterpolatedExpression node)
+ => visitInterpolatedNode(node);
+ T visitInterpolatedLiteral(InterpolatedLiteral node)
+ => visitInterpolatedNode(node);
+ T visitInterpolatedParameter(InterpolatedParameter node)
+ => visitInterpolatedNode(node);
+ T visitInterpolatedSelector(InterpolatedSelector node)
+ => visitInterpolatedNode(node);
+ T visitInterpolatedStatement(InterpolatedStatement node)
+ => visitInterpolatedNode(node);
+ T visitInterpolatedDeclaration(InterpolatedDeclaration node) {
+ return visitInterpolatedNode(node);
+ }
+
+ // Ignore comments by default.
+ T visitComment(Comment node) => null;
+
+ T visitAwait(Await node) => visitExpression(node);
+ T visitDartYield(DartYield node) => visitStatement(node);
+}
+
+/// This tag interface has no behaviour but must be implemented by any class
+/// that is to be stored on a [Node] as source information.
+abstract class JavaScriptNodeSourceInformation {}
+
+abstract class Node {
+ JavaScriptNodeSourceInformation get sourceInformation => _sourceInformation;
+
+ JavaScriptNodeSourceInformation _sourceInformation;
+
+ accept(NodeVisitor visitor);
+ void visitChildren(NodeVisitor visitor);
+
+ // Shallow clone of node. Does not clone positions since the only use of this
+ // private method is create a copy with a new position.
+ Node _clone();
+
+ // Returns a node equivalent to [this], but with new source position and end
+ // source position.
+ Node withSourceInformation(
+ JavaScriptNodeSourceInformation sourceInformation) {
+ if (sourceInformation == _sourceInformation) {
+ return this;
+ }
+ Node clone = _clone();
+ // TODO(sra): Should existing data be 'sticky' if we try to overwrite with
+ // `null`?
+ clone._sourceInformation = sourceInformation;
+ return clone;
+ }
+
+ VariableUse asVariableUse() => null;
+
+ bool get isCommaOperator => false;
+
+ Statement toStatement() {
+ throw new UnsupportedError('toStatement');
+ }
+}
+
+class Program extends Node {
+ final List<Statement> body;
+ Program(this.body);
+
+ accept(NodeVisitor visitor) => visitor.visitProgram(this);
+ void visitChildren(NodeVisitor visitor) {
+ for (Statement statement in body) statement.accept(visitor);
+ }
+ Program _clone() => new Program(body);
+}
+
+abstract class Statement extends Node {
+ Statement toStatement() => this;
+}
+
+class Block extends Statement {
+ final List<Statement> statements;
+ Block(this.statements);
+ Block.empty() : this.statements = <Statement>[];
+
+ accept(NodeVisitor visitor) => visitor.visitBlock(this);
+ void visitChildren(NodeVisitor visitor) {
+ for (Statement statement in statements) statement.accept(visitor);
+ }
+ Block _clone() => new Block(statements);
+}
+
+class ExpressionStatement extends Statement {
+ final Expression expression;
+ ExpressionStatement(this.expression);
+
+ accept(NodeVisitor visitor) => visitor.visitExpressionStatement(this);
+ void visitChildren(NodeVisitor visitor) { expression.accept(visitor); }
+ ExpressionStatement _clone() => new ExpressionStatement(expression);
+}
+
+class EmptyStatement extends Statement {
+ EmptyStatement();
+
+ accept(NodeVisitor visitor) => visitor.visitEmptyStatement(this);
+ void visitChildren(NodeVisitor visitor) {}
+ EmptyStatement _clone() => new EmptyStatement();
+}
+
+class If extends Statement {
+ final Expression condition;
+ final Node then;
+ final Node otherwise;
+
+ If(this.condition, this.then, this.otherwise);
+ If.noElse(this.condition, this.then) : this.otherwise = new EmptyStatement();
+
+ bool get hasElse => otherwise is !EmptyStatement;
+
+ accept(NodeVisitor visitor) => visitor.visitIf(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ condition.accept(visitor);
+ then.accept(visitor);
+ otherwise.accept(visitor);
+ }
+
+ If _clone() => new If(condition, then, otherwise);
+}
+
+abstract class Loop extends Statement {
+ final Statement body;
+ Loop(this.body);
+}
+
+class For extends Loop {
+ final Expression init;
+ final Expression condition;
+ final Expression update;
+
+ For(this.init, this.condition, this.update, Statement body) : super(body);
+
+ accept(NodeVisitor visitor) => visitor.visitFor(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ if (init != null) init.accept(visitor);
+ if (condition != null) condition.accept(visitor);
+ if (update != null) update.accept(visitor);
+ body.accept(visitor);
+ }
+
+ For _clone() => new For(init, condition, update, body);
+}
+
+class ForIn extends Loop {
+ // Note that [VariableDeclarationList] is a subclass of [Expression].
+ // Therefore we can type the leftHandSide as [Expression].
+ final Expression leftHandSide;
+ final Expression object;
+
+ ForIn(this.leftHandSide, this.object, Statement body) : super(body);
+
+ accept(NodeVisitor visitor) => visitor.visitForIn(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ leftHandSide.accept(visitor);
+ object.accept(visitor);
+ body.accept(visitor);
+ }
+
+ ForIn _clone() => new ForIn(leftHandSide, object, body);
+}
+
+class While extends Loop {
+ final Node condition;
+
+ While(this.condition, Statement body) : super(body);
+
+ accept(NodeVisitor visitor) => visitor.visitWhile(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ condition.accept(visitor);
+ body.accept(visitor);
+ }
+
+ While _clone() => new While(condition, body);
+}
+
+class Do extends Loop {
+ final Expression condition;
+
+ Do(Statement body, this.condition) : super(body);
+
+ accept(NodeVisitor visitor) => visitor.visitDo(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ body.accept(visitor);
+ condition.accept(visitor);
+ }
+
+ Do _clone() => new Do(body, condition);
+}
+
+class Continue extends Statement {
+ final String targetLabel; // Can be null.
+
+ Continue(this.targetLabel);
+
+ accept(NodeVisitor visitor) => visitor.visitContinue(this);
+ void visitChildren(NodeVisitor visitor) {}
+
+ Continue _clone() => new Continue(targetLabel);
+}
+
+class Break extends Statement {
+ final String targetLabel; // Can be null.
+
+ Break(this.targetLabel);
+
+ accept(NodeVisitor visitor) => visitor.visitBreak(this);
+ void visitChildren(NodeVisitor visitor) {}
+
+ Break _clone() => new Break(targetLabel);
+}
+
+class Return extends Statement {
+ final Expression value; // Can be null.
+
+ Return([this.value = null]);
+
+ accept(NodeVisitor visitor) => visitor.visitReturn(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ if (value != null) value.accept(visitor);
+ }
+
+ Return _clone() => new Return(value);
+}
+
+class Throw extends Statement {
+ final Expression expression;
+
+ Throw(this.expression);
+
+ accept(NodeVisitor visitor) => visitor.visitThrow(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ expression.accept(visitor);
+ }
+
+ Throw _clone() => new Throw(expression);
+}
+
+class Try extends Statement {
+ final Block body;
+ final Catch catchPart; // Can be null if [finallyPart] is non-null.
+ final Block finallyPart; // Can be null if [catchPart] is non-null.
+
+ Try(this.body, this.catchPart, this.finallyPart) {
+ assert(catchPart != null || finallyPart != null);
+ }
+
+ accept(NodeVisitor visitor) => visitor.visitTry(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ body.accept(visitor);
+ if (catchPart != null) catchPart.accept(visitor);
+ if (finallyPart != null) finallyPart.accept(visitor);
+ }
+
+ Try _clone() => new Try(body, catchPart, finallyPart);
+}
+
+class Catch extends Node {
+ final Declaration declaration;
+ final Block body;
+
+ Catch(this.declaration, this.body);
+
+ accept(NodeVisitor visitor) => visitor.visitCatch(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ declaration.accept(visitor);
+ body.accept(visitor);
+ }
+
+ Catch _clone() => new Catch(declaration, body);
+}
+
+class Switch extends Statement {
+ final Expression key;
+ final List<SwitchClause> cases;
+
+ Switch(this.key, this.cases);
+
+ accept(NodeVisitor visitor) => visitor.visitSwitch(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ key.accept(visitor);
+ for (SwitchClause clause in cases) clause.accept(visitor);
+ }
+
+ Switch _clone() => new Switch(key, cases);
+}
+
+abstract class SwitchClause extends Node {
+ final Block body;
+
+ SwitchClause(this.body);
+}
+
+class Case extends SwitchClause {
+ final Expression expression;
+
+ Case(this.expression, Block body) : super(body);
+
+ accept(NodeVisitor visitor) => visitor.visitCase(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ expression.accept(visitor);
+ body.accept(visitor);
+ }
+
+ Case _clone() => new Case(expression, body);
+}
+
+class Default extends SwitchClause {
+ Default(Block body) : super(body);
+
+ accept(NodeVisitor visitor) => visitor.visitDefault(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ body.accept(visitor);
+ }
+
+ Default _clone() => new Default(body);
+}
+
+class FunctionDeclaration extends Statement {
+ final Declaration name;
+ final Fun function;
+
+ FunctionDeclaration(this.name, this.function);
+
+ accept(NodeVisitor visitor) => visitor.visitFunctionDeclaration(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ name.accept(visitor);
+ function.accept(visitor);
+ }
+
+ FunctionDeclaration _clone() => new FunctionDeclaration(name, function);
+}
+
+class LabeledStatement extends Statement {
+ final String label;
+ final Statement body;
+
+ LabeledStatement(this.label, this.body);
+
+ accept(NodeVisitor visitor) => visitor.visitLabeledStatement(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ body.accept(visitor);
+ }
+
+ LabeledStatement _clone() => new LabeledStatement(label, body);
+}
+
+class LiteralStatement extends Statement {
+ final String code;
+
+ LiteralStatement(this.code);
+
+ accept(NodeVisitor visitor) => visitor.visitLiteralStatement(this);
+ void visitChildren(NodeVisitor visitor) { }
+
+ LiteralStatement _clone() => new LiteralStatement(code);
+}
+
+// Not a real JavaScript node, but represents the yield statement from a dart
+// program translated to JavaScript.
+class DartYield extends Statement {
+ final Expression expression;
+
+ final bool hasStar;
+
+ DartYield(this.expression, this.hasStar);
+
+ accept(NodeVisitor visitor) => visitor.visitDartYield(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ expression.accept(visitor);
+ }
+
+ DartYield _clone() => new DartYield(expression, hasStar);
+}
+
+abstract class Expression extends Node {
+ int get precedenceLevel;
+
+ Statement toStatement() => new ExpressionStatement(this);
+}
+
+abstract class Declaration implements VariableReference {
+
+}
+
+class LiteralExpression extends Expression {
+ final String template;
+ final List<Expression> inputs;
+
+ LiteralExpression(this.template) : inputs = const [];
+ LiteralExpression.withData(this.template, this.inputs);
+
+ accept(NodeVisitor visitor) => visitor.visitLiteralExpression(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ if (inputs != null) {
+ for (Expression expr in inputs) expr.accept(visitor);
+ }
+ }
+
+ LiteralExpression _clone() =>
+ new LiteralExpression.withData(template, inputs);
+
+ // Code that uses JS must take care of operator precedences, and
+ // put parenthesis if needed.
+ int get precedenceLevel => PRIMARY;
+}
+
+/**
+ * [VariableDeclarationList] is a subclass of [Expression] to simplify the
+ * AST.
+ */
+class VariableDeclarationList extends Expression {
+ final List<VariableInitialization> declarations;
+
+ VariableDeclarationList(this.declarations);
+
+ accept(NodeVisitor visitor) => visitor.visitVariableDeclarationList(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ for (VariableInitialization declaration in declarations) {
+ declaration.accept(visitor);
+ }
+ }
+
+ VariableDeclarationList _clone() => new VariableDeclarationList(declarations);
+
+ int get precedenceLevel => EXPRESSION;
+}
+
+class Assignment extends Expression {
+ final Expression leftHandSide;
+ final String op; // Null, if the assignment is not compound.
+ final Expression value; // May be null, for [VariableInitialization]s.
+
+ Assignment(leftHandSide, value)
+ : this.compound(leftHandSide, null, value);
+ Assignment.compound(this.leftHandSide, this.op, this.value);
+
+ int get precedenceLevel => ASSIGNMENT;
+
+ bool get isCompound => op != null;
+
+ accept(NodeVisitor visitor) => visitor.visitAssignment(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ leftHandSide.accept(visitor);
+ if (value != null) value.accept(visitor);
+ }
+
+ Assignment _clone() =>
+ new Assignment.compound(leftHandSide, op, value);
+}
+
+class VariableInitialization extends Assignment {
+ /** [value] may be null. */
+ VariableInitialization(Declaration declaration, Expression value)
+ : super(declaration, value);
+
+ Declaration get declaration => leftHandSide;
+
+ accept(NodeVisitor visitor) => visitor.visitVariableInitialization(this);
+
+ VariableInitialization _clone() =>
+ new VariableInitialization(declaration, value);
+}
+
+class Conditional extends Expression {
+ final Expression condition;
+ final Expression then;
+ final Expression otherwise;
+
+ Conditional(this.condition, this.then, this.otherwise);
+
+ accept(NodeVisitor visitor) => visitor.visitConditional(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ condition.accept(visitor);
+ then.accept(visitor);
+ otherwise.accept(visitor);
+ }
+
+ Conditional _clone() => new Conditional(condition, then, otherwise);
+
+ int get precedenceLevel => ASSIGNMENT;
+}
+
+class Call extends Expression {
+ Expression target;
+ List<Expression> arguments;
+
+ Call(this.target, this.arguments);
+
+ accept(NodeVisitor visitor) => visitor.visitCall(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ target.accept(visitor);
+ for (Expression arg in arguments) arg.accept(visitor);
+ }
+
+ Call _clone() => new Call(target, arguments);
+
+ int get precedenceLevel => CALL;
+}
+
+class New extends Call {
+ New(Expression cls, List<Expression> arguments) : super(cls, arguments);
+
+ accept(NodeVisitor visitor) => visitor.visitNew(this);
+
+ New _clone() => new New(target, arguments);
+}
+
+class Binary extends Expression {
+ final String op;
+ final Expression left;
+ final Expression right;
+
+ Binary(this.op, this.left, this.right);
+
+ accept(NodeVisitor visitor) => visitor.visitBinary(this);
+
+ Binary _clone() => new Binary(op, left, right);
+
+ void visitChildren(NodeVisitor visitor) {
+ left.accept(visitor);
+ right.accept(visitor);
+ }
+
+ bool get isCommaOperator => op == ',';
+
+ int get precedenceLevel {
+ // TODO(floitsch): switch to constant map.
+ switch (op) {
+ case "*":
+ case "/":
+ case "%":
+ return MULTIPLICATIVE;
+ case "+":
+ case "-":
+ return ADDITIVE;
+ case "<<":
+ case ">>":
+ case ">>>":
+ return SHIFT;
+ case "<":
+ case ">":
+ case "<=":
+ case ">=":
+ case "instanceof":
+ case "in":
+ return RELATIONAL;
+ case "==":
+ case "===":
+ case "!=":
+ case "!==":
+ return EQUALITY;
+ case "&":
+ return BIT_AND;
+ case "^":
+ return BIT_XOR;
+ case "|":
+ return BIT_OR;
+ case "&&":
+ return LOGICAL_AND;
+ case "||":
+ return LOGICAL_OR;
+ case ',':
+ return EXPRESSION;
+ default:
+ throw "Internal Error: Unhandled binary operator: $op";
+ }
+ }
+}
+
+class Prefix extends Expression {
+ final String op;
+ final Expression argument;
+
+ Prefix(this.op, this.argument);
+
+ accept(NodeVisitor visitor) => visitor.visitPrefix(this);
+
+ Prefix _clone() => new Prefix(op, argument);
+
+ void visitChildren(NodeVisitor visitor) {
+ argument.accept(visitor);
+ }
+
+ int get precedenceLevel => UNARY;
+}
+
+class Postfix extends Expression {
+ final String op;
+ final Expression argument;
+
+ Postfix(this.op, this.argument);
+
+ accept(NodeVisitor visitor) => visitor.visitPostfix(this);
+
+ Postfix _clone() => new Postfix(op, argument);
+
+ void visitChildren(NodeVisitor visitor) {
+ argument.accept(visitor);
+ }
+
+
+ int get precedenceLevel => UNARY;
+}
+
+abstract class VariableReference extends Expression {
+ final String name;
+
+ VariableReference(this.name) {
+ assert(_identifierRE.hasMatch(name));
+ }
+ static RegExp _identifierRE = new RegExp(r'^[A-Za-z_$][A-Za-z_$0-9]*$');
+
+ accept(NodeVisitor visitor);
+ int get precedenceLevel => PRIMARY;
+ void visitChildren(NodeVisitor visitor) {}
+}
+
+class VariableUse extends VariableReference {
+ VariableUse(String name) : super(name);
+
+ accept(NodeVisitor visitor) => visitor.visitVariableUse(this);
+ VariableUse _clone() => new VariableUse(name);
+
+ VariableUse asVariableUse() => this;
+
+ toString() => 'VariableUse($name)';
+}
+
+class VariableDeclaration extends VariableReference implements Declaration {
+ final bool allowRename;
+ VariableDeclaration(String name, {this.allowRename: true}) : super(name);
+
+ accept(NodeVisitor visitor) => visitor.visitVariableDeclaration(this);
+ VariableDeclaration _clone() => new VariableDeclaration(name);
+}
+
+class Parameter extends VariableDeclaration {
+ Parameter(String name) : super(name);
+
+ accept(NodeVisitor visitor) => visitor.visitParameter(this);
+ Parameter _clone() => new Parameter(name);
+}
+
+class This extends Parameter {
+ This() : super("this");
+
+ accept(NodeVisitor visitor) => visitor.visitThis(this);
+ This _clone() => new This();
+}
+
+class NamedFunction extends Expression {
+ final Declaration name;
+ final Fun function;
+
+ NamedFunction(this.name, this.function);
+
+ accept(NodeVisitor visitor) => visitor.visitNamedFunction(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ name.accept(visitor);
+ function.accept(visitor);
+ }
+ NamedFunction _clone() => new NamedFunction(name, function);
+
+ int get precedenceLevel => CALL;
+}
+
+class Fun extends Expression {
+ final List<Parameter> params;
+ final Block body;
+ final AsyncModifier asyncModifier;
+
+ Fun(this.params, this.body, {this.asyncModifier: const AsyncModifier.sync()});
+
+ accept(NodeVisitor visitor) => visitor.visitFun(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ for (Parameter param in params) param.accept(visitor);
+ body.accept(visitor);
+ }
+
+ Fun _clone() => new Fun(params, body, asyncModifier: asyncModifier);
+
+ int get precedenceLevel => CALL;
+}
+
+class AsyncModifier {
+ final bool isAsync;
+ final bool isYielding;
+ final String description;
+
+ const AsyncModifier.sync()
+ : isAsync = false,
+ isYielding = false,
+ description = "sync";
+ const AsyncModifier.async()
+ : isAsync = true,
+ isYielding = false,
+ description = "async";
+ const AsyncModifier.asyncStar()
+ : isAsync = true,
+ isYielding = true,
+ description = "async*";
+ const AsyncModifier.syncStar()
+ : isAsync = false,
+ isYielding = true,
+ description = "sync*";
+ toString() => description;
+}
+
+class PropertyAccess extends Expression {
+ final Expression receiver;
+ final Expression selector;
+
+ PropertyAccess(this.receiver, this.selector);
+ PropertyAccess.field(this.receiver, String fieldName)
+ : selector = new LiteralString('"$fieldName"');
+ PropertyAccess.indexed(this.receiver, int index)
+ : selector = new LiteralNumber('$index');
+
+ accept(NodeVisitor visitor) => visitor.visitAccess(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ receiver.accept(visitor);
+ selector.accept(visitor);
+ }
+
+ PropertyAccess _clone() => new PropertyAccess(receiver, selector);
+
+ int get precedenceLevel => CALL;
+}
+
+abstract class Literal extends Expression {
+ void visitChildren(NodeVisitor visitor) {}
+
+ int get precedenceLevel => PRIMARY;
+}
+
+class LiteralBool extends Literal {
+ final bool value;
+
+ LiteralBool(this.value);
+
+ accept(NodeVisitor visitor) => visitor.visitLiteralBool(this);
+ // [visitChildren] inherited from [Literal].
+ LiteralBool _clone() => new LiteralBool(value);
+}
+
+class LiteralNull extends Literal {
+ LiteralNull();
+
+ accept(NodeVisitor visitor) => visitor.visitLiteralNull(this);
+ LiteralNull _clone() => new LiteralNull();
+}
+
+class LiteralString extends Literal {
+ final String value;
+
+ /**
+ * Constructs a LiteralString from a string value.
+ *
+ * The constructor does not add the required quotes. If [value] is not
+ * surrounded by quotes and property escaped, the resulting object is invalid
+ * as a JS value.
+ *
+ * TODO(sra): Introduce variants for known valid strings that don't allocate a
+ * new string just to add quotes.
+ */
+ LiteralString(this.value);
+
+ accept(NodeVisitor visitor) => visitor.visitLiteralString(this);
+ LiteralString _clone() => new LiteralString(value);
+}
+
+class LiteralNumber extends Literal {
+ final String value; // Must be a valid JavaScript number literal.
+
+ LiteralNumber(this.value);
+
+ accept(NodeVisitor visitor) => visitor.visitLiteralNumber(this);
+ LiteralNumber _clone() => new LiteralNumber(value);
+}
+
+class ArrayInitializer extends Expression {
+ final List<Expression> elements;
+
+ ArrayInitializer(this.elements);
+
+ accept(NodeVisitor visitor) => visitor.visitArrayInitializer(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ for (Expression element in elements) element.accept(visitor);
+ }
+
+ ArrayInitializer _clone() => new ArrayInitializer(elements);
+
+ int get precedenceLevel => PRIMARY;
+}
+
+/**
+ * An empty place in an [ArrayInitializer].
+ * For example the list [1, , , 2] would contain two holes.
+ */
+class ArrayHole extends Expression {
+ accept(NodeVisitor visitor) => visitor.visitArrayHole(this);
+
+ void visitChildren(NodeVisitor visitor) {}
+
+ ArrayHole _clone() => new ArrayHole();
+
+ int get precedenceLevel => PRIMARY;
+}
+
+class ObjectInitializer extends Expression {
+ final List<Property> properties;
+ final bool isOneLiner;
+
+ /**
+ * Constructs a new object-initializer containing the given [properties].
+ *
+ * [isOneLiner] describes the behaviour when pretty-printing (non-minified).
+ * If true print all properties on the same line.
+ * If false print each property on a seperate line.
+ */
+ ObjectInitializer(this.properties, {this.isOneLiner: true});
+
+ accept(NodeVisitor visitor) => visitor.visitObjectInitializer(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ for (Property init in properties) init.accept(visitor);
+ }
+
+ ObjectInitializer _clone() =>
+ new ObjectInitializer(properties, isOneLiner: isOneLiner);
+
+ int get precedenceLevel => PRIMARY;
+}
+
+class Property extends Node {
+ final Literal name;
+ final Expression value;
+
+ Property(this.name, this.value);
+
+ accept(NodeVisitor visitor) => visitor.visitProperty(this);
+
+ void visitChildren(NodeVisitor visitor) {
+ name.accept(visitor);
+ value.accept(visitor);
+ }
+
+ Property _clone() => new Property(name, value);
+}
+
+/// Tag class for all interpolated positions.
+abstract class InterpolatedNode implements Node {
+ get nameOrPosition;
+
+ bool get isNamed => nameOrPosition is String;
+ bool get isPositional => nameOrPosition is int;
+}
+
+class InterpolatedExpression extends Expression with InterpolatedNode {
+ final nameOrPosition;
+
+ InterpolatedExpression(this.nameOrPosition);
+
+ accept(NodeVisitor visitor) => visitor.visitInterpolatedExpression(this);
+ void visitChildren(NodeVisitor visitor) {}
+ InterpolatedExpression _clone() =>
+ new InterpolatedExpression(nameOrPosition);
+
+ int get precedenceLevel => PRIMARY;
+}
+
+class InterpolatedLiteral extends Literal with InterpolatedNode {
+ final nameOrPosition;
+
+ InterpolatedLiteral(this.nameOrPosition);
+
+ accept(NodeVisitor visitor) => visitor.visitInterpolatedLiteral(this);
+ void visitChildren(NodeVisitor visitor) {}
+ InterpolatedLiteral _clone() => new InterpolatedLiteral(nameOrPosition);
+}
+
+class InterpolatedParameter extends Expression with InterpolatedNode
+ implements Parameter {
+ final nameOrPosition;
+
+ String get name { throw "InterpolatedParameter.name must not be invoked"; }
+ bool get allowRename => false;
+
+ InterpolatedParameter(this.nameOrPosition);
+
+ accept(NodeVisitor visitor) => visitor.visitInterpolatedParameter(this);
+ void visitChildren(NodeVisitor visitor) {}
+ InterpolatedParameter _clone() => new InterpolatedParameter(nameOrPosition);
+
+ int get precedenceLevel => PRIMARY;
+}
+
+class InterpolatedSelector extends Expression with InterpolatedNode {
+ final nameOrPosition;
+
+ InterpolatedSelector(this.nameOrPosition);
+
+ accept(NodeVisitor visitor) => visitor.visitInterpolatedSelector(this);
+ void visitChildren(NodeVisitor visitor) {}
+ InterpolatedSelector _clone() => new InterpolatedSelector(nameOrPosition);
+
+ int get precedenceLevel => PRIMARY;
+}
+
+class InterpolatedStatement extends Statement with InterpolatedNode {
+ final nameOrPosition;
+
+ InterpolatedStatement(this.nameOrPosition);
+
+ accept(NodeVisitor visitor) => visitor.visitInterpolatedStatement(this);
+ void visitChildren(NodeVisitor visitor) {}
+ InterpolatedStatement _clone() => new InterpolatedStatement(nameOrPosition);
+}
+
+class InterpolatedDeclaration extends Expression
+ with InterpolatedNode
+ implements Declaration {
+ final nameOrPosition;
+
+ InterpolatedDeclaration(this.nameOrPosition);
+
+ accept(NodeVisitor visitor) => visitor.visitInterpolatedDeclaration(this);
+ void visitChildren(NodeVisitor visitor) {}
+ InterpolatedDeclaration _clone() {
+ return new InterpolatedDeclaration(nameOrPosition);
+ }
+
+ @override
+ String get name => throw "No name for the interpolated node";
+
+ @override
+ int get precedenceLevel => PRIMARY;
+}
+
+/**
+ * [RegExpLiteral]s, despite being called "Literal", do not inherit from
+ * [Literal]. Indeed, regular expressions in JavaScript have a side-effect and
+ * are thus not in the same category as numbers or strings.
+ */
+class RegExpLiteral extends Expression {
+ /** Contains the pattern and the flags.*/
+ final String pattern;
+
+ RegExpLiteral(this.pattern);
+
+ accept(NodeVisitor visitor) => visitor.visitRegExpLiteral(this);
+ void visitChildren(NodeVisitor visitor) {}
+ RegExpLiteral _clone() => new RegExpLiteral(pattern);
+
+ int get precedenceLevel => PRIMARY;
+}
+
+/**
+ * An asynchronous await.
+ *
+ * Not part of JavaScript. We desugar this expression before outputting.
+ * Should only occur in a [Fun] with `asyncModifier` async or asyncStar.
+ */
+class Await extends Expression {
+ /** The awaited expression. */
+ final Expression expression;
+
+ Await(this.expression);
+
+ int get precedenceLevel => UNARY;
+ accept(NodeVisitor visitor) => visitor.visitAwait(this);
+ void visitChildren(NodeVisitor visitor) => expression.accept(visitor);
+ Await _clone() => new Await(expression);
+
+}
+
+/**
+ * A comment.
+ *
+ * Extends [Statement] so we can add comments before statements in
+ * [Block] and [Program].
+ */
+class Comment extends Statement {
+ final String comment;
+
+ Comment(this.comment);
+
+ accept(NodeVisitor visitor) => visitor.visitComment(this);
+ Comment _clone() => new Comment(comment);
+
+ void visitChildren(NodeVisitor visitor) {}
+}
diff --git a/pkg/compiler/lib/src/js/precedence.dart b/pkg/js_ast/lib/src/precedence.dart
similarity index 100%
rename from pkg/compiler/lib/src/js/precedence.dart
rename to pkg/js_ast/lib/src/precedence.dart
diff --git a/pkg/js_ast/lib/src/printer.dart b/pkg/js_ast/lib/src/printer.dart
new file mode 100644
index 0000000..b1aceba
--- /dev/null
+++ b/pkg/js_ast/lib/src/printer.dart
@@ -0,0 +1,1251 @@
+// 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 js_ast;
+
+
+class JavaScriptPrintingOptions {
+ final bool shouldCompressOutput;
+ final bool minifyLocalVariables;
+ final bool preferSemicolonToNewlineInMinifiedOutput;
+
+ JavaScriptPrintingOptions(
+ {this.shouldCompressOutput: false,
+ this.minifyLocalVariables: false,
+ this.preferSemicolonToNewlineInMinifiedOutput: false});
+}
+
+
+/// An environment in which JavaScript printing is done. Provides emitting of
+/// text and pre- and post-visit callbacks.
+abstract class JavaScriptPrintingContext {
+ /// Signals an error. This should happen only for serious internal errors.
+ void error(String message) { throw message; }
+
+ /// Adds [string] to the output.
+ void emit(String string);
+
+ /// Callback immediately before printing [node]. Whitespace may be printed
+ /// after this callback before the first non-whitespace character for [node].
+ void enterNode(Node node) {}
+ /// Callback after printing the last character representing [node].
+ void exitNode(Node node) {}
+}
+
+/// A simple implementation of [JavaScriptPrintingContext] suitable for tests.
+class SimpleJavaScriptPrintingContext extends JavaScriptPrintingContext {
+ final StringBuffer buffer = new StringBuffer();
+
+ void emit(String string) {
+ buffer.write(string);
+ }
+
+ String getText() => buffer.toString();
+}
+
+
+class Printer implements NodeVisitor {
+ final JavaScriptPrintingOptions options;
+ final JavaScriptPrintingContext context;
+ final bool shouldCompressOutput;
+ final DanglingElseVisitor danglingElseVisitor;
+ final LocalNamer localNamer;
+
+ bool inForInit = false;
+ bool atStatementBegin = false;
+ bool pendingSemicolon = false;
+ bool pendingSpace = false;
+
+ // The current indentation level.
+ int _indentLevel = 0;
+ // A cache of all indentation strings used so far.
+ List<String> _indentList = <String>[""];
+
+ static final identifierCharacterRegExp = new RegExp(r'^[a-zA-Z_0-9$]');
+ static final expressionContinuationRegExp = new RegExp(r'^[-+([]');
+
+ Printer(JavaScriptPrintingOptions options,
+ JavaScriptPrintingContext context)
+ : options = options,
+ context = context,
+ shouldCompressOutput = options.shouldCompressOutput,
+ danglingElseVisitor = new DanglingElseVisitor(context),
+ localNamer = determineRenamer(options.shouldCompressOutput,
+ options.minifyLocalVariables);
+
+ static LocalNamer determineRenamer(bool shouldCompressOutput,
+ bool allowVariableMinification) {
+ return (shouldCompressOutput && allowVariableMinification)
+ ? new MinifyRenamer() : new IdentityNamer();
+ }
+
+
+ // The current indentation string.
+ String get indentation {
+ // Lazily add new indentation strings as required.
+ while (_indentList.length <= _indentLevel) {
+ _indentList.add(_indentList.last + " ");
+ }
+ return _indentList[_indentLevel];
+ }
+
+ void indentMore() {
+ _indentLevel++;
+ }
+
+ void indentLess() {
+ _indentLevel--;
+ }
+
+
+ /// Always emit a newline, even under `enableMinification`.
+ void forceLine() {
+ out("\n");
+ }
+ /// Emits a newline for readability.
+ void lineOut() {
+ if (!shouldCompressOutput) forceLine();
+ }
+ void spaceOut() {
+ if (!shouldCompressOutput) out(" ");
+ }
+
+ String lastAddedString = null;
+ int get lastCharCode {
+ if (lastAddedString == null) return 0;
+ assert(lastAddedString.length != "");
+ return lastAddedString.codeUnitAt(lastAddedString.length - 1);
+ }
+
+ void out(String str) {
+ if (str != "") {
+ if (pendingSemicolon) {
+ if (!shouldCompressOutput) {
+ context.emit(";");
+ } else if (str != "}") {
+ // We want to output newline instead of semicolon because it makes
+ // the raw stack traces much easier to read and it also makes line-
+ // based tools like diff work much better. JavaScript will
+ // automatically insert the semicolon at the newline if it means a
+ // parsing error is avoided, so we can only do this trick if the
+ // next line is not something that can be glued onto a valid
+ // expression to make a new valid expression.
+
+ // If we're using the new emitter where most pretty printed code
+ // is escaped in strings, it is a lot easier to deal with semicolons
+ // than newlines because the former doesn't need escaping.
+ if (options.preferSemicolonToNewlineInMinifiedOutput ||
+ expressionContinuationRegExp.hasMatch(str)) {
+ context.emit(";");
+ } else {
+ context.emit("\n");
+ }
+ }
+ }
+ if (pendingSpace &&
+ (!shouldCompressOutput || identifierCharacterRegExp.hasMatch(str))) {
+ context.emit(" ");
+ }
+ pendingSpace = false;
+ pendingSemicolon = false;
+ context.emit(str);
+ lastAddedString = str;
+ }
+ }
+
+ void outLn(String str) {
+ out(str);
+ lineOut();
+ }
+
+ void outSemicolonLn() {
+ if (shouldCompressOutput) {
+ pendingSemicolon = true;
+ } else {
+ out(";");
+ forceLine();
+ }
+ }
+
+ void outIndent(String str) { indent(); out(str); }
+ void outIndentLn(String str) { indent(); outLn(str); }
+ void indent() {
+ if (!shouldCompressOutput) {
+ out(indentation);
+ }
+ }
+
+ visit(Node node) {
+ context.enterNode(node);
+ node.accept(this);
+ context.exitNode(node);
+ }
+
+ visitCommaSeparated(List<Node> nodes, int hasRequiredType,
+ {bool newInForInit, bool newAtStatementBegin}) {
+ for (int i = 0; i < nodes.length; i++) {
+ if (i != 0) {
+ atStatementBegin = false;
+ out(",");
+ spaceOut();
+ }
+ visitNestedExpression(nodes[i], hasRequiredType,
+ newInForInit: newInForInit,
+ newAtStatementBegin: newAtStatementBegin);
+ }
+ }
+
+ visitAll(List<Node> nodes) {
+ nodes.forEach(visit);
+ }
+
+ visitProgram(Program program) {
+ visitAll(program.body);
+ }
+
+ bool blockBody(Node body, {bool needsSeparation, bool needsNewline}) {
+ if (body is Block) {
+ spaceOut();
+ blockOut(body, false, needsNewline);
+ return true;
+ }
+ if (shouldCompressOutput && needsSeparation) {
+ // If [shouldCompressOutput] is false, then the 'lineOut' will insert
+ // the separation.
+ out(" ");
+ } else {
+ lineOut();
+ }
+ indentMore();
+ visit(body);
+ indentLess();
+ return false;
+ }
+
+ void blockOutWithoutBraces(Node node) {
+ if (node is Block) {
+ context.enterNode(node);
+ Block block = node;
+ block.statements.forEach(blockOutWithoutBraces);
+ context.exitNode(node);
+ } else {
+ visit(node);
+ }
+ }
+
+ void blockOut(Block node, bool shouldIndent, bool needsNewline) {
+ if (shouldIndent) indent();
+ context.enterNode(node);
+ out("{");
+ lineOut();
+ indentMore();
+ node.statements.forEach(blockOutWithoutBraces);
+ indentLess();
+ indent();
+ out("}");
+ context.exitNode(node);
+ if (needsNewline) lineOut();
+ }
+
+ visitBlock(Block block) {
+ blockOut(block, true, true);
+ }
+
+ visitExpressionStatement(ExpressionStatement expressionStatement) {
+ indent();
+ visitNestedExpression(expressionStatement.expression, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: true);
+ outSemicolonLn();
+ }
+
+ visitEmptyStatement(EmptyStatement nop) {
+ outIndentLn(";");
+ }
+
+ void ifOut(If node, bool shouldIndent) {
+ Node then = node.then;
+ Node elsePart = node.otherwise;
+ bool hasElse = node.hasElse;
+
+ // Handle dangling elses and a work-around for Android 4.0 stock browser.
+ // Android 4.0 requires braces for a single do-while in the `then` branch.
+ // See issue 10923.
+ if (hasElse) {
+ bool needsBraces = node.then.accept(danglingElseVisitor) || then is Do;
+ if (needsBraces) {
+ then = new Block(<Statement>[then]);
+ }
+ }
+ if (shouldIndent) indent();
+ out("if");
+ spaceOut();
+ out("(");
+ visitNestedExpression(node.condition, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ out(")");
+ bool thenWasBlock =
+ blockBody(then, needsSeparation: false, needsNewline: !hasElse);
+ if (hasElse) {
+ if (thenWasBlock) {
+ spaceOut();
+ } else {
+ indent();
+ }
+ out("else");
+ if (elsePart is If) {
+ pendingSpace = true;
+ ifOut(elsePart, false);
+ } else {
+ blockBody(elsePart, needsSeparation: true, needsNewline: true);
+ }
+ }
+ }
+
+ visitIf(If node) {
+ ifOut(node, true);
+ }
+
+ visitFor(For loop) {
+ outIndent("for");
+ spaceOut();
+ out("(");
+ if (loop.init != null) {
+ visitNestedExpression(loop.init, EXPRESSION,
+ newInForInit: true, newAtStatementBegin: false);
+ }
+ out(";");
+ if (loop.condition != null) {
+ spaceOut();
+ visitNestedExpression(loop.condition, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ }
+ out(";");
+ if (loop.update != null) {
+ spaceOut();
+ visitNestedExpression(loop.update, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ }
+ out(")");
+ blockBody(loop.body, needsSeparation: false, needsNewline: true);
+ }
+
+ visitForIn(ForIn loop) {
+ outIndent("for");
+ spaceOut();
+ out("(");
+ visitNestedExpression(loop.leftHandSide, EXPRESSION,
+ newInForInit: true, newAtStatementBegin: false);
+ out(" in");
+ pendingSpace = true;
+ visitNestedExpression(loop.object, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ out(")");
+ blockBody(loop.body, needsSeparation: false, needsNewline: true);
+ }
+
+ visitWhile(While loop) {
+ outIndent("while");
+ spaceOut();
+ out("(");
+ visitNestedExpression(loop.condition, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ out(")");
+ blockBody(loop.body, needsSeparation: false, needsNewline: true);
+ }
+
+ visitDo(Do loop) {
+ outIndent("do");
+ if (blockBody(loop.body, needsSeparation: true, needsNewline: false)) {
+ spaceOut();
+ } else {
+ indent();
+ }
+ out("while");
+ spaceOut();
+ out("(");
+ visitNestedExpression(loop.condition, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ out(")");
+ outSemicolonLn();
+ }
+
+ visitContinue(Continue node) {
+ if (node.targetLabel == null) {
+ outIndent("continue");
+ } else {
+ outIndent("continue ${node.targetLabel}");
+ }
+ outSemicolonLn();
+ }
+
+ visitBreak(Break node) {
+ if (node.targetLabel == null) {
+ outIndent("break");
+ } else {
+ outIndent("break ${node.targetLabel}");
+ }
+ outSemicolonLn();
+ }
+
+ visitReturn(Return node) {
+ if (node.value == null) {
+ outIndent("return");
+ } else {
+ outIndent("return");
+ pendingSpace = true;
+ visitNestedExpression(node.value, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ }
+ outSemicolonLn();
+ }
+
+ visitDartYield(DartYield node) {
+ if (node.hasStar) {
+ outIndent("yield*");
+ } else {
+ outIndent("yield");
+ }
+ pendingSpace = true;
+ visitNestedExpression(node.expression, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ outSemicolonLn();
+ }
+
+
+ visitThrow(Throw node) {
+ outIndent("throw");
+ pendingSpace = true;
+ visitNestedExpression(node.expression, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ outSemicolonLn();
+ }
+
+ visitTry(Try node) {
+ outIndent("try");
+ blockBody(node.body, needsSeparation: true, needsNewline: false);
+ if (node.catchPart != null) {
+ visit(node.catchPart);
+ }
+ if (node.finallyPart != null) {
+ spaceOut();
+ out("finally");
+ blockBody(node.finallyPart, needsSeparation: true, needsNewline: true);
+ } else {
+ lineOut();
+ }
+ }
+
+ visitCatch(Catch node) {
+ spaceOut();
+ out("catch");
+ spaceOut();
+ out("(");
+ visitNestedExpression(node.declaration, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ out(")");
+ blockBody(node.body, needsSeparation: false, needsNewline: true);
+ }
+
+ visitSwitch(Switch node) {
+ outIndent("switch");
+ spaceOut();
+ out("(");
+ visitNestedExpression(node.key, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ out(")");
+ spaceOut();
+ outLn("{");
+ indentMore();
+ visitAll(node.cases);
+ indentLess();
+ outIndentLn("}");
+ }
+
+ visitCase(Case node) {
+ outIndent("case");
+ pendingSpace = true;
+ visitNestedExpression(node.expression, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ outLn(":");
+ if (!node.body.statements.isEmpty) {
+ indentMore();
+ blockOutWithoutBraces(node.body);
+ indentLess();
+ }
+ }
+
+ visitDefault(Default node) {
+ outIndentLn("default:");
+ if (!node.body.statements.isEmpty) {
+ indentMore();
+ blockOutWithoutBraces(node.body);
+ indentLess();
+ }
+ }
+
+ visitLabeledStatement(LabeledStatement node) {
+ outIndent("${node.label}:");
+ blockBody(node.body, needsSeparation: false, needsNewline: true);
+ }
+
+ void functionOut(Fun fun, Node name, VarCollector vars) {
+ out("function");
+ if (name != null) {
+ out(" ");
+ // Name must be a [Decl]. Therefore only test for primary expressions.
+ visitNestedExpression(name, PRIMARY,
+ newInForInit: false, newAtStatementBegin: false);
+ }
+ localNamer.enterScope(vars);
+ out("(");
+ if (fun.params != null) {
+ visitCommaSeparated(fun.params, PRIMARY,
+ newInForInit: false, newAtStatementBegin: false);
+ }
+ out(")");
+ switch (fun.asyncModifier) {
+ case const AsyncModifier.sync():
+ break;
+ case const AsyncModifier.async():
+ out(' async');
+ break;
+ case const AsyncModifier.syncStar():
+ out(' sync*');
+ break;
+ case const AsyncModifier.asyncStar():
+ out(' async*');
+ break;
+ }
+ blockBody(fun.body, needsSeparation: false, needsNewline: false);
+ localNamer.leaveScope();
+ }
+
+ visitFunctionDeclaration(FunctionDeclaration declaration) {
+ VarCollector vars = new VarCollector();
+ vars.visitFunctionDeclaration(declaration);
+ indent();
+ functionOut(declaration.function, declaration.name, vars);
+ lineOut();
+ }
+
+ visitNestedExpression(Expression node, int requiredPrecedence,
+ {bool newInForInit, bool newAtStatementBegin}) {
+ bool needsParentheses =
+ // a - (b + c).
+ (requiredPrecedence != EXPRESSION &&
+ node.precedenceLevel < requiredPrecedence) ||
+ // for (a = (x in o); ... ; ... ) { ... }
+ (newInForInit && node is Binary && node.op == "in") ||
+ // (function() { ... })().
+ // ({a: 2, b: 3}.toString()).
+ (newAtStatementBegin && (node is NamedFunction ||
+ node is Fun ||
+ node is ObjectInitializer));
+ if (needsParentheses) {
+ inForInit = false;
+ atStatementBegin = false;
+ out("(");
+ visit(node);
+ out(")");
+ } else {
+ inForInit = newInForInit;
+ atStatementBegin = newAtStatementBegin;
+ visit(node);
+ }
+ }
+
+ visitVariableDeclarationList(VariableDeclarationList list) {
+ out("var ");
+ visitCommaSeparated(list.declarations, ASSIGNMENT,
+ newInForInit: inForInit, newAtStatementBegin: false);
+ }
+
+ visitAssignment(Assignment assignment) {
+ visitNestedExpression(assignment.leftHandSide, LEFT_HAND_SIDE,
+ newInForInit: inForInit,
+ newAtStatementBegin: atStatementBegin);
+ if (assignment.value != null) {
+ spaceOut();
+ String op = assignment.op;
+ if (op != null) out(op);
+ out("=");
+ spaceOut();
+ visitNestedExpression(assignment.value, ASSIGNMENT,
+ newInForInit: inForInit,
+ newAtStatementBegin: false);
+ }
+ }
+
+ visitVariableInitialization(VariableInitialization initialization) {
+ visitAssignment(initialization);
+ }
+
+ visitConditional(Conditional cond) {
+ visitNestedExpression(cond.condition, LOGICAL_OR,
+ newInForInit: inForInit,
+ newAtStatementBegin: atStatementBegin);
+ spaceOut();
+ out("?");
+ spaceOut();
+ // The then part is allowed to have an 'in'.
+ visitNestedExpression(cond.then, ASSIGNMENT,
+ newInForInit: false, newAtStatementBegin: false);
+ spaceOut();
+ out(":");
+ spaceOut();
+ visitNestedExpression(cond.otherwise, ASSIGNMENT,
+ newInForInit: inForInit, newAtStatementBegin: false);
+ }
+
+ visitNew(New node) {
+ out("new ");
+ visitNestedExpression(node.target, CALL,
+ newInForInit: inForInit, newAtStatementBegin: false);
+ out("(");
+ visitCommaSeparated(node.arguments, ASSIGNMENT,
+ newInForInit: false, newAtStatementBegin: false);
+ out(")");
+ }
+
+ visitCall(Call call) {
+ visitNestedExpression(call.target, LEFT_HAND_SIDE,
+ newInForInit: inForInit,
+ newAtStatementBegin: atStatementBegin);
+ out("(");
+ visitCommaSeparated(call.arguments, ASSIGNMENT,
+ newInForInit: false, newAtStatementBegin: false);
+ out(")");
+ }
+
+ visitBinary(Binary binary) {
+ Expression left = binary.left;
+ Expression right = binary.right;
+ String op = binary.op;
+ int leftPrecedenceRequirement;
+ int rightPrecedenceRequirement;
+ bool leftSpace = true; // left<HERE>op right
+ switch (op) {
+ case ',':
+ // x, (y, z) <=> (x, y), z.
+ leftPrecedenceRequirement = EXPRESSION;
+ rightPrecedenceRequirement = EXPRESSION;
+ leftSpace = false;
+ break;
+ case "||":
+ leftPrecedenceRequirement = LOGICAL_OR;
+ // x || (y || z) <=> (x || y) || z.
+ rightPrecedenceRequirement = LOGICAL_OR;
+ break;
+ case "&&":
+ leftPrecedenceRequirement = LOGICAL_AND;
+ // x && (y && z) <=> (x && y) && z.
+ rightPrecedenceRequirement = LOGICAL_AND;
+ break;
+ case "|":
+ leftPrecedenceRequirement = BIT_OR;
+ // x | (y | z) <=> (x | y) | z.
+ rightPrecedenceRequirement = BIT_OR;
+ break;
+ case "^":
+ leftPrecedenceRequirement = BIT_XOR;
+ // x ^ (y ^ z) <=> (x ^ y) ^ z.
+ rightPrecedenceRequirement = BIT_XOR;
+ break;
+ case "&":
+ leftPrecedenceRequirement = BIT_AND;
+ // x & (y & z) <=> (x & y) & z.
+ rightPrecedenceRequirement = BIT_AND;
+ break;
+ case "==":
+ case "!=":
+ case "===":
+ case "!==":
+ leftPrecedenceRequirement = EQUALITY;
+ rightPrecedenceRequirement = RELATIONAL;
+ break;
+ case "<":
+ case ">":
+ case "<=":
+ case ">=":
+ case "instanceof":
+ case "in":
+ leftPrecedenceRequirement = RELATIONAL;
+ rightPrecedenceRequirement = SHIFT;
+ break;
+ case ">>":
+ case "<<":
+ case ">>>":
+ leftPrecedenceRequirement = SHIFT;
+ rightPrecedenceRequirement = ADDITIVE;
+ break;
+ case "+":
+ case "-":
+ leftPrecedenceRequirement = ADDITIVE;
+ // We cannot remove parenthesis for "+" because
+ // x + (y + z) <!=> (x + y) + z:
+ // Example:
+ // "a" + (1 + 2) => "a3";
+ // ("a" + 1) + 2 => "a12";
+ rightPrecedenceRequirement = MULTIPLICATIVE;
+ break;
+ case "*":
+ case "/":
+ case "%":
+ leftPrecedenceRequirement = MULTIPLICATIVE;
+ // We cannot remove parenthesis for "*" because of precision issues.
+ rightPrecedenceRequirement = UNARY;
+ break;
+ default:
+ context.error("Forgot operator: $op");
+ }
+
+ visitNestedExpression(left, leftPrecedenceRequirement,
+ newInForInit: inForInit,
+ newAtStatementBegin: atStatementBegin);
+
+ if (op == "in" || op == "instanceof") {
+ // There are cases where the space is not required but without further
+ // analysis we cannot know.
+ out(" ");
+ out(op);
+ out(" ");
+ } else {
+ if (leftSpace) spaceOut();
+ out(op);
+ spaceOut();
+ }
+ visitNestedExpression(right, rightPrecedenceRequirement,
+ newInForInit: inForInit,
+ newAtStatementBegin: false);
+ }
+
+ visitPrefix(Prefix unary) {
+ String op = unary.op;
+ switch (op) {
+ case "delete":
+ case "void":
+ case "typeof":
+ // There are cases where the space is not required but without further
+ // analysis we cannot know.
+ out(op);
+ out(" ");
+ break;
+ case "+":
+ case "++":
+ if (lastCharCode == charCodes.$PLUS) out(" ");
+ out(op);
+ break;
+ case "-":
+ case "--":
+ if (lastCharCode == charCodes.$MINUS) out(" ");
+ out(op);
+ break;
+ default:
+ out(op);
+ }
+ visitNestedExpression(unary.argument, UNARY,
+ newInForInit: inForInit, newAtStatementBegin: false);
+ }
+
+ visitPostfix(Postfix postfix) {
+ visitNestedExpression(postfix.argument, LEFT_HAND_SIDE,
+ newInForInit: inForInit,
+ newAtStatementBegin: atStatementBegin);
+ out(postfix.op);
+ }
+
+ visitVariableUse(VariableUse ref) {
+ out(localNamer.getName(ref.name));
+ }
+
+ visitThis(This node) {
+ out("this");
+ }
+
+ visitVariableDeclaration(VariableDeclaration decl) {
+ out(localNamer.getName(decl.name));
+ }
+
+ visitParameter(Parameter param) {
+ out(localNamer.getName(param.name));
+ }
+
+ bool isDigit(int charCode) {
+ return charCodes.$0 <= charCode && charCode <= charCodes.$9;
+ }
+
+ bool isValidJavaScriptId(String field) {
+ if (field.length < 3) return false;
+ // Ignore the leading and trailing string-delimiter.
+ for (int i = 1; i < field.length - 1; i++) {
+ // TODO(floitsch): allow more characters.
+ int charCode = field.codeUnitAt(i);
+ if (!(charCodes.$a <= charCode && charCode <= charCodes.$z ||
+ charCodes.$A <= charCode && charCode <= charCodes.$Z ||
+ charCode == charCodes.$$ ||
+ charCode == charCodes.$_ ||
+ i != 1 && isDigit(charCode))) {
+ return false;
+ }
+ }
+ // TODO(floitsch): normally we should also check that the field is not a
+ // reserved word. We don't generate fields with reserved word names except
+ // for 'super'.
+ if (field == '"super"') return false;
+ return true;
+ }
+
+ visitAccess(PropertyAccess access) {
+ visitNestedExpression(access.receiver, CALL,
+ newInForInit: inForInit,
+ newAtStatementBegin: atStatementBegin);
+ Node selector = access.selector;
+ if (selector is LiteralString) {
+ LiteralString selectorString = selector;
+ String fieldWithQuotes = selectorString.value;
+ if (isValidJavaScriptId(fieldWithQuotes)) {
+ if (access.receiver is LiteralNumber) out(" ");
+ out(".");
+ out(fieldWithQuotes.substring(1, fieldWithQuotes.length - 1));
+ return;
+ }
+ }
+ out("[");
+ visitNestedExpression(selector, EXPRESSION,
+ newInForInit: false, newAtStatementBegin: false);
+ out("]");
+ }
+
+ visitNamedFunction(NamedFunction namedFunction) {
+ VarCollector vars = new VarCollector();
+ vars.visitNamedFunction(namedFunction);
+ functionOut(namedFunction.function, namedFunction.name, vars);
+ }
+
+ visitFun(Fun fun) {
+ VarCollector vars = new VarCollector();
+ vars.visitFun(fun);
+ functionOut(fun, null, vars);
+ }
+
+ visitLiteralBool(LiteralBool node) {
+ out(node.value ? "true" : "false");
+ }
+
+ visitLiteralString(LiteralString node) {
+ out(node.value);
+ }
+
+ visitLiteralNumber(LiteralNumber node) {
+ int charCode = node.value.codeUnitAt(0);
+ if (charCode == charCodes.$MINUS && lastCharCode == charCodes.$MINUS) {
+ out(" ");
+ }
+ out(node.value);
+ }
+
+ visitLiteralNull(LiteralNull node) {
+ out("null");
+ }
+
+ visitArrayInitializer(ArrayInitializer node) {
+ out("[");
+ List<Expression> elements = node.elements;
+ for (int i = 0; i < elements.length; i++) {
+ Expression element = elements[i];
+ if (element is ArrayHole) {
+ // Note that array holes must have a trailing "," even if they are
+ // in last position. Otherwise `[,]` (having length 1) would become
+ // equal to `[]` (the empty array)
+ // and [1,,] (array with 1 and a hole) would become [1,] = [1].
+ out(",");
+ continue;
+ }
+ if (i != 0) spaceOut();
+ visitNestedExpression(element, ASSIGNMENT,
+ newInForInit: false, newAtStatementBegin: false);
+ // We can skip the trailing "," for the last element (since it's not
+ // an array hole).
+ if (i != elements.length - 1) out(",");
+ }
+ out("]");
+ }
+
+ visitArrayHole(ArrayHole node) {
+ throw "Unreachable";
+ }
+
+ visitObjectInitializer(ObjectInitializer node) {
+ // Print all the properties on one line until we see a function-valued
+ // property. Ideally, we would use a proper pretty-printer to make the
+ // decision based on layout.
+ List<Property> properties = node.properties;
+ out("{");
+ indentMore();
+ for (int i = 0; i < properties.length; i++) {
+ Expression value = properties[i].value;
+ if (i != 0) {
+ out(",");
+ if (node.isOneLiner) spaceOut();
+ }
+ if (!node.isOneLiner) {
+ forceLine();
+ indent();
+ }
+ visit(properties[i]);
+ }
+ indentLess();
+ if (!node.isOneLiner && !properties.isEmpty) {
+ lineOut();
+ indent();
+ }
+ out("}");
+ }
+
+ visitProperty(Property node) {
+ if (node.name is LiteralString) {
+ LiteralString nameString = node.name;
+ String name = nameString.value;
+ if (isValidJavaScriptId(name)) {
+ out(name.substring(1, name.length - 1));
+ } else {
+ out(name);
+ }
+ } else {
+ assert(node.name is LiteralNumber);
+ LiteralNumber nameNumber = node.name;
+ out(nameNumber.value);
+ }
+ out(":");
+ spaceOut();
+ visitNestedExpression(node.value, ASSIGNMENT,
+ newInForInit: false, newAtStatementBegin: false);
+ }
+
+ visitRegExpLiteral(RegExpLiteral node) {
+ out(node.pattern);
+ }
+
+ visitLiteralExpression(LiteralExpression node) {
+ String template = node.template;
+ List<Expression> inputs = node.inputs;
+
+ List<String> parts = template.split('#');
+ int inputsLength = inputs == null ? 0 : inputs.length;
+ if (parts.length != inputsLength + 1) {
+ context.error('Wrong number of arguments for JS: $template');
+ }
+ // Code that uses JS must take care of operator precedences, and
+ // put parenthesis if needed.
+ out(parts[0]);
+ for (int i = 0; i < inputsLength; i++) {
+ visit(inputs[i]);
+ out(parts[i + 1]);
+ }
+ }
+
+ visitLiteralStatement(LiteralStatement node) {
+ outLn(node.code);
+ }
+
+ visitInterpolatedNode(InterpolatedNode node) {
+ out('#${node.nameOrPosition}');
+ }
+
+ visitInterpolatedExpression(InterpolatedExpression node) =>
+ visitInterpolatedNode(node);
+
+ visitInterpolatedLiteral(InterpolatedLiteral node) =>
+ visitInterpolatedNode(node);
+
+ visitInterpolatedParameter(InterpolatedParameter node) =>
+ visitInterpolatedNode(node);
+
+ visitInterpolatedSelector(InterpolatedSelector node) =>
+ visitInterpolatedNode(node);
+
+ visitInterpolatedStatement(InterpolatedStatement node) {
+ outLn('#${node.nameOrPosition}');
+ }
+
+ visitInterpolatedDeclaration(InterpolatedDeclaration node) {
+ visitInterpolatedNode(node);
+ }
+
+ void visitComment(Comment node) {
+ if (shouldCompressOutput) return;
+ String comment = node.comment.trim();
+ if (comment.isEmpty) return;
+ for (var line in comment.split('\n')) {
+ if (comment.startsWith('//')) {
+ outIndentLn(line.trim());
+ } else {
+ outIndentLn('// ${line.trim()}');
+ }
+ }
+ }
+
+ void visitAwait(Await node) {
+ out("await ");
+ visit(node.expression);
+ }
+}
+
+
+class OrderedSet<T> {
+ final Set<T> set;
+ final List<T> list;
+
+ OrderedSet() : set = new Set<T>(), list = <T>[];
+
+ void add(T x) {
+ if (!set.contains(x)) {
+ set.add(x);
+ list.add(x);
+ }
+ }
+
+ void forEach(void fun(T x)) {
+ list.forEach(fun);
+ }
+}
+
+// Collects all the var declarations in the function. We need to do this in a
+// separate pass because JS vars are lifted to the top of the function.
+class VarCollector extends BaseVisitor {
+ bool nested;
+ final OrderedSet<String> vars;
+ final OrderedSet<String> params;
+
+ VarCollector() : nested = false,
+ vars = new OrderedSet<String>(),
+ params = new OrderedSet<String>();
+
+ void forEachVar(void fn(String v)) => vars.forEach(fn);
+ void forEachParam(void fn(String p)) => params.forEach(fn);
+
+ void collectVarsInFunction(Fun fun) {
+ if (!nested) {
+ nested = true;
+ if (fun.params != null) {
+ for (int i = 0; i < fun.params.length; i++) {
+ params.add(fun.params[i].name);
+ }
+ }
+ visitBlock(fun.body);
+ nested = false;
+ }
+ }
+
+ void visitFunctionDeclaration(FunctionDeclaration declaration) {
+ // Note that we don't bother collecting the name of the function.
+ collectVarsInFunction(declaration.function);
+ }
+
+ void visitNamedFunction(NamedFunction namedFunction) {
+ // Note that we don't bother collecting the name of the function.
+ collectVarsInFunction(namedFunction.function);
+ }
+
+ void visitFun(Fun fun) {
+ collectVarsInFunction(fun);
+ }
+
+ void visitThis(This node) {}
+
+ void visitVariableDeclaration(VariableDeclaration decl) {
+ if (decl.allowRename) vars.add(decl.name);
+ }
+}
+
+
+/**
+ * Returns true, if the given node must be wrapped into braces when used
+ * as then-statement in an [If] that has an else branch.
+ */
+class DanglingElseVisitor extends BaseVisitor<bool> {
+ JavaScriptPrintingContext context;
+
+ DanglingElseVisitor(this.context);
+
+ bool visitProgram(Program node) => false;
+
+ bool visitNode(Statement node) {
+ context.error("Forgot node: $node");
+ return null;
+ }
+
+ bool visitBlock(Block node) => false;
+ bool visitExpressionStatement(ExpressionStatement node) => false;
+ bool visitEmptyStatement(EmptyStatement node) => false;
+ bool visitIf(If node) {
+ if (!node.hasElse) return true;
+ return node.otherwise.accept(this);
+ }
+ bool visitFor(For node) => node.body.accept(this);
+ bool visitForIn(ForIn node) => node.body.accept(this);
+ bool visitWhile(While node) => node.body.accept(this);
+ bool visitDo(Do node) => false;
+ bool visitContinue(Continue node) => false;
+ bool visitBreak(Break node) => false;
+ bool visitReturn(Return node) => false;
+ bool visitThrow(Throw node) => false;
+ bool visitTry(Try node) {
+ if (node.finallyPart != null) {
+ return node.finallyPart.accept(this);
+ } else {
+ return node.catchPart.accept(this);
+ }
+ }
+ bool visitCatch(Catch node) => node.body.accept(this);
+ bool visitSwitch(Switch node) => false;
+ bool visitCase(Case node) => false;
+ bool visitDefault(Default node) => false;
+ bool visitFunctionDeclaration(FunctionDeclaration node) => false;
+ bool visitLabeledStatement(LabeledStatement node)
+ => node.body.accept(this);
+ bool visitLiteralStatement(LiteralStatement node) => true;
+
+ bool visitExpression(Expression node) => false;
+}
+
+
+abstract class LocalNamer {
+ String getName(String oldName);
+ String declareVariable(String oldName);
+ String declareParameter(String oldName);
+ void enterScope(VarCollector vars);
+ void leaveScope();
+}
+
+
+class IdentityNamer implements LocalNamer {
+ String getName(String oldName) => oldName;
+ String declareVariable(String oldName) => oldName;
+ String declareParameter(String oldName) => oldName;
+ void enterScope(VarCollector vars) {}
+ void leaveScope() {}
+}
+
+
+class MinifyRenamer implements LocalNamer {
+ final List<Map<String, String>> maps = [];
+ final List<int> parameterNumberStack = [];
+ final List<int> variableNumberStack = [];
+ int parameterNumber = 0;
+ int variableNumber = 0;
+
+ MinifyRenamer();
+
+ void enterScope(VarCollector vars) {
+ maps.add(new Map<String, String>());
+ variableNumberStack.add(variableNumber);
+ parameterNumberStack.add(parameterNumber);
+ vars.forEachVar(declareVariable);
+ vars.forEachParam(declareParameter);
+ }
+
+ void leaveScope() {
+ maps.removeLast();
+ variableNumber = variableNumberStack.removeLast();
+ parameterNumber = parameterNumberStack.removeLast();
+ }
+
+ String getName(String oldName) {
+ // Go from inner scope to outer looking for mapping of name.
+ for (int i = maps.length - 1; i >= 0; i--) {
+ var map = maps[i];
+ var replacement = map[oldName];
+ if (replacement != null) return replacement;
+ }
+ return oldName;
+ }
+
+ static const LOWER_CASE_LETTERS = 26;
+ static const LETTERS = LOWER_CASE_LETTERS;
+ static const DIGITS = 10;
+
+ static int nthLetter(int n) {
+ return (n < LOWER_CASE_LETTERS) ?
+ charCodes.$a + n :
+ charCodes.$A + n - LOWER_CASE_LETTERS;
+ }
+
+ // Parameters go from a to z and variables go from z to a. This makes each
+ // argument list and each top-of-function var declaration look similar and
+ // helps gzip compress the file. If we have more than 26 arguments and
+ // variables then we meet somewhere in the middle of the alphabet. After
+ // that we give up trying to be nice to the compression algorithm and just
+ // use the same namespace for arguments and variables, starting with A, and
+ // moving on to a0, a1, etc.
+ String declareVariable(String oldName) {
+ if (avoidRenaming(oldName)) return oldName;
+ var newName;
+ if (variableNumber + parameterNumber < LOWER_CASE_LETTERS) {
+ // Variables start from z and go backwards, for better gzipability.
+ newName = getNameNumber(oldName, LOWER_CASE_LETTERS - 1 - variableNumber);
+ } else {
+ // After 26 variables and parameters we allocate them in the same order.
+ newName = getNameNumber(oldName, variableNumber + parameterNumber);
+ }
+ variableNumber++;
+ return newName;
+ }
+
+ String declareParameter(String oldName) {
+ if (avoidRenaming(oldName)) return oldName;
+ var newName;
+ if (variableNumber + parameterNumber < LOWER_CASE_LETTERS) {
+ newName = getNameNumber(oldName, parameterNumber);
+ } else {
+ newName = getNameNumber(oldName, variableNumber + parameterNumber);
+ }
+ parameterNumber++;
+ return newName;
+ }
+
+ bool avoidRenaming(String oldName) {
+ // Variables of this $form$ are used in pattern matching the message of JS
+ // exceptions, so should not be renamed.
+ // TODO(sra): Introduce a way for indicating in the JS text which variables
+ // should not be renamed.
+ return oldName.startsWith(r'$') && oldName.endsWith(r'$');
+ }
+
+ String getNameNumber(String oldName, int n) {
+ if (maps.isEmpty) return oldName;
+
+ String newName;
+ if (n < LETTERS) {
+ // Start naming variables a, b, c, ..., z, A, B, C, ..., Z.
+ newName = new String.fromCharCodes([nthLetter(n)]);
+ } else {
+ // Then name variables a0, a1, a2, ..., a9, b0, b1, ..., Z9, aa0, aa1, ...
+ // For all functions with fewer than 500 locals this is just as compact
+ // as using aa, ab, etc. but avoids clashes with keywords.
+ n -= LETTERS;
+ int digit = n % DIGITS;
+ n ~/= DIGITS;
+ int alphaChars = 1;
+ int nameSpaceSize = LETTERS;
+ // Find out whether we should use the 1-character namespace (size 52), the
+ // 2-character namespace (size 52*52), etc.
+ while (n >= nameSpaceSize) {
+ n -= nameSpaceSize;
+ alphaChars++;
+ nameSpaceSize *= LETTERS;
+ }
+ var codes = <int>[];
+ for (var i = 0; i < alphaChars; i++) {
+ nameSpaceSize ~/= LETTERS;
+ codes.add(nthLetter((n ~/ nameSpaceSize) % LETTERS));
+ }
+ codes.add(charCodes.$0 + digit);
+ newName = new String.fromCharCodes(codes);
+ }
+ assert(new RegExp(r'[a-zA-Z][a-zA-Z0-9]*').hasMatch(newName));
+ maps.last[oldName] = newName;
+ return newName;
+ }
+}
diff --git a/pkg/js_ast/lib/src/template.dart b/pkg/js_ast/lib/src/template.dart
new file mode 100644
index 0000000..eb4089a
--- /dev/null
+++ b/pkg/js_ast/lib/src/template.dart
@@ -0,0 +1,754 @@
+// 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.
+
+part of js_ast;
+
+class TemplateManager {
+ Map<String, Template> expressionTemplates = new Map<String, Template>();
+ Map<String, Template> statementTemplates = new Map<String, Template>();
+
+ TemplateManager();
+
+
+ Template lookupExpressionTemplate(String source) {
+ return expressionTemplates[source];
+ }
+
+ Template defineExpressionTemplate(String source, Node ast) {
+ Template template =
+ new Template(source, ast, isExpression: true, forceCopy: false);
+ expressionTemplates[source] = template;
+ return template;
+ }
+
+ Template lookupStatementTemplate(String source) {
+ return statementTemplates[source];
+ }
+
+ Template defineStatementTemplate(String source, Node ast) {
+ Template template =
+ new Template(source, ast, isExpression: false, forceCopy: false);
+ statementTemplates[source] = template;
+ return template;
+ }
+}
+
+/**
+ * A Template is created with JavaScript AST containing placeholders (interface
+ * InterpolatedNode). The [instantiate] method creates an AST that looks like
+ * the original with the placeholders replaced by the arguments to
+ * [instantiate].
+ */
+class Template {
+ final String source;
+ final bool isExpression;
+ final bool forceCopy;
+ final Node ast;
+
+ Instantiator instantiator;
+
+ int positionalArgumentCount = -1;
+
+ // Null, unless there are named holes.
+ List<String> holeNames;
+ bool get isPositional => holeNames == null;
+
+ Template(this.source, this.ast,
+ {this.isExpression: true, this.forceCopy: false}) {
+ _compile();
+ }
+
+ Template.withExpressionResult(this.ast)
+ : source = null, isExpression = true, forceCopy = false {
+ assert(ast is Expression);
+ assert(_checkNoPlaceholders());
+ positionalArgumentCount = 0;
+ instantiator = (arguments) => ast;
+ }
+
+ Template.withStatementResult(this.ast)
+ : source = null, isExpression = false, forceCopy = false {
+ assert(ast is Statement);
+ assert(_checkNoPlaceholders());
+ positionalArgumentCount = 0;
+ instantiator = (arguments) => ast;
+ }
+
+ bool _checkNoPlaceholders() {
+ InstantiatorGeneratorVisitor generator =
+ new InstantiatorGeneratorVisitor(false);
+ generator.compile(ast);
+ return generator.analysis.count == 0;
+ }
+
+ void _compile() {
+ InstantiatorGeneratorVisitor generator =
+ new InstantiatorGeneratorVisitor(forceCopy);
+ instantiator = generator.compile(ast);
+ positionalArgumentCount = generator.analysis.count;
+ Set<String> names = generator.analysis.holeNames;
+ holeNames = names.toList(growable:false);
+ }
+
+ /// Instantiates the template with the given [arguments].
+ ///
+ /// This method fills in the holes with the given arguments. The [arguments]
+ /// must be either a [List] or a [Map].
+ Node instantiate(var arguments) {
+ if (arguments is List) {
+ if (arguments.length != positionalArgumentCount) {
+ throw 'Wrong number of template arguments, given ${arguments.length}, '
+ 'expected $positionalArgumentCount';
+ }
+ return instantiator(arguments);
+ }
+ assert(arguments is Map);
+ if (holeNames.length < arguments.length) {
+ // This search is in O(n), but we only do it in case of an error, and the
+ // number of holes should be quite limited.
+ String unusedNames =
+ arguments.keys.where((name) => !holeNames.contains(name)).join(", ");
+ throw "Template arguments has unused mappings: $unusedNames";
+ }
+ if (!holeNames.every((String name) => arguments.containsKey(name))) {
+ String notFound =
+ holeNames.where((name) => !arguments.containsKey(name)).join(", ");
+ throw "Template arguments is missing mappings for: $notFound";
+ }
+ return instantiator(arguments);
+ }
+}
+
+/**
+ * An Instantiator is a Function that generates a JS AST tree or List of
+ * trees. [arguments] is a List for positional templates, or Map for
+ * named templates.
+ */
+typedef Node Instantiator(var arguments);
+
+
+/**
+ * InstantiatorGeneratorVisitor compiles a template. This class compiles a tree
+ * containing [InterpolatedNode]s into a function that will create a copy of the
+ * tree with the interpolated nodes substituted with provided values.
+ */
+class InstantiatorGeneratorVisitor implements NodeVisitor<Instantiator> {
+
+ final bool forceCopy;
+
+ InterpolatedNodeAnalysis analysis = new InterpolatedNodeAnalysis();
+
+ /**
+ * The entire tree is cloned if [forceCopy] is true.
+ */
+ InstantiatorGeneratorVisitor(this.forceCopy);
+
+ Instantiator compile(Node node) {
+ analysis.visit(node);
+ Instantiator result = visit(node);
+ return result;
+ }
+
+ static error(String message) {
+ throw message;
+ }
+
+ static Instantiator same(Node node) => (arguments) => node;
+ static Node makeNull(arguments) => null;
+
+ Instantiator visit(Node node) {
+ if (forceCopy || analysis.containsInterpolatedNodes(node)) {
+ return node.accept(this);
+ }
+ return same(node);
+ }
+
+ Instantiator visitNullable(Node node) {
+ if (node == null) return makeNull;
+ return visit(node);
+ }
+
+ Instantiator visitSplayable(Node node) {
+ // TODO(sra): Process immediate [InterpolatedNode]s, permitting splaying.
+ return visit(node);
+ }
+
+ Instantiator visitNode(Node node) {
+ throw 'Unimplemented InstantiatorGeneratorVisitor for $node';
+ }
+
+ static RegExp identiferRE = new RegExp(r'^[A-Za-z_$][A-Za-z_$0-9]*$');
+
+ static Expression convertStringToVariableUse(String value) {
+ assert(identiferRE.hasMatch(value));
+ return new VariableUse(value);
+ }
+
+ static Expression convertStringToVariableDeclaration(String value) {
+ assert(identiferRE.hasMatch(value));
+ return new VariableDeclaration(value);
+ }
+
+ Instantiator visitInterpolatedExpression(InterpolatedExpression node) {
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+ if (value is Expression) return value;
+ if (value is String) return convertStringToVariableUse(value);
+ error('Interpolated value #$nameOrPosition is not an Expression: $value');
+ };
+ }
+
+ Instantiator visitInterpolatedDeclaration(InterpolatedDeclaration node) {
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+ if (value is Declaration) return value;
+ if (value is String) return convertStringToVariableDeclaration(value);
+ error('Interpolated value #$nameOrPosition is not a declaration: $value');
+ };
+ }
+
+ Instantiator visitSplayableExpression(Node node) {
+ if (node is InterpolatedExpression) {
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+ Expression toExpression(item) {
+ if (item is Expression) return item;
+ if (item is String) return convertStringToVariableUse(item);
+ return error('Interpolated value #$nameOrPosition is not '
+ 'an Expression or List of Expressions: $value');
+ }
+ if (value is Iterable) return value.map(toExpression);
+ return toExpression(value);
+ };
+ }
+ return visit(node);
+ }
+
+ Instantiator visitInterpolatedLiteral(InterpolatedLiteral node) {
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+ if (value is Literal) return value;
+ error('Interpolated value #$nameOrPosition is not a Literal: $value');
+ };
+ }
+
+ Instantiator visitInterpolatedParameter(InterpolatedParameter node) {
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+
+ Parameter toParameter(item) {
+ if (item is Parameter) return item;
+ if (item is String) return new Parameter(item);
+ return error('Interpolated value #$nameOrPosition is not a Parameter or'
+ ' List of Parameters: $value');
+ }
+ if (value is Iterable) return value.map(toParameter);
+ return toParameter(value);
+ };
+ }
+
+ Instantiator visitInterpolatedSelector(InterpolatedSelector node) {
+ // A selector is an expression, as in `a[selector]`.
+ // A String argument converted into a LiteralString, so `a.#` with argument
+ // 'foo' generates `a["foo"]` which prints as `a.foo`.
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+ if (value is Expression) return value;
+ if (value is String) return new LiteralString('"$value"');
+ error('Interpolated value #$nameOrPosition is not a selector: $value');
+ };
+ }
+
+ Instantiator visitInterpolatedStatement(InterpolatedStatement node) {
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+ if (value is Node) return value.toStatement();
+ error('Interpolated value #$nameOrPosition is not a Statement: $value');
+ };
+ }
+
+ Instantiator visitSplayableStatement(Node node) {
+ if (node is InterpolatedStatement) {
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+ Statement toStatement(item) {
+ if (item is Statement) return item;
+ if (item is Expression) return item.toStatement();;
+ return error('Interpolated value #$nameOrPosition is not '
+ 'a Statement or List of Statements: $value');
+ }
+ if (value is Iterable) return value.map(toStatement);
+ return toStatement(value);
+ };
+ }
+ return visit(node);
+ }
+
+ Instantiator visitProgram(Program node) {
+ List instantiators = node.body.map(visitSplayableStatement).toList();
+ return (arguments) {
+ List<Statement> statements = <Statement>[];
+ void add(node) {
+ if (node is EmptyStatement) return;
+ if (node is Iterable) {
+ statements.addAll(node);
+ } else {
+ statements.add(node.toStatement());
+ }
+ }
+ for (Instantiator instantiator in instantiators) {
+ add(instantiator(arguments));
+ }
+ return new Program(statements);
+ };
+ }
+
+ Instantiator visitBlock(Block node) {
+ List instantiators = node.statements.map(visitSplayableStatement).toList();
+ return (arguments) {
+ List<Statement> statements = <Statement>[];
+ void add(node) {
+ if (node is EmptyStatement) return;
+ if (node is Iterable) {
+ statements.addAll(node);
+ } else if (node is Block) {
+ statements.addAll(node.statements);
+ } else {
+ statements.add(node.toStatement());
+ }
+ }
+ for (Instantiator instantiator in instantiators) {
+ add(instantiator(arguments));
+ }
+ return new Block(statements);
+ };
+ }
+
+ Instantiator visitExpressionStatement(ExpressionStatement node) {
+ Instantiator buildExpression = visit(node.expression);
+ return (arguments) {
+ return buildExpression(arguments).toStatement();
+ };
+ }
+
+ Instantiator visitEmptyStatement(EmptyStatement node) =>
+ (arguments) => new EmptyStatement();
+
+ Instantiator visitIf(If node) {
+ if (node.condition is InterpolatedExpression) {
+ return visitIfConditionalCompilation(node);
+ } else {
+ return visitIfNormal(node);
+ }
+ }
+
+ Instantiator visitIfConditionalCompilation(If node) {
+ // Special version of visitInterpolatedExpression that permits bools.
+ compileCondition(InterpolatedExpression node) {
+ var nameOrPosition = node.nameOrPosition;
+ return (arguments) {
+ var value = arguments[nameOrPosition];
+ if (value is bool) return value;
+ if (value is Expression) return value;
+ if (value is String) return convertStringToVariableUse(value);;
+ error('Interpolated value #$nameOrPosition '
+ 'is not an Expression: $value');
+ };
+ }
+ var makeCondition = compileCondition(node.condition);
+ Instantiator makeThen = visit(node.then);
+ Instantiator makeOtherwise = visit(node.otherwise);
+ return (arguments) {
+ var condition = makeCondition(arguments);
+ if (condition is bool) {
+ if (condition == true) {
+ return makeThen(arguments);
+ } else {
+ return makeOtherwise(arguments);
+ }
+ }
+ return new If(
+ condition,
+ makeThen(arguments),
+ makeOtherwise(arguments));
+ };
+ }
+
+ Instantiator visitIfNormal(If node) {
+ Instantiator makeCondition = visit(node.condition);
+ Instantiator makeThen = visit(node.then);
+ Instantiator makeOtherwise = visit(node.otherwise);
+ return (arguments) {
+ return new If(
+ makeCondition(arguments),
+ makeThen(arguments),
+ makeOtherwise(arguments));
+ };
+ }
+
+ Instantiator visitFor(For node) {
+ Instantiator makeInit = visitNullable(node.init);
+ Instantiator makeCondition = visitNullable(node.condition);
+ Instantiator makeUpdate = visitNullable(node.update);
+ Instantiator makeBody = visit(node.body);
+ return (arguments) {
+ return new For(
+ makeInit(arguments), makeCondition(arguments), makeUpdate(arguments),
+ makeBody(arguments));
+ };
+ }
+
+ Instantiator visitForIn(ForIn node) {
+ Instantiator makeLeftHandSide = visit(node.leftHandSide);
+ Instantiator makeObject = visit(node.object);
+ Instantiator makeBody = visit(node.body);
+ return (arguments) {
+ return new ForIn(
+ makeLeftHandSide(arguments),
+ makeObject(arguments),
+ makeBody(arguments));
+ };
+ }
+
+ TODO(String name) {
+ throw new UnimplementedError('$this.$name');
+ }
+
+ Instantiator visitWhile(While node) {
+ Instantiator makeCondition = visit(node.condition);
+ Instantiator makeBody = visit(node.body);
+ return (arguments) {
+ return new While(makeCondition(arguments), makeBody(arguments));
+ };
+ }
+
+ Instantiator visitDo(Do node) {
+ Instantiator makeBody = visit(node.body);
+ Instantiator makeCondition = visit(node.condition);
+ return (arguments) {
+ return new Do(makeBody(arguments), makeCondition(arguments));
+ };
+ }
+
+ Instantiator visitContinue(Continue node) =>
+ (arguments) => new Continue(node.targetLabel);
+
+ Instantiator visitBreak(Break node) =>
+ (arguments) => new Break(node.targetLabel);
+
+ Instantiator visitReturn(Return node) {
+ Instantiator makeExpression = visitNullable(node.value);
+ return (arguments) => new Return(makeExpression(arguments));
+ }
+
+ Instantiator visitDartYield(DartYield node) {
+ Instantiator makeExpression = visit(node.expression);
+ return (arguments) => new DartYield(makeExpression(arguments), node.hasStar);
+ }
+
+ Instantiator visitThrow(Throw node) {
+ Instantiator makeExpression = visit(node.expression);
+ return (arguments) => new Throw(makeExpression(arguments));
+ }
+
+ Instantiator visitTry(Try node) {
+ Instantiator makeBody = visit(node.body);
+ Instantiator makeCatch = visitNullable(node.catchPart);
+ Instantiator makeFinally = visitNullable(node.finallyPart);
+ return (arguments) => new Try(
+ makeBody(arguments), makeCatch(arguments), makeFinally(arguments));
+ }
+
+ Instantiator visitCatch(Catch node) {
+ Instantiator makeDeclaration = visit(node.declaration);
+ Instantiator makeBody = visit(node.body);
+ return (arguments) => new Catch(
+ makeDeclaration(arguments), makeBody(arguments));
+ }
+
+ Instantiator visitSwitch(Switch node) {
+ Instantiator makeKey = visit(node.key);
+ Iterable<Instantiator> makeCases = node.cases.map(visit);
+ return (arguments) {
+ return new Switch(makeKey(arguments),
+ makeCases.map((Instantiator makeCase) => makeCase(arguments))
+ .toList());
+ };
+ }
+
+ Instantiator visitCase(Case node) {
+ Instantiator makeExpression = visit(node.expression);
+ Instantiator makeBody = visit(node.body);
+ return (arguments) {
+ return new Case(makeExpression(arguments), makeBody(arguments));
+ };
+ }
+
+ Instantiator visitDefault(Default node) {
+ Instantiator makeBody = visit(node.body);
+ return (arguments) {
+ return new Default(makeBody(arguments));
+ };
+ }
+
+ Instantiator visitFunctionDeclaration(FunctionDeclaration node) {
+ Instantiator makeName = visit(node.name);
+ Instantiator makeFunction = visit(node.function);
+ return (arguments) =>
+ new FunctionDeclaration(makeName(arguments), makeFunction(arguments));
+ }
+
+ Instantiator visitLabeledStatement(LabeledStatement node) {
+ Instantiator makeBody = visit(node.body);
+ return (arguments) => new LabeledStatement(node.label, makeBody(arguments));
+ }
+
+ Instantiator visitLiteralStatement(LiteralStatement node) =>
+ TODO('visitLiteralStatement');
+ Instantiator visitLiteralExpression(LiteralExpression node) =>
+ TODO('visitLiteralExpression');
+
+ Instantiator visitVariableDeclarationList(VariableDeclarationList node) {
+ List<Instantiator> declarationMakers =
+ node.declarations.map(visit).toList();
+ return (arguments) {
+ List<VariableInitialization> declarations = <VariableInitialization>[];
+ for (Instantiator instantiator in declarationMakers) {
+ var result = instantiator(arguments);
+ declarations.add(result);
+ }
+ return new VariableDeclarationList(declarations);
+ };
+ }
+
+ Instantiator visitAssignment(Assignment node) {
+ Instantiator makeLeftHandSide = visit(node.leftHandSide);
+ String op = node.op;
+ Instantiator makeValue = visitNullable(node.value);
+ return (arguments) {
+ return new Assignment.compound(
+ makeLeftHandSide(arguments),
+ op,
+ makeValue(arguments));
+ };
+ }
+
+ Instantiator visitVariableInitialization(VariableInitialization node) {
+ Instantiator makeDeclaration = visit(node.declaration);
+ Instantiator makeValue = visitNullable(node.value);
+ return (arguments) {
+ return new VariableInitialization(
+ makeDeclaration(arguments), makeValue(arguments));
+ };
+ }
+
+ Instantiator visitConditional(Conditional cond) {
+ Instantiator makeCondition = visit(cond.condition);
+ Instantiator makeThen = visit(cond.then);
+ Instantiator makeOtherwise = visit(cond.otherwise);
+ return (arguments) => new Conditional(
+ makeCondition(arguments),
+ makeThen(arguments),
+ makeOtherwise(arguments));
+ }
+
+ Instantiator visitNew(New node) =>
+ handleCallOrNew(node, (target, arguments) => new New(target, arguments));
+
+ Instantiator visitCall(Call node) =>
+ handleCallOrNew(node, (target, arguments) => new Call(target, arguments));
+
+ Instantiator handleCallOrNew(Call node, finish(target, arguments)) {
+ Instantiator makeTarget = visit(node.target);
+ Iterable<Instantiator> argumentMakers =
+ node.arguments.map(visitSplayableExpression).toList();
+
+ // TODO(sra): Avoid copying call arguments if no interpolation or forced
+ // copying.
+ return (arguments) {
+ Node target = makeTarget(arguments);
+ List<Expression> callArguments = <Expression>[];
+ for (Instantiator instantiator in argumentMakers) {
+ var result = instantiator(arguments);
+ if (result is Iterable) {
+ callArguments.addAll(result);
+ } else {
+ callArguments.add(result);
+ }
+ }
+ return finish(target, callArguments.toList(growable: false));
+ };
+ }
+
+ Instantiator visitBinary(Binary node) {
+ Instantiator makeLeft = visit(node.left);
+ Instantiator makeRight = visit(node.right);
+ String op = node.op;
+ return (arguments) =>
+ new Binary(op, makeLeft(arguments), makeRight(arguments));
+ }
+
+ Instantiator visitPrefix(Prefix node) {
+ Instantiator makeOperand = visit(node.argument);
+ String op = node.op;
+ return (arguments) => new Prefix(op, makeOperand(arguments));
+ }
+
+ Instantiator visitPostfix(Postfix node) {
+ Instantiator makeOperand = visit(node.argument);
+ String op = node.op;
+ return (arguments) => new Postfix(op, makeOperand(arguments));
+ }
+
+ Instantiator visitVariableUse(VariableUse node) =>
+ (arguments) => new VariableUse(node.name);
+
+ Instantiator visitThis(This node) => (arguments) => new This();
+
+ Instantiator visitVariableDeclaration(VariableDeclaration node) =>
+ (arguments) => new VariableDeclaration(node.name);
+
+ Instantiator visitParameter(Parameter node) =>
+ (arguments) => new Parameter(node.name);
+
+ Instantiator visitAccess(PropertyAccess node) {
+ Instantiator makeReceiver = visit(node.receiver);
+ Instantiator makeSelector = visit(node.selector);
+ return (arguments) =>
+ new PropertyAccess(makeReceiver(arguments), makeSelector(arguments));
+ }
+
+ Instantiator visitNamedFunction(NamedFunction node) {
+ Instantiator makeDeclaration = visit(node.name);
+ Instantiator makeFunction = visit(node.function);
+ return (arguments) =>
+ new NamedFunction(makeDeclaration(arguments), makeFunction(arguments));
+ }
+
+ Instantiator visitFun(Fun node) {
+ List<Instantiator> paramMakers = node.params.map(visitSplayable).toList();
+ Instantiator makeBody = visit(node.body);
+ // TODO(sra): Avoid copying params if no interpolation or forced copying.
+ return (arguments) {
+ List<Parameter> params = <Parameter>[];
+ for (Instantiator instantiator in paramMakers) {
+ var result = instantiator(arguments);
+ if (result is Iterable) {
+ params.addAll(result);
+ } else {
+ params.add(result);
+ }
+ }
+ Statement body = makeBody(arguments);
+ return new Fun(params, body);
+ };
+ }
+
+ Instantiator visitLiteralBool(LiteralBool node) =>
+ (arguments) => new LiteralBool(node.value);
+
+ Instantiator visitLiteralString(LiteralString node) =>
+ (arguments) => new LiteralString(node.value);
+
+ Instantiator visitLiteralNumber(LiteralNumber node) =>
+ (arguments) => new LiteralNumber(node.value);
+
+ Instantiator visitLiteralNull(LiteralNull node) =>
+ (arguments) => new LiteralNull();
+
+ Instantiator visitArrayInitializer(ArrayInitializer node) {
+ // TODO(sra): Implement splicing?
+ List<Instantiator> elementMakers = node.elements
+ .map(visit)
+ .toList(growable: false);
+ return (arguments) {
+ List<Expression> elements = elementMakers
+ .map((Instantiator instantiator) => instantiator(arguments))
+ .toList(growable: false);
+ return new ArrayInitializer(elements);
+ };
+ }
+
+ Instantiator visitArrayHole(ArrayHole node) {
+ return (arguments) => new ArrayHole();
+ }
+
+ Instantiator visitObjectInitializer(ObjectInitializer node) {
+ List<Instantiator> propertyMakers =
+ node.properties.map(visitSplayable).toList();
+ bool isOneLiner = node.isOneLiner;
+ return (arguments) {
+ List<Property> properties = <Property>[];
+ for (Instantiator instantiator in propertyMakers) {
+ var result = instantiator(arguments);
+ if (result is Iterable) {
+ properties.addAll(result);
+ } else {
+ properties.add(result);
+ }
+ }
+ return new ObjectInitializer(properties, isOneLiner: isOneLiner);
+ };
+ }
+
+ Instantiator visitProperty(Property node) {
+ Instantiator makeName = visit(node.name);
+ Instantiator makeValue = visit(node.value);
+ return (arguments) {
+ return new Property(makeName(arguments), makeValue(arguments));
+ };
+ }
+
+ Instantiator visitRegExpLiteral(RegExpLiteral node) =>
+ (arguments) => new RegExpLiteral(node.pattern);
+
+ Instantiator visitComment(Comment node) => TODO('visitComment');
+
+ Instantiator visitAwait(Await node) {
+ Instantiator makeExpression = visit(node.expression);
+ return (arguments) {
+ return new Await(makeExpression(arguments));
+ };
+ }
+}
+
+/**
+ * InterpolatedNodeAnalysis determines which AST trees contain
+ * [InterpolatedNode]s, and the names of the named interpolated nodes.
+ */
+class InterpolatedNodeAnalysis extends BaseVisitor {
+ final Set<Node> containsInterpolatedNode = new Set<Node>();
+ final Set<String> holeNames = new Set<String>();
+ int count = 0;
+
+ InterpolatedNodeAnalysis();
+
+ bool containsInterpolatedNodes(Node node) =>
+ containsInterpolatedNode.contains(node);
+
+ void visit(Node node) {
+ node.accept(this);
+ }
+
+ void visitNode(Node node) {
+ int before = count;
+ node.visitChildren(this);
+ if (count != before) containsInterpolatedNode.add(node);
+ return null;
+ }
+
+ visitInterpolatedNode(InterpolatedNode node) {
+ containsInterpolatedNode.add(node);
+ if (node.isNamed) holeNames.add(node.nameOrPosition);
+ ++count;
+ }
+}
diff --git a/pkg/js_ast/pubspec.yaml b/pkg/js_ast/pubspec.yaml
new file mode 100644
index 0000000..ce29268
--- /dev/null
+++ b/pkg/js_ast/pubspec.yaml
@@ -0,0 +1,9 @@
+name: js_ast
+version: 0.0.0
+author: Dart Team <misc@dartlang.org>
+description: Library creating and printing JavaScript ASTs.
+homepage: http://www.dartlang.org
+dev_dependencies:
+ unittest: ">=0.9.0 <0.10.0"
+environment:
+ sdk: ">=0.8.10+6 <2.0.0"
diff --git a/pkg/mime/CHANGELOG.md b/pkg/mime/CHANGELOG.md
index eab1ae3..98abd3a 100644
--- a/pkg/mime/CHANGELOG.md
+++ b/pkg/mime/CHANGELOG.md
@@ -1,3 +1,13 @@
+# 0.9.3
+
+* Fixed erroneous behavior for listening and when pausing/resuming
+ stream of parts.
+
+# 0.9.2
+
+* Fixed erroneous behavior when pausing/canceling stream of parts but already
+ listened to one part.
+
# 0.9.1
* Handle parsing of MIME multipart content with no parts.
diff --git a/pkg/mime/README.md b/pkg/mime/README.md
new file mode 100644
index 0000000..dd69358
--- /dev/null
+++ b/pkg/mime/README.md
@@ -0,0 +1,48 @@
+#MIME type package
+
+Package for working with MIME type definitions and for processing
+streams of MIME multipart media types.
+
+##Determining the MIME type for a file
+
+The `MimeTypeResolver` class can be used to determine the MIME type of
+a file. It supports both using the extension of the file name and
+looking at magic bytes from the begining of the file.
+
+There is a builtin instance of `MimeTypeResolver` accessible through
+the top level function `lookupMimeType`. This builtin instance has
+the most common file name extensions and magic bytes registered.
+
+ print(lookupMimeType('test.html')); // Will print text/html
+ print(lookupMimeType('test', [0xFF, 0xD8])); // Will print image/jpeg
+ print(lookupMimeType('test.html', [0xFF, 0xD8])); // Will print image/jpeg
+
+You can build you own resolver by creating an instance of
+`MimeTypeResolver` and adding file name extensions and magic bytes
+using `addExtension` and `addMagicNumber`.
+
+##Processing MIME multipart media types
+
+The class `MimeMultipartTransformer` is used to process a `Stream` of
+bytes encoded using a MIME multipart media types encoding. The
+transformer provides a new `Stream` of `MimeMultipart` objects each of
+which have the headers and the content of each part. The content of a
+part is provided as a stream of bytes.
+
+Below is an example showing how to process an HTTP request and print
+the length of the content of each part.
+
+ // HTTP request with content type multipart/form-data.
+ HttpRequest request = ...;
+ // Determine the boundary form the content type header
+ String boundary = request.headers.contentType.parameters['boundary'];
+
+ // Process the body just calculating the length of each part.
+ request.transform(new MimeMultipartTransformer(boundary))
+ .map((part) => part.fold(0, (p, d) => p + d))
+ .listen((length) => print('Part with length $length'));
+
+Take a look at the `HttpBodyHandler` in the [http_server][1] package for
+handling different content types in a HTTP request.
+
+[1]: https://pub.dartlang.org/packages/http_server
diff --git a/pkg/mime/lib/src/bound_multipart_stream.dart b/pkg/mime/lib/src/bound_multipart_stream.dart
index a049b1d..ab06dab 100644
--- a/pkg/mime/lib/src/bound_multipart_stream.dart
+++ b/pkg/mime/lib/src/bound_multipart_stream.dart
@@ -74,6 +74,16 @@
final List<int> _headerField = [];
final List<int> _headerValue = [];
+ // The following states belong to `_controller`, state changes will not be
+ // immediately acted upon but rather only after the current
+ // `_multipartController` is done.
+ static const int _CONTROLLER_STATE_IDLE = 0;
+ static const int _CONTROLLER_STATE_ACTIVE = 1;
+ static const int _CONTROLLER_STATE_PAUSED = 2;
+ static const int _CONTROLLER_STATE_CANCELED = 3;
+
+ int _controllerState = _CONTROLLER_STATE_IDLE;
+
StreamController _controller;
Stream<MimeMultipart> get stream => _controller.stream;
@@ -95,15 +105,17 @@
_controller = new StreamController(
sync: true,
onPause: _pauseStream,
- onResume:_resumeStream,
+ onResume: _resumeStream,
onCancel: () {
- _subscription.cancel();
+ _controllerState = _CONTROLLER_STATE_CANCELED;
+ _tryPropagateControllerState();
},
onListen: () {
+ _controllerState = _CONTROLLER_STATE_ACTIVE;
_subscription = stream.listen(
(data) {
assert(_buffer == null);
- _pauseStream();
+ _subscription.pause();
_buffer = data;
_index = 0;
_parse();
@@ -120,13 +132,33 @@
}
void _resumeStream() {
- _subscription.resume();
+ assert (_controllerState == _CONTROLLER_STATE_PAUSED);
+ _controllerState = _CONTROLLER_STATE_ACTIVE;
+ _tryPropagateControllerState();
}
void _pauseStream() {
- _subscription.pause();
+ _controllerState = _CONTROLLER_STATE_PAUSED;
+ _tryPropagateControllerState();
}
+ void _tryPropagateControllerState() {
+ if (_multipartController == null) {
+ switch (_controllerState) {
+ case _CONTROLLER_STATE_ACTIVE:
+ if (_subscription.isPaused) _subscription.resume();
+ break;
+ case _CONTROLLER_STATE_PAUSED:
+ if (!_subscription.isPaused) _subscription.pause();
+ break;
+ case _CONTROLLER_STATE_CANCELED:
+ _subscription.cancel();
+ break;
+ default:
+ throw new StateError("This code should never be reached.");
+ }
+ }
+ }
void _parse() {
// Number of boundary bytes to artificially place before the supplied data.
@@ -171,9 +203,6 @@
boundaryPrefix = _boundaryIndex;
while ((_index < _buffer.length) && _state != _FAIL && _state != _DONE) {
- if (_multipartController != null && _multipartController.isPaused) {
- return;
- }
int byte;
if (_index < 0) {
byte = _boundary[boundaryPrefix + _index];
@@ -210,6 +239,7 @@
if (_multipartController != null) {
_multipartController.close();
_multipartController = null;
+ _tryPropagateControllerState();
}
_state = _HEADER_START;
break;
@@ -282,13 +312,11 @@
_expectByteValue(byte, CharCode.LF);
_multipartController = new StreamController(
sync: true,
- onPause: () {
- _pauseStream();
+ onListen: () {
+ if (_subscription.isPaused) _subscription.resume();
},
- onResume: () {
- _resumeStream();
- _parse();
- });
+ onPause: _subscription.pause,
+ onResume: _subscription.resume);
_controller.add(
new _MimeMultipart(_headers, _multipartController.stream));
_headers = null;
@@ -306,6 +334,8 @@
_index--;
}
_multipartController.close();
+ _multipartController = null;
+ _tryPropagateControllerState();
_boundaryIndex = 0;
_state = _BOUNDARY_ENDING;
}
@@ -335,6 +365,7 @@
if (_multipartController != null) {
_multipartController.close();
_multipartController = null;
+ _tryPropagateControllerState();
}
_state = _DONE;
break;
@@ -358,7 +389,7 @@
if (_index == _buffer.length) {
_buffer = null;
_index = null;
- _resumeStream();
+ _subscription.resume();
}
}
}
diff --git a/pkg/mime/pubspec.yaml b/pkg/mime/pubspec.yaml
index 7ca4669..2de7eca 100644
--- a/pkg/mime/pubspec.yaml
+++ b/pkg/mime/pubspec.yaml
@@ -1,5 +1,5 @@
name: mime
-version: 0.9.1
+version: 0.9.3
author: Dart Team <misc@dartlang.org>
description: Helper-package for working with MIME.
homepage: http://www.dartlang.org
diff --git a/pkg/mime/test/mime_multipart_transformer_test.dart b/pkg/mime/test/mime_multipart_transformer_test.dart
index 0008ff0..5038999 100644
--- a/pkg/mime/test/mime_multipart_transformer_test.dart
+++ b/pkg/mime/test/mime_multipart_transformer_test.dart
@@ -8,11 +8,34 @@
import "package:unittest/unittest.dart";
import "package:mime/mime.dart";
-void _testParse(String message,
- String boundary,
- [List<Map> expectedHeaders,
- List expectedParts,
- bool expectError = false]) {
+void _writeInChunks(List<int> data,
+ int chunkSize,
+ StreamController<List<int>> controller) {
+ if (chunkSize == -1) chunkSize = data.length;
+
+ int written = 0;
+ for (int pos = 0; pos < data.length; pos += chunkSize) {
+ int remaining = data.length - pos;
+ int writeLength = min(chunkSize, remaining);
+ controller.add(data.sublist(pos, pos + writeLength));
+ written += writeLength;
+ }
+ controller.close();
+}
+
+
+enum TestMode {
+ IMMEDIATE_LISTEN,
+ DELAY_LISTEN,
+ PAUSE_RESUME
+}
+
+void _runParseTest(String message,
+ String boundary,
+ TestMode mode,
+ [List<Map> expectedHeaders,
+ List expectedParts,
+ bool expectError = false]) {
Future testWrite(List<int> data, [int chunkSize = -1]) {
StreamController controller = new StreamController(sync: true);
@@ -26,12 +49,46 @@
if (expectedHeaders != null) {
expect(multipart.headers, equals(expectedHeaders[part]));
}
- futures.add(multipart.fold([], (buffer, data) => buffer..addAll(data))
- .then((data) {
- if (expectedParts[part] != null) {
- expect(data, equals(expectedParts[part].codeUnits));
- }
+ switch (mode) {
+ case TestMode.IMMEDIATE_LISTEN:
+ futures.add(multipart.fold([], (buffer, data) => buffer..addAll(data))
+ .then((data) {
+ if (expectedParts[part] != null) {
+ expect(data, equals(expectedParts[part].codeUnits));
+ }
+ }));
+ break;
+
+ case TestMode.DELAY_LISTEN:
+ futures.add(new Future(() {
+ return multipart.fold([], (buffer, data) => buffer..addAll(data))
+ .then((data) {
+ if (expectedParts[part] != null) {
+ expect(data, equals(expectedParts[part].codeUnits));
+ }
+ });
}));
+ break;
+
+ case TestMode.PAUSE_RESUME:
+ var completer = new Completer();
+ futures.add(completer.future);
+ var buffer = [];
+ var subscription;
+ subscription = multipart.listen(
+ (data) {
+ buffer.addAll(data);
+ subscription.pause();
+ new Future(() => subscription.resume());
+ },
+ onDone: () {
+ if (expectedParts[part] != null) {
+ expect(buffer, equals(expectedParts[part].codeUnits));
+ }
+ completer.complete();
+ });
+ break;
+ }
}, onError: (error) {
if (!expectError) throw error;
}, onDone: () {
@@ -41,16 +98,71 @@
Future.wait(futures).then(completer.complete);
});
- if (chunkSize == -1) chunkSize = data.length;
+ _writeInChunks(data, chunkSize, controller);
- int written = 0;
- for (int pos = 0; pos < data.length; pos += chunkSize) {
- int remaining = data.length - pos;
- int writeLength = min(chunkSize, remaining);
- controller.add(data.sublist(pos, pos + writeLength));
- written += writeLength;
- }
- controller.close();
+ return completer.future;
+ }
+
+ Future testFirstPartOnly(List<int> data, [int chunkSize = -1]) {
+ var completer = new Completer();
+ var controller = new StreamController(sync: true);
+
+ var stream = controller.stream.transform(
+ new MimeMultipartTransformer(boundary));
+
+ var subscription;
+ subscription = stream.first.then((multipart) {
+ if (expectedHeaders != null) {
+ expect(multipart.headers, equals(expectedHeaders[0]));
+ }
+ return (multipart.fold([], (b, d) => b..addAll(d)).then((data) {
+ if (expectedParts != null && expectedParts[0] != null) {
+ expect(data, equals(expectedParts[0].codeUnits));
+ }
+ }));
+ }).then((_) {
+ completer.complete();
+ });
+
+ _writeInChunks(data, chunkSize, controller);
+
+ return completer.future;
+ }
+
+ Future testCompletePartAfterCancel(List<int> data,
+ int parts,
+ [int chunkSize = -1]) {
+ var completer = new Completer();
+ var controller = new StreamController(sync: true);
+ var stream = controller.stream.transform(
+ new MimeMultipartTransformer(boundary));
+ var subscription;
+ int i = 0;
+ var futures = [];
+ subscription = stream.listen((multipart) {
+ int partIndex = i;
+
+ if (partIndex >= parts) {
+ throw 'Expected no more parts, but got one.';
+ }
+
+ if (expectedHeaders != null) {
+ expect(multipart.headers, equals(expectedHeaders[partIndex]));
+ }
+ futures.add((multipart.fold([], (b, d) => b..addAll(d)).then((data) {
+ if (expectedParts != null && expectedParts[partIndex] != null) {
+ expect(data, equals(expectedParts[partIndex].codeUnits));
+ }
+ })));
+
+ if (partIndex == (parts - 1)) {
+ subscription.cancel();
+ Future.wait(futures).then(completer.complete);
+ }
+ i++;
+ });
+
+ _writeInChunks(data, chunkSize, controller);
return completer.future;
}
@@ -63,9 +175,48 @@
testWrite(data),
testWrite(data, 10),
testWrite(data, 2),
- testWrite(data, 1)]),
- completes);
+ testWrite(data, 1),
+ ]), completes);
});
+
+ if (expectedParts.length > 0) {
+ test('test-first-part-only', () {
+ expect(Future.wait([
+ testFirstPartOnly(data),
+ testFirstPartOnly(data, 10),
+ testFirstPartOnly(data, 2),
+ testFirstPartOnly(data, 1),
+ ]), completes);
+ });
+
+ test('test-n-parts-only', () {
+ int numPartsExpected = expectedParts.length - 1;
+ if (numPartsExpected == 0) numPartsExpected = 1;
+
+ expect(Future.wait([
+ testCompletePartAfterCancel(data, numPartsExpected),
+ testCompletePartAfterCancel(data, numPartsExpected, 10),
+ testCompletePartAfterCancel(data, numPartsExpected, 2),
+ testCompletePartAfterCancel(data, numPartsExpected, 1),
+ ]), completes);
+ });
+ }
+}
+
+void _testParse(String message,
+ String boundary,
+ [List<Map> expectedHeaders,
+ List expectedParts,
+ bool expectError = false]) {
+ _runParseTest(
+ message, boundary, TestMode.IMMEDIATE_LISTEN,
+ expectedHeaders, expectedParts, expectError);
+ _runParseTest(
+ message, boundary, TestMode.DELAY_LISTEN,
+ expectedHeaders, expectedParts, expectError);
+ _runParseTest(
+ message, boundary, TestMode.PAUSE_RESUME,
+ expectedHeaders, expectedParts, expectError);
}
void _testParseValid() {
diff --git a/pkg/pkg.status b/pkg/pkg.status
index fb2fc499..11d7ccb 100644
--- a/pkg/pkg.status
+++ b/pkg/pkg.status
@@ -21,25 +21,25 @@
unittest/*: Skip # Issue 21949
[ $runtime == vm && $mode == debug]
-analysis_server/test/analysis_server_test: Skip # Times out
-analysis_server/test/completion_test: Skip # Times out
-analysis_server/test/domain_context_test: Skip # Times out
-analysis_server/test/domain_server_test: Skip # Times out
-analysis_server/test/integration/analysis/reanalyze_concurrent_test: Skip # Times out
-analysis_server/test/integration/analysis/update_content_test: Skip # Times out
-analysis_server/tool/spec/check_all_test: Skip # Times out
-analyzer/test/generated/element_test: Skip # Times out
-analyzer/test/generated/parser_test: Skip # Times out
-docgen/test/*: Skip # Slow
-third_party/html5lib/test/tokenizer_test: Skip # Times out
+analysis_server/test/analysis_server_test: SkipSlow # Times out
+analysis_server/test/completion_test: SkipSlow # Times out
+analysis_server/test/domain_context_test: SkipSlow # Times out
+analysis_server/test/domain_server_test: SkipSlow # Times out
+analysis_server/test/integration/analysis/reanalyze_concurrent_test: SkipSlow # Times out
+analysis_server/test/integration/analysis/update_content_test: SkipSlow # Times out
+analysis_server/tool/spec/check_all_test: SkipSlow # Times out
+analyzer/test/generated/element_test: SkipSlow # Times out
+analyzer/test/generated/parser_test: SkipSlow # Times out
+docgen/test/*: SkipSlow
+third_party/html5lib/test/tokenizer_test: SkipSlow # Times out
[ $runtime == vm && $system == windows]
analysis_server/test/analysis/get_errors_test: Skip # runtime error, Issue 22180
[ $runtime == vm && ( $arch == simarm || $arch == simmips ) ]
-docgen/test/*: Skip # Too slow
+docgen/test/*: SkipSlow
third_party/html5lib/test/tokenizer_test: Pass, Slow
-analysis_server/*: Skip # Timeout in some tests.
+analysis_server/*: SkipSlow # Timeout in some tests.
[ $compiler == dart2js ]
collection/test/equality_test/01: Fail # Issue 1533
@@ -48,10 +48,10 @@
collection/test/equality_test/04: Fail # Issue 1533
collection/test/equality_test/05: Fail # Issue 1533
collection/test/equality_test/none: Pass, Fail # Issue 14348
-docgen/test/*: Skip # Far too slow
+docgen/test/*: SkipSlow # Far too slow
third_party/angular_tests/browser_test: Pass, Slow # Large dart2js compile time
typed_data/test/typed_buffers_test/01: Fail # Not supporting Int64List, Uint64List.
-analyzer/test/generated/engine_test: Skip # Slow
+analyzer/test/generated/engine_test: SkipSlow
analyzer/test/generated/static_type_warning_code_test: Pass, Slow
analyzer/test/generated/compile_time_error_code_test: Pass, Slow
@@ -102,11 +102,11 @@
async/test/stream_zip_test: RuntimeError, Pass # Issue 18548
[ $compiler == dart2js && ($runtime == chrome || $runtime == ff) ]
-collection/test/unmodifiable_collection_test: Skip # Times out. Issue 22050
-async/test/stream_zip_test: Skip # Times out. Issue 22050
+collection/test/unmodifiable_collection_test: SkipSlow # Times out. Issue 22050
+async/test/stream_zip_test: SkipSlow # Times out. Issue 22050
[ $runtime == vm || $runtime == d8 || $runtime == jsshell ]
-third_party/angular_tests/browser_test: Skip # uses dart:html
+third_party/angular_tests/browser_test: SkipByDesign # uses dart:html
[$compiler == dart2dart]
*: Skip
@@ -148,23 +148,21 @@
crypto/test/sha1_test: Slow, Pass
[ $browser ]
-analysis_server/test/*: Skip # Uses dart:io.
-analysis_server/tool/spec/check_all_test: Skip # Uses dart:io.
-analyzer2dart/*: Skip # Uses dart:io.
-analyzer/test/*: Skip # Uses dart:io.
+*/test/analyzer_test: SkipByDesign # No need to run analysis tests on browser bots
+analysis_server/test/*: SkipByDesign # Uses dart:io.
+analysis_server/tool/spec/check_all_test: SkipByDesign # Uses dart:io.
+analyzer/test/*: SkipByDesign # Uses dart:io.
+analyzer2dart/*: SkipByDesign # Uses dart:io.
+docgen/test/*: SkipByDesign # Uses dart:io.
http_server/test/*: Fail, OK # Uses dart:io.
observe/test/transformer_test: Fail, OK # Uses dart:io.
-observe/test/unique_message_test: Skip # Intended only as a vm test.
+observe/test/unique_message_test: SkipByDesign # Uses dart:io.
stub_core_library/test/*: Fail, OK # Uses dart:io.
third_party/angular_tests/browser_test/core_dom/cookies: Fail # Issue 16337
-third_party/angular_tests/vm_test: Skip # Uses dart:io
-
-*/test/analyzer_test: Skip # No need to run analysis tests on browser bots
-
-# Skip tests on the browser if the test depends on dart:io
-third_party/html5lib/test/parser_test: Skip
-third_party/html5lib/test/tokenizer_test: Skip
-third_party/html5lib/test/selectors/*: Skip
+third_party/angular_tests/vm_test: SkipByDesign # Uses dart:io
+third_party/html5lib/test/parser_test: SkipByDesign # Uses dart:io.
+third_party/html5lib/test/selectors/*: SkipByDesign # Uses dart:io.
+third_party/html5lib/test/tokenizer_test: SkipByDesign # Uses dart:io.
[ $arch == simarm64 ]
# Timeout. These are not unit tests. They do not run efficiently on our
@@ -176,20 +174,21 @@
mutation_observer: Skip
third_party/html5lib/test/browser/browser_test: Skip
-[ $browser ]
-docgen/test/*: Skip # Uses dart:io
-
[ $compiler == dartanalyzer || $compiler == dart2analyzer ]
third_party/angular_tests/vm_test: StaticWarning # Uses removed APIs. See issue 18733.
+analyzer2dart/test/driver_test: StaticWarning # Issue 22418
+analyzer2dart/test/sexpr_test: StaticWarning # Issue 22418
+analyzer2dart/test/tree_shaker_test: StaticWarning # Issue 22418
+analyzer2dart/test/end2end_test: StaticWarning # Issue 22418
[ $runtime == safari || $runtime == safarimobilesim || $runtime == chrome || $runtime == ff || $ie ]
# Various issues due to limited browser testing in Angular.
third_party/angular_tests/*: Skip
[ $unchecked ]
-third_party/angular_tests/browser_test/angular: Skip # Requires checked mode.
-third_party/angular_tests/browser_test/core/scope: Skip # Requires checked mode.
-third_party/angular_tests/browser_test/core/zone: Skip # Requires checked mode.
+third_party/angular_tests/browser_test/angular: SkipByDesign # Requires checked mode.
+third_party/angular_tests/browser_test/core/scope: SkipByDesign # Requires checked mode.
+third_party/angular_tests/browser_test/core/zone: SkipByDesign # Requires checked mode.
third_party/angular_tests/browser_test/directive/ng_repeat: Skip # Issue 17152
third_party/angular_tests/browser_test/change_detection/dirty_checking_change_detector: Skip # Issue 17152
diff --git a/runtime/BUILD.gn b/runtime/BUILD.gn
index 793e5ed..fb02b45 100644
--- a/runtime/BUILD.gn
+++ b/runtime/BUILD.gn
@@ -45,6 +45,13 @@
"-O3",
]
}
+
+ if (is_asan) {
+ ldflags = [
+ "-Wl,-u_sanitizer_options_link_helper",
+ "-fsanitize=address",
+ ]
+ }
}
diff --git a/runtime/bin/BUILD.gn b/runtime/bin/BUILD.gn
index 23c9746..7ddfa0c 100644
--- a/runtime/bin/BUILD.gn
+++ b/runtime/bin/BUILD.gn
@@ -149,6 +149,7 @@
]
sources = [
+ "address_sanitizer.cc",
"gen_snapshot.cc",
# Very limited native resolver provided.
"builtin_common.cc",
diff --git a/runtime/bin/address_sanitizer.cc b/runtime/bin/address_sanitizer.cc
new file mode 100644
index 0000000..6795da8
--- /dev/null
+++ b/runtime/bin/address_sanitizer.cc
@@ -0,0 +1,27 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+#include "platform/globals.h"
+
+#if defined(TARGET_OS_LINUX) || defined(TARGET_OS_MACOSX)
+#if defined(__has_feature)
+#if __has_feature(address_sanitizer)
+
+const char *kAsanDefaultOptions =
+ "strict_memcmp=0 symbolize=0 check_printf=1 use_sigaltstack=1 "
+ "detect_leaks=0 fast_unwind_on_fatal=1 handle_segv=0 ";
+
+extern "C"
+__attribute__((no_sanitize_address))
+__attribute__((visibility("default")))
+// The function isn't referenced from the executable itself. Make sure it isn't
+// stripped by the linker.
+__attribute__((used))
+const char *__asan_default_options() {
+ return kAsanDefaultOptions;
+}
+
+#endif // __has_feature(address_sanitizer)
+#endif // defined(__has_feature)
+#endif // defined(TARGET_OS_LINUX) || defined(TARGET_OS_MACOSX)
diff --git a/runtime/bin/bin.gypi b/runtime/bin/bin.gypi
index 0d92b4d..c626805 100644
--- a/runtime/bin/bin.gypi
+++ b/runtime/bin/bin.gypi
@@ -387,6 +387,7 @@
'..',
],
'sources': [
+ 'address_sanitizer.cc',
'gen_snapshot.cc',
# Very limited native resolver provided.
'builtin_gen_snapshot.cc',
diff --git a/runtime/bin/dbg_connection.cc b/runtime/bin/dbg_connection.cc
index a63cf44..0b0b217 100644
--- a/runtime/bin/dbg_connection.cc
+++ b/runtime/bin/dbg_connection.cc
@@ -328,8 +328,9 @@
OSError *os_error;
AddressList<SocketAddress>* addresses =
Socket::LookupAddress(address, -1, &os_error);
- listener_fd_ = ServerSocket::CreateBindListen(
- addresses->GetAt(0)->addr(), port_number, 1);
+ RawAddr addr = addresses->GetAt(0)->addr();
+ SocketAddress::SetAddrPort(&addr, port_number);
+ listener_fd_ = ServerSocket::CreateBindListen(addr, 1);
delete addresses;
if (listener_fd_ < 0) {
fprintf(stderr, "%s", "Could not initialize debug socket\n");
diff --git a/runtime/bin/file_patch.dart b/runtime/bin/file_patch.dart
index 36e5b57..14499af 100644
--- a/runtime/bin/file_patch.dart
+++ b/runtime/bin/file_patch.dart
@@ -99,7 +99,7 @@
_newWatcher();
} catch (e) {
_broadcastController.addError(new FileSystemException(
- "Failed to initialize file system entity watcher"));
+ "Failed to initialize file system entity watcher", null, e));
_broadcastController.close();
return;
}
diff --git a/runtime/bin/file_system_watcher.cc b/runtime/bin/file_system_watcher.cc
index 0260be7..164346c 100644
--- a/runtime/bin/file_system_watcher.cc
+++ b/runtime/bin/file_system_watcher.cc
@@ -6,6 +6,7 @@
#include "bin/builtin.h"
#include "bin/dartutils.h"
+#include "bin/utils.h"
#include "include/dart_api.h"
@@ -18,7 +19,15 @@
void FUNCTION_NAME(FileSystemWatcher_InitWatcher)(Dart_NativeArguments args) {
- Dart_SetReturnValue(args, Dart_NewInteger(FileSystemWatcher::Init()));
+ intptr_t id = FileSystemWatcher::Init();
+ if (id >= 0) {
+ Dart_SetReturnValue(args, Dart_NewInteger(id));
+ } else {
+ OSError os_error;
+ Dart_Handle error = DartUtils::NewDartOSError(&os_error);
+ if (Dart_IsError(error)) Dart_PropagateError(error);
+ Dart_ThrowException(error);
+ }
}
diff --git a/runtime/bin/file_system_watcher_linux.cc b/runtime/bin/file_system_watcher_linux.cc
index 9261426..48c7323 100644
--- a/runtime/bin/file_system_watcher_linux.cc
+++ b/runtime/bin/file_system_watcher_linux.cc
@@ -117,4 +117,3 @@
} // namespace dart
#endif // defined(TARGET_OS_LINUX)
-
diff --git a/runtime/bin/main.cc b/runtime/bin/main.cc
index b2723ca..693ab90 100644
--- a/runtime/bin/main.cc
+++ b/runtime/bin/main.cc
@@ -947,20 +947,6 @@
// Start event handler.
EventHandler::Start();
- // Initialize the Dart VM.
- if (!Dart_Initialize(CreateIsolateAndSetup, NULL, NULL, ShutdownIsolate,
- DartUtils::OpenFile,
- DartUtils::ReadFile,
- DartUtils::WriteFile,
- DartUtils::CloseFile,
- DartUtils::EntropySource)) {
- fprintf(stderr, "%s", "VM initialization failed\n");
- fflush(stderr);
- exit(kErrorExitCode);
- }
-
-
-
// Start the debugger wire protocol handler if necessary.
if (start_debugger) {
ASSERT(debug_port >= 0);
@@ -973,6 +959,18 @@
DebuggerConnectionHandler::InitForVmService();
}
+ // Initialize the Dart VM.
+ if (!Dart_Initialize(CreateIsolateAndSetup, NULL, NULL, ShutdownIsolate,
+ DartUtils::OpenFile,
+ DartUtils::ReadFile,
+ DartUtils::WriteFile,
+ DartUtils::CloseFile,
+ DartUtils::EntropySource)) {
+ fprintf(stderr, "%s", "VM initialization failed\n");
+ fflush(stderr);
+ exit(kErrorExitCode);
+ }
+
Dart_RegisterIsolateServiceRequestCallback(
"io", &ServiceRequestHandler, NULL);
diff --git a/runtime/bin/secure_socket.cc b/runtime/bin/secure_socket.cc
index 2e22fef..63f600f 100644
--- a/runtime/bin/secure_socket.cc
+++ b/runtime/bin/secure_socket.cc
@@ -150,7 +150,7 @@
ASSERT(!Dart_IsNull(protocols_handle));
GetFilter(args)->Connect(host_name,
- &raw_addr,
+ raw_addr,
static_cast<int>(port),
is_server,
certificate_name,
@@ -666,7 +666,7 @@
void SSLFilter::Connect(const char* host_name,
- RawAddr* raw_addr,
+ const RawAddr& raw_addr,
int port,
bool is_server,
const char* certificate_name,
@@ -835,13 +835,13 @@
memset(&peername, 0, sizeof(peername));
intptr_t len = SocketAddress::GetAddrLength(raw_addr);
ASSERT(static_cast<size_t>(len) <= sizeof(peername));
- memmove(&peername, &raw_addr->addr, len);
+ memmove(&peername, &raw_addr.addr, len);
// Adjust the address family field for BSD, whose sockaddr
// structure has a one-byte length and one-byte address family
// field at the beginning. PRNetAddr has a two-byte address
// family field at the beginning.
- peername.raw.family = raw_addr->addr.sa_family;
+ peername.raw.family = raw_addr.addr.sa_family;
memio_SetPeerName(filter_, &peername);
}
diff --git a/runtime/bin/secure_socket.h b/runtime/bin/secure_socket.h
index e5d7608..5deccc1 100644
--- a/runtime/bin/secure_socket.h
+++ b/runtime/bin/secure_socket.h
@@ -59,7 +59,7 @@
void Init(Dart_Handle dart_this);
void Connect(const char* host,
- RawAddr* raw_addr,
+ const RawAddr& raw_addr,
int port,
bool is_server,
const char* certificate_name,
diff --git a/runtime/bin/socket.cc b/runtime/bin/socket.cc
index b8e8766..ea5154e 100644
--- a/runtime/bin/socket.cc
+++ b/runtime/bin/socket.cc
@@ -43,12 +43,13 @@
Dart_Handle ListeningSocketRegistry::CreateBindListen(Dart_Handle socket_object,
RawAddr addr,
- intptr_t port,
intptr_t backlog,
bool v6_only,
bool shared) {
MutexLocker ml(ListeningSocketRegistry::mutex_);
+ intptr_t port = SocketAddress::GetAddrPort(addr);
+
SocketsIterator it = sockets_by_port_.find(port);
OSSocket *first_os_socket = NULL;
if (it != sockets_by_port_.end()) {
@@ -94,8 +95,7 @@
}
// There is no socket listening on that (address, port), so we create new one.
- intptr_t socketfd = ServerSocket::CreateBindListen(
- addr, port, backlog, v6_only);
+ intptr_t socketfd = ServerSocket::CreateBindListen(addr, backlog, v6_only);
if (socketfd == -5) {
OSError os_error(-1, "Invalid host", OSError::kUnknown);
return DartUtils::NewDartOSError(&os_error);
@@ -201,7 +201,7 @@
if (!ok) {
Dart_SetReturnValue(args, Dart_Null());
} else {
- Dart_SetReturnValue(args, SocketAddress::ToTypedData(&raw));
+ Dart_SetReturnValue(args, SocketAddress::ToTypedData(raw));
}
}
@@ -211,7 +211,8 @@
SocketAddress::GetSockAddr(Dart_GetNativeArgument(args, 1), &addr);
Dart_Handle port_arg = Dart_GetNativeArgument(args, 2);
int64_t port = DartUtils::GetInt64ValueCheckRange(port_arg, 0, 65535);
- intptr_t socket = Socket::CreateConnect(addr, static_cast<intptr_t>(port));
+ SocketAddress::SetAddrPort(&addr, static_cast<intptr_t>(port));
+ intptr_t socket = Socket::CreateConnect(addr);
OSError error;
if (socket >= 0) {
Socket::SetSocketIdNativeField(Dart_GetNativeArgument(args, 0), socket);
@@ -227,10 +228,10 @@
SocketAddress::GetSockAddr(Dart_GetNativeArgument(args, 1), &addr);
Dart_Handle port_arg = Dart_GetNativeArgument(args, 2);
int64_t port = DartUtils::GetInt64ValueCheckRange(port_arg, 0, 65535);
+ SocketAddress::SetAddrPort(&addr, static_cast<intptr_t>(port));
RawAddr sourceAddr;
SocketAddress::GetSockAddr(Dart_GetNativeArgument(args, 3), &sourceAddr);
- intptr_t socket = Socket::CreateBindConnect(
- addr, static_cast<intptr_t>(port), sourceAddr);
+ intptr_t socket = Socket::CreateBindConnect(addr, sourceAddr);
OSError error;
if (socket >= 0) {
Socket::SetSocketIdNativeField(Dart_GetNativeArgument(args, 0), socket);
@@ -246,10 +247,9 @@
SocketAddress::GetSockAddr(Dart_GetNativeArgument(args, 1), &addr);
Dart_Handle port_arg = Dart_GetNativeArgument(args, 2);
int64_t port = DartUtils::GetInt64ValueCheckRange(port_arg, 0, 65535);
+ SocketAddress::SetAddrPort(&addr, port);
bool reuse_addr = DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 3));
- intptr_t socket = Socket::CreateBindDatagram(&addr,
- static_cast<intptr_t>(port),
- reuse_addr);
+ intptr_t socket = Socket::CreateBindDatagram(addr, reuse_addr);
if (socket >= 0) {
Socket::SetSocketIdNativeField(Dart_GetNativeArgument(args, 0), socket);
Dart_SetReturnValue(args, Dart_True());
@@ -347,7 +347,7 @@
memmove(data_buffer, isolate_data->udp_receive_buffer, bytes_read);
// Get the port and clear it in the sockaddr structure.
- int port = SocketAddress::GetAddrPort(&addr);
+ int port = SocketAddress::GetAddrPort(addr);
if (addr.addr.sa_family == AF_INET) {
addr.in.sin_port = 0;
} else {
@@ -356,7 +356,7 @@
}
// Format the address to a string using the numeric format.
char numeric_address[INET6_ADDRSTRLEN];
- Socket::FormatNumericAddress(&addr, numeric_address, INET6_ADDRSTRLEN);
+ Socket::FormatNumericAddress(addr, numeric_address, INET6_ADDRSTRLEN);
// Create a Datagram object with the data and sender address and port.
const int kNumArgs = 4;
@@ -364,7 +364,7 @@
dart_args[0] = data;
dart_args[1] = Dart_NewStringFromCString(numeric_address);
if (Dart_IsError(dart_args[1])) Dart_PropagateError(dart_args[1]);
- dart_args[2] = SocketAddress::ToTypedData(&addr);
+ dart_args[2] = SocketAddress::ToTypedData(addr);
dart_args[3] = Dart_NewInteger(port);
if (Dart_IsError(dart_args[3])) Dart_PropagateError(dart_args[3]);
// TODO(sgjesse): Cache the _makeDatagram function somewhere.
@@ -488,7 +488,7 @@
Dart_ListSetAt(entry, 1, Dart_NewStringFromCString(addr->as_string()));
RawAddr raw = addr->addr();
- intptr_t data_length = SocketAddress::GetAddrLength(&raw);
+ intptr_t data_length = SocketAddress::GetAddrLength(raw);
Dart_Handle data = Dart_NewTypedData(Dart_TypedData_kUint8, data_length);
Dart_ListSetAsBytes(data, 0, reinterpret_cast<uint8_t*>(&raw), data_length);
Dart_ListSetAt(entry, 2, data);
@@ -555,6 +555,7 @@
Dart_GetNativeArgument(args, 2),
0,
65535);
+ SocketAddress::SetAddrPort(&addr, port);
int64_t backlog = DartUtils::GetInt64ValueCheckRange(
Dart_GetNativeArgument(args, 3),
0,
@@ -564,7 +565,7 @@
Dart_Handle socket_object = Dart_GetNativeArgument(args, 0);
Dart_Handle result = ListeningSocketRegistry::Instance()->CreateBindListen(
- socket_object, addr, port, backlog, v6_only, shared);
+ socket_object, addr, backlog, v6_only, shared);
Dart_SetReturnValue(args, result);
}
@@ -611,7 +612,7 @@
entry->SetAt(1, as_string);
RawAddr raw = addr->addr();
- CObjectUint8Array* data = SocketAddress::ToCObject(&raw);
+ CObjectUint8Array* data = SocketAddress::ToCObject(raw);
entry->SetAt(2, data);
array->SetAt(i + 1, entry);
@@ -689,7 +690,7 @@
entry->SetAt(1, as_string);
RawAddr raw = addr->addr();
- CObjectUint8Array* data = SocketAddress::ToCObject(&raw);
+ CObjectUint8Array* data = SocketAddress::ToCObject(raw);
entry->SetAt(2, data);
CObjectString* interface_name = new CObjectString(CObject::NewString(
@@ -827,7 +828,7 @@
}
int interfaceIndex =
DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 3));
- if (Socket::JoinMulticast(socket, &addr, &interface, interfaceIndex)) {
+ if (Socket::JoinMulticast(socket, addr, interface, interfaceIndex)) {
Dart_SetReturnValue(args, Dart_Null());
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError());
@@ -846,7 +847,7 @@
}
int interfaceIndex =
DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 3));
- if (Socket::LeaveMulticast(socket, &addr, &interface, interfaceIndex)) {
+ if (Socket::LeaveMulticast(socket, addr, interface, interfaceIndex)) {
Dart_SetReturnValue(args, Dart_Null());
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError());
diff --git a/runtime/bin/socket.h b/runtime/bin/socket.h
index fc27903..507acd9 100644
--- a/runtime/bin/socket.h
+++ b/runtime/bin/socket.h
@@ -66,15 +66,15 @@
const char* as_string() const { return as_string_; }
const RawAddr& addr() const { return addr_; }
- static intptr_t GetAddrLength(const RawAddr* addr) {
- ASSERT(addr->ss.ss_family == AF_INET || addr->ss.ss_family == AF_INET6);
- return addr->ss.ss_family == AF_INET6 ?
+ static intptr_t GetAddrLength(const RawAddr& addr) {
+ ASSERT(addr.ss.ss_family == AF_INET || addr.ss.ss_family == AF_INET6);
+ return addr.ss.ss_family == AF_INET6 ?
sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
}
- static intptr_t GetInAddrLength(const RawAddr* addr) {
- ASSERT(addr->ss.ss_family == AF_INET || addr->ss.ss_family == AF_INET6);
- return addr->ss.ss_family == AF_INET6 ?
+ static intptr_t GetInAddrLength(const RawAddr& addr) {
+ ASSERT(addr.ss.ss_family == AF_INET || addr.ss.ss_family == AF_INET6);
+ return addr.ss.ss_family == AF_INET6 ?
sizeof(struct in6_addr) : sizeof(struct in_addr);
}
@@ -132,39 +132,41 @@
}
}
- static intptr_t GetAddrPort(const RawAddr* addr) {
- if (addr->ss.ss_family == AF_INET) {
- return ntohs(addr->in.sin_port);
+ static intptr_t GetAddrPort(const RawAddr& addr) {
+ if (addr.ss.ss_family == AF_INET) {
+ return ntohs(addr.in.sin_port);
} else {
- return ntohs(addr->in6.sin6_port);
+ return ntohs(addr.in6.sin6_port);
}
}
- static Dart_Handle ToTypedData(RawAddr* raw) {
- int len = GetInAddrLength(raw);
+ static Dart_Handle ToTypedData(const RawAddr& addr) {
+ int len = GetInAddrLength(addr);
Dart_Handle result = Dart_NewTypedData(Dart_TypedData_kUint8, len);
if (Dart_IsError(result)) Dart_PropagateError(result);
Dart_Handle err;
- if (raw->addr.sa_family == AF_INET6) {
+ RawAddr& raw = const_cast<RawAddr&>(addr);
+ if (addr.addr.sa_family == AF_INET6) {
err = Dart_ListSetAsBytes(
- result, 0, reinterpret_cast<uint8_t*>(&raw->in6.sin6_addr), len);
+ result, 0, reinterpret_cast<uint8_t*>(&raw.in6.sin6_addr), len);
} else {
err = Dart_ListSetAsBytes(
- result, 0, reinterpret_cast<uint8_t*>(&raw->in.sin_addr), len);
+ result, 0, reinterpret_cast<uint8_t*>(&raw.in.sin_addr), len);
}
if (Dart_IsError(err)) Dart_PropagateError(err);
return result;
}
- static CObjectUint8Array* ToCObject(RawAddr* raw) {
- int in_addr_len = SocketAddress::GetInAddrLength(raw);
+ static CObjectUint8Array* ToCObject(const RawAddr& addr) {
+ int in_addr_len = SocketAddress::GetInAddrLength(addr);
void* in_addr;
+ RawAddr& raw = const_cast<RawAddr&>(addr);
CObjectUint8Array* data =
new CObjectUint8Array(CObject::NewUint8Array(in_addr_len));
- if (raw->addr.sa_family == AF_INET6) {
- in_addr = reinterpret_cast<void*>(&raw->in6.sin6_addr);
+ if (addr.addr.sa_family == AF_INET6) {
+ in_addr = reinterpret_cast<void*>(&raw.in6.sin6_addr);
} else {
- in_addr = reinterpret_cast<void*>(&raw->in.sin_addr);
+ in_addr = reinterpret_cast<void*>(&raw.in.sin_addr);
}
memmove(data->Buffer(), in_addr, in_addr_len);
return data;
@@ -240,17 +242,23 @@
static intptr_t Available(intptr_t fd);
static intptr_t Read(intptr_t fd, void* buffer, intptr_t num_bytes);
static intptr_t Write(intptr_t fd, const void* buffer, intptr_t num_bytes);
+ // Send data on a socket. The port to send to is specified in the port
+ // component of the passed RawAddr structure. The RawAddr structure is only
+ // used for datagram sockets.
static intptr_t SendTo(
- intptr_t fd, const void* buffer, intptr_t num_bytes, RawAddr addr);
+ intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr);
static intptr_t RecvFrom(
intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr);
- static intptr_t CreateConnect(const RawAddr& addr,
- const intptr_t port);
+ // Creates a socket which is bound and connected. The port to connect to is
+ // specified as the port component of the passed RawAddr structure.
+ static intptr_t CreateConnect(const RawAddr& addr);
+ // Creates a socket which is bound and connected. The port to connect to is
+ // specified as the port component of the passed RawAddr structure.
static intptr_t CreateBindConnect(const RawAddr& addr,
- const intptr_t port,
const RawAddr& source_addr);
- static intptr_t CreateBindDatagram(
- RawAddr* addr, intptr_t port, bool reuseAddress);
+ // Creates a datagram socket which is bound. The port to bind
+ // to is specified as the port component of the RawAddr structure.
+ static intptr_t CreateBindDatagram(const RawAddr& addr, bool reuseAddress);
static intptr_t GetPort(intptr_t fd);
static SocketAddress* GetRemotePeer(intptr_t fd, intptr_t* port);
static void GetError(intptr_t fd, OSError* os_error);
@@ -265,23 +273,27 @@
static bool SetMulticastHops(intptr_t fd, intptr_t protocol, int value);
static bool GetBroadcast(intptr_t fd, bool* value);
static bool SetBroadcast(intptr_t fd, bool value);
- static bool JoinMulticast(
- intptr_t fd, RawAddr* addr, RawAddr* interface, int interfaceIndex);
- static bool LeaveMulticast(
- intptr_t fd, RawAddr* addr, RawAddr* interface, int interfaceIndex);
+ static bool JoinMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr& interface,
+ int interfaceIndex);
+ static bool LeaveMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr& interface,
+ int interfaceIndex);
// Perform a hostname lookup. Returns a AddressList of SocketAddress's.
static AddressList<SocketAddress>* LookupAddress(const char* host,
int type,
OSError** os_error);
- static bool ReverseLookup(RawAddr addr,
+ static bool ReverseLookup(const RawAddr& addr,
char* host,
intptr_t host_len,
OSError** os_error);
static bool ParseAddress(int type, const char* address, RawAddr* addr);
- static bool FormatNumericAddress(RawAddr* addr, char* address, int len);
+ static bool FormatNumericAddress(const RawAddr& addr, char* address, int len);
// List interfaces. Returns a AddressList of InterfaceSocketAddress's.
static AddressList<InterfaceSocketAddress>* ListInterfaces(
@@ -309,13 +321,15 @@
static intptr_t Accept(intptr_t fd);
+ // Creates a socket which is bound and listens. The port to listen on is
+ // specified in the port component of the passed RawAddr structure.
+ //
// Returns a positive integer if the call is successful. In case of failure
// it returns:
//
// -1: system error (errno set)
// -5: invalid bindAddress
- static intptr_t CreateBindListen(RawAddr addr,
- intptr_t port,
+ static intptr_t CreateBindListen(const RawAddr& addr,
intptr_t backlog,
bool v6_only = false);
@@ -367,7 +381,6 @@
// a new (potentially shared) socket.
Dart_Handle CreateBindListen(Dart_Handle socket_object,
RawAddr addr,
- intptr_t port,
intptr_t backlog,
bool v6_only,
bool shared);
diff --git a/runtime/bin/socket_android.cc b/runtime/bin/socket_android.cc
index e965057..606a817 100644
--- a/runtime/bin/socket_android.cc
+++ b/runtime/bin/socket_android.cc
@@ -26,17 +26,17 @@
SocketAddress::SocketAddress(struct sockaddr* sa) {
ASSERT(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN);
if (!Socket::FormatNumericAddress(
- reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
+ *reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
as_string_[0] = 0;
}
- socklen_t salen = GetAddrLength(reinterpret_cast<RawAddr*>(sa));
+ socklen_t salen = GetAddrLength(*reinterpret_cast<RawAddr*>(sa));
memmove(reinterpret_cast<void *>(&addr_), sa, salen);
}
-bool Socket::FormatNumericAddress(RawAddr* addr, char* address, int len) {
+bool Socket::FormatNumericAddress(const RawAddr& addr, char* address, int len) {
socklen_t salen = SocketAddress::GetAddrLength(addr);
- if (NO_RETRY_EXPECTED(getnameinfo(&addr->addr,
+ if (NO_RETRY_EXPECTED(getnameinfo(&addr.addr,
salen,
address,
len,
@@ -55,7 +55,7 @@
}
-static intptr_t Create(RawAddr addr) {
+static intptr_t Create(const RawAddr& addr) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.ss.ss_family, SOCK_STREAM, 0));
if (fd < 0) {
@@ -66,10 +66,9 @@
}
-static intptr_t Connect(intptr_t fd, RawAddr addr, const intptr_t port) {
- SocketAddress::SetAddrPort(&addr, port);
+static intptr_t Connect(intptr_t fd, const RawAddr& addr) {
intptr_t result = TEMP_FAILURE_RETRY(
- connect(fd, &addr.addr, SocketAddress::GetAddrLength(&addr)));
+ connect(fd, &addr.addr, SocketAddress::GetAddrLength(addr)));
if (result == 0 || errno == EINPROGRESS) {
return fd;
}
@@ -78,7 +77,7 @@
}
-intptr_t Socket::CreateConnect(const RawAddr& addr, const intptr_t port) {
+intptr_t Socket::CreateConnect(const RawAddr& addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
@@ -86,12 +85,11 @@
FDUtils::SetNonBlocking(fd);
- return Connect(fd, addr, port);
+ return Connect(fd, addr);
}
intptr_t Socket::CreateBindConnect(const RawAddr& addr,
- const intptr_t port,
const RawAddr& source_addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
@@ -99,13 +97,13 @@
}
intptr_t result = TEMP_FAILURE_RETRY(
- bind(fd, &source_addr.addr, SocketAddress::GetAddrLength(&source_addr)));
+ bind(fd, &source_addr.addr, SocketAddress::GetAddrLength(source_addr)));
if (result != 0 && errno != EINPROGRESS) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
- return Connect(fd, addr, port);
+ return Connect(fd, addr);
}
@@ -127,8 +125,8 @@
}
-intptr_t Socket::RecvFrom(intptr_t fd, void* buffer, intptr_t num_bytes,
- RawAddr* addr) {
+intptr_t Socket::RecvFrom(
+ intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
ASSERT(fd >= 0);
socklen_t addr_len = sizeof(addr->ss);
ssize_t read_bytes = TEMP_FAILURE_RETRY(
@@ -155,12 +153,12 @@
}
-intptr_t Socket::SendTo(intptr_t fd, const void* buffer, intptr_t num_bytes,
- RawAddr addr) {
+intptr_t Socket::SendTo(
+ intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
ASSERT(fd >= 0);
ssize_t written_bytes = TEMP_FAILURE_RETRY(
sendto(fd, buffer, num_bytes, 0,
- &addr.addr, SocketAddress::GetAddrLength(&addr)));
+ &addr.addr, SocketAddress::GetAddrLength(addr)));
ASSERT(EAGAIN == EWOULDBLOCK);
if (written_bytes == -1 && errno == EWOULDBLOCK) {
// If the would block we need to retry and therefore return 0 as
@@ -178,7 +176,7 @@
if (NO_RETRY_EXPECTED(getsockname(fd, &raw.addr, &size))) {
return 0;
}
- return SocketAddress::GetAddrPort(&raw);
+ return SocketAddress::GetAddrPort(raw);
}
@@ -189,7 +187,7 @@
if (NO_RETRY_EXPECTED(getpeername(fd, &raw.addr, &size))) {
return NULL;
}
- *port = SocketAddress::GetAddrPort(&raw);
+ *port = SocketAddress::GetAddrPort(raw);
return new SocketAddress(&raw.addr);
}
@@ -264,14 +262,14 @@
}
-bool Socket::ReverseLookup(RawAddr addr,
+bool Socket::ReverseLookup(const RawAddr& addr,
char* host,
intptr_t host_len,
OSError** os_error) {
ASSERT(host_len >= NI_MAXHOST);
int status = NO_RETRY_EXPECTED(getnameinfo(
&addr.addr,
- SocketAddress::GetAddrLength(&addr),
+ SocketAddress::GetAddrLength(addr),
host,
host_len,
NULL,
@@ -300,11 +298,10 @@
}
-intptr_t Socket::CreateBindDatagram(
- RawAddr* addr, intptr_t port, bool reuseAddress) {
+intptr_t Socket::CreateBindDatagram(const RawAddr& addr, bool reuseAddress) {
intptr_t fd;
- fd = NO_RETRY_EXPECTED(socket(addr->addr.sa_family, SOCK_DGRAM, IPPROTO_UDP));
+ fd = NO_RETRY_EXPECTED(socket(addr.addr.sa_family, SOCK_DGRAM, IPPROTO_UDP));
if (fd < 0) return -1;
FDUtils::SetCloseOnExec(fd);
@@ -315,10 +312,9 @@
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)));
}
- SocketAddress::SetAddrPort(addr, port);
if (NO_RETRY_EXPECTED(
bind(fd,
- &addr->addr,
+ &addr.addr,
SocketAddress::GetAddrLength(addr))) < 0) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
@@ -338,8 +334,7 @@
}
-intptr_t ServerSocket::CreateBindListen(RawAddr addr,
- intptr_t port,
+intptr_t ServerSocket::CreateBindListen(const RawAddr& addr,
intptr_t backlog,
bool v6_only) {
intptr_t fd;
@@ -359,20 +354,19 @@
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)));
}
- SocketAddress::SetAddrPort(&addr, port);
if (NO_RETRY_EXPECTED(
bind(fd,
&addr.addr,
- SocketAddress::GetAddrLength(&addr))) < 0) {
+ SocketAddress::GetAddrLength(addr))) < 0) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
// Test for invalid socket port 65535 (some browsers disallow it).
- if (port == 0 && Socket::GetPort(fd) == 65535) {
+ if (SocketAddress::GetAddrPort(addr) == 0 && Socket::GetPort(fd) == 65535) {
// Don't close the socket until we have created a new socket, ensuring
// that we do not get the bad port number again.
- intptr_t new_fd = CreateBindListen(addr, 0, backlog, v6_only);
+ intptr_t new_fd = CreateBindListen(addr, backlog, v6_only);
int err = errno;
VOID_TEMP_FAILURE_RETRY(close(fd));
errno = err;
@@ -544,22 +538,22 @@
bool Socket::JoinMulticast(
- intptr_t fd, RawAddr* addr, RawAddr*, int interfaceIndex) {
- int proto = addr->addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
+ intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+ int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
- memmove(&mreq.gr_group, &addr->ss, SocketAddress::GetAddrLength(addr));
+ memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
return NO_RETRY_EXPECTED(setsockopt(
fd, proto, MCAST_JOIN_GROUP, &mreq, sizeof(mreq))) == 0;
}
bool Socket::LeaveMulticast(
- intptr_t fd, RawAddr* addr, RawAddr*, int interfaceIndex) {
- int proto = addr->addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
+ intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+ int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
- memmove(&mreq.gr_group, &addr->ss, SocketAddress::GetAddrLength(addr));
+ memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
return NO_RETRY_EXPECTED(setsockopt(
fd, proto, MCAST_LEAVE_GROUP, &mreq, sizeof(mreq))) == 0;
}
diff --git a/runtime/bin/socket_linux.cc b/runtime/bin/socket_linux.cc
index 151ac5b..976bd0f 100644
--- a/runtime/bin/socket_linux.cc
+++ b/runtime/bin/socket_linux.cc
@@ -28,18 +28,18 @@
SocketAddress::SocketAddress(struct sockaddr* sa) {
ASSERT(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN);
if (!Socket::FormatNumericAddress(
- reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
+ *reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
as_string_[0] = 0;
}
- socklen_t salen = GetAddrLength(reinterpret_cast<RawAddr*>(sa));
+ socklen_t salen = GetAddrLength(*reinterpret_cast<RawAddr*>(sa));
memmove(reinterpret_cast<void *>(&addr_), sa, salen);
}
-bool Socket::FormatNumericAddress(RawAddr* addr, char* address, int len) {
+bool Socket::FormatNumericAddress(const RawAddr& addr, char* address, int len) {
socklen_t salen = SocketAddress::GetAddrLength(addr);
if (NO_RETRY_EXPECTED(getnameinfo(
- &addr->addr, salen, address, len, NULL, 0, NI_NUMERICHOST) != 0)) {
+ &addr.addr, salen, address, len, NULL, 0, NI_NUMERICHOST) != 0)) {
return false;
}
return true;
@@ -52,7 +52,7 @@
}
-static intptr_t Create(RawAddr addr) {
+static intptr_t Create(const RawAddr& addr) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(
socket(addr.ss.ss_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
@@ -63,10 +63,9 @@
}
-static intptr_t Connect(intptr_t fd, RawAddr addr, const intptr_t port) {
- SocketAddress::SetAddrPort(&addr, port);
+static intptr_t Connect(intptr_t fd, const RawAddr& addr) {
intptr_t result = TEMP_FAILURE_RETRY(
- connect(fd, &addr.addr, SocketAddress::GetAddrLength(&addr)));
+ connect(fd, &addr.addr, SocketAddress::GetAddrLength(addr)));
if (result == 0 || errno == EINPROGRESS) {
return fd;
}
@@ -75,17 +74,16 @@
}
-intptr_t Socket::CreateConnect(const RawAddr& addr, const intptr_t port) {
+intptr_t Socket::CreateConnect(const RawAddr& addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
}
- return Connect(fd, addr, port);
+ return Connect(fd, addr);
}
intptr_t Socket::CreateBindConnect(const RawAddr& addr,
- const intptr_t port,
const RawAddr& source_addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
@@ -93,13 +91,13 @@
}
intptr_t result = TEMP_FAILURE_RETRY(
- bind(fd, &source_addr.addr, SocketAddress::GetAddrLength(&source_addr)));
+ bind(fd, &source_addr.addr, SocketAddress::GetAddrLength(source_addr)));
if (result != 0 && errno != EINPROGRESS) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
- return Connect(fd, addr, port);
+ return Connect(fd, addr);
}
@@ -121,8 +119,8 @@
}
-intptr_t Socket::RecvFrom(intptr_t fd, void* buffer, intptr_t num_bytes,
- RawAddr* addr) {
+intptr_t Socket::RecvFrom(
+ intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
ASSERT(fd >= 0);
socklen_t addr_len = sizeof(addr->ss);
ssize_t read_bytes = TEMP_FAILURE_RETRY(
@@ -149,12 +147,12 @@
}
-intptr_t Socket::SendTo(intptr_t fd, const void* buffer, intptr_t num_bytes,
- RawAddr addr) {
+intptr_t Socket::SendTo(
+ intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
ASSERT(fd >= 0);
ssize_t written_bytes = TEMP_FAILURE_RETRY(
sendto(fd, buffer, num_bytes, 0,
- &addr.addr, SocketAddress::GetAddrLength(&addr)));
+ &addr.addr, SocketAddress::GetAddrLength(addr)));
ASSERT(EAGAIN == EWOULDBLOCK);
if (written_bytes == -1 && errno == EWOULDBLOCK) {
// If the would block we need to retry and therefore return 0 as
@@ -172,7 +170,7 @@
if (NO_RETRY_EXPECTED(getsockname(fd, &raw.addr, &size))) {
return 0;
}
- return SocketAddress::GetAddrPort(&raw);
+ return SocketAddress::GetAddrPort(raw);
}
@@ -183,7 +181,7 @@
if (NO_RETRY_EXPECTED(getpeername(fd, &raw.addr, &size))) {
return NULL;
}
- *port = SocketAddress::GetAddrPort(&raw);
+ *port = SocketAddress::GetAddrPort(raw);
return new SocketAddress(&raw.addr);
}
@@ -256,14 +254,14 @@
}
-bool Socket::ReverseLookup(RawAddr addr,
+bool Socket::ReverseLookup(const RawAddr& addr,
char* host,
intptr_t host_len,
OSError** os_error) {
ASSERT(host_len >= NI_MAXHOST);
int status = NO_RETRY_EXPECTED(getnameinfo(
&addr.addr,
- SocketAddress::GetAddrLength(&addr),
+ SocketAddress::GetAddrLength(addr),
host,
host_len,
NULL,
@@ -293,11 +291,10 @@
}
-intptr_t Socket::CreateBindDatagram(
- RawAddr* addr, intptr_t port, bool reuseAddress) {
+intptr_t Socket::CreateBindDatagram(const RawAddr& addr, bool reuseAddress) {
intptr_t fd;
- fd = NO_RETRY_EXPECTED(socket(addr->addr.sa_family,
+ fd = NO_RETRY_EXPECTED(socket(addr.addr.sa_family,
SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
IPPROTO_UDP));
if (fd < 0) return -1;
@@ -308,9 +305,8 @@
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)));
}
- SocketAddress::SetAddrPort(addr, port);
if (NO_RETRY_EXPECTED(
- bind(fd, &addr->addr, SocketAddress::GetAddrLength(addr))) < 0) {
+ bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
@@ -369,8 +365,7 @@
}
-intptr_t ServerSocket::CreateBindListen(RawAddr addr,
- intptr_t port,
+intptr_t ServerSocket::CreateBindListen(const RawAddr& addr,
intptr_t backlog,
bool v6_only) {
intptr_t fd;
@@ -389,18 +384,17 @@
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)));
}
- SocketAddress::SetAddrPort(&addr, port);
if (NO_RETRY_EXPECTED(
- bind(fd, &addr.addr, SocketAddress::GetAddrLength(&addr))) < 0) {
+ bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
// Test for invalid socket port 65535 (some browsers disallow it).
- if (port == 0 && Socket::GetPort(fd) == 65535) {
+ if (SocketAddress::GetAddrPort(addr) == 0 && Socket::GetPort(fd) == 65535) {
// Don't close the socket until we have created a new socket, ensuring
// that we do not get the bad port number again.
- intptr_t new_fd = CreateBindListen(addr, 0, backlog, v6_only);
+ intptr_t new_fd = CreateBindListen(addr, backlog, v6_only);
int err = errno;
VOID_TEMP_FAILURE_RETRY(close(fd));
errno = err;
@@ -554,22 +548,22 @@
bool Socket::JoinMulticast(
- intptr_t fd, RawAddr* addr, RawAddr*, int interfaceIndex) {
- int proto = addr->addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
+ intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+ int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
- memmove(&mreq.gr_group, &addr->ss, SocketAddress::GetAddrLength(addr));
+ memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
return NO_RETRY_EXPECTED(
setsockopt(fd, proto, MCAST_JOIN_GROUP, &mreq, sizeof(mreq))) == 0;
}
bool Socket::LeaveMulticast(
- intptr_t fd, RawAddr* addr, RawAddr*, int interfaceIndex) {
- int proto = addr->addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
+ intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+ int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
- memmove(&mreq.gr_group, &addr->ss, SocketAddress::GetAddrLength(addr));
+ memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
return NO_RETRY_EXPECTED(
setsockopt(fd, proto, MCAST_LEAVE_GROUP, &mreq, sizeof(mreq))) == 0;
}
diff --git a/runtime/bin/socket_macos.cc b/runtime/bin/socket_macos.cc
index 239bb45..205793b 100644
--- a/runtime/bin/socket_macos.cc
+++ b/runtime/bin/socket_macos.cc
@@ -28,17 +28,17 @@
SocketAddress::SocketAddress(struct sockaddr* sa) {
ASSERT(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN);
if (!Socket::FormatNumericAddress(
- reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
+ *reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
as_string_[0] = 0;
}
- socklen_t salen = GetAddrLength(reinterpret_cast<RawAddr*>(sa));
+ socklen_t salen = GetAddrLength(*reinterpret_cast<RawAddr*>(sa));
memmove(reinterpret_cast<void *>(&addr_), sa, salen);
}
-bool Socket::FormatNumericAddress(RawAddr* addr, char* address, int len) {
+bool Socket::FormatNumericAddress(const RawAddr& addr, char* address, int len) {
socklen_t salen = SocketAddress::GetAddrLength(addr);
- if (NO_RETRY_EXPECTED(getnameinfo(&addr->addr,
+ if (NO_RETRY_EXPECTED(getnameinfo(&addr.addr,
salen,
address,
len,
@@ -57,7 +57,7 @@
}
-static intptr_t Create(RawAddr addr) {
+static intptr_t Create(const RawAddr& addr) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.ss.ss_family, SOCK_STREAM, 0));
if (fd < 0) {
@@ -68,10 +68,9 @@
}
-static intptr_t Connect(intptr_t fd, RawAddr addr, const intptr_t port) {
- SocketAddress::SetAddrPort(&addr, port);
+static intptr_t Connect(intptr_t fd, const RawAddr& addr) {
intptr_t result = TEMP_FAILURE_RETRY(
- connect(fd, &addr.addr, SocketAddress::GetAddrLength(&addr)));
+ connect(fd, &addr.addr, SocketAddress::GetAddrLength(addr)));
if (result == 0 || errno == EINPROGRESS) {
return fd;
}
@@ -80,7 +79,7 @@
}
-intptr_t Socket::CreateConnect(const RawAddr& addr, const intptr_t port) {
+intptr_t Socket::CreateConnect(const RawAddr& addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
@@ -88,12 +87,11 @@
FDUtils::SetNonBlocking(fd);
- return Connect(fd, addr, port);
+ return Connect(fd, addr);
}
intptr_t Socket::CreateBindConnect(const RawAddr& addr,
- const intptr_t port,
const RawAddr& source_addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
@@ -101,13 +99,13 @@
}
intptr_t result = TEMP_FAILURE_RETRY(
- bind(fd, &source_addr.addr, SocketAddress::GetAddrLength(&source_addr)));
+ bind(fd, &source_addr.addr, SocketAddress::GetAddrLength(source_addr)));
if (result != 0 && errno != EINPROGRESS) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
- return Connect(fd, addr, port);
+ return Connect(fd, addr);
}
@@ -129,8 +127,8 @@
}
-intptr_t Socket::RecvFrom(intptr_t fd, void* buffer, intptr_t num_bytes,
- RawAddr* addr) {
+intptr_t Socket::RecvFrom(
+ intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
ASSERT(fd >= 0);
socklen_t addr_len = sizeof(addr->ss);
ssize_t read_bytes = TEMP_FAILURE_RETRY(
@@ -157,12 +155,12 @@
}
-intptr_t Socket::SendTo(intptr_t fd, const void* buffer, intptr_t num_bytes,
- RawAddr addr) {
+intptr_t Socket::SendTo(
+ intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
ASSERT(fd >= 0);
ssize_t written_bytes = TEMP_FAILURE_RETRY(
sendto(fd, buffer, num_bytes, 0,
- &addr.addr, SocketAddress::GetAddrLength(&addr)));
+ &addr.addr, SocketAddress::GetAddrLength(addr)));
ASSERT(EAGAIN == EWOULDBLOCK);
if (written_bytes == -1 && errno == EWOULDBLOCK) {
// If the would block we need to retry and therefore return 0 as
@@ -180,7 +178,7 @@
if (NO_RETRY_EXPECTED(getsockname(fd, &raw.addr, &size))) {
return 0;
}
- return SocketAddress::GetAddrPort(&raw);
+ return SocketAddress::GetAddrPort(raw);
}
@@ -191,7 +189,7 @@
if (NO_RETRY_EXPECTED(getpeername(fd, &raw.addr, &size))) {
return NULL;
}
- *port = SocketAddress::GetAddrPort(&raw);
+ *port = SocketAddress::GetAddrPort(raw);
return new SocketAddress(&raw.addr);
}
@@ -259,14 +257,14 @@
}
-bool Socket::ReverseLookup(RawAddr addr,
+bool Socket::ReverseLookup(const RawAddr& addr,
char* host,
intptr_t host_len,
OSError** os_error) {
ASSERT(host_len >= NI_MAXHOST);
int status = NO_RETRY_EXPECTED(getnameinfo(
&addr.addr,
- SocketAddress::GetAddrLength(&addr),
+ SocketAddress::GetAddrLength(addr),
host,
host_len,
NULL,
@@ -295,11 +293,10 @@
}
-intptr_t Socket::CreateBindDatagram(
- RawAddr* addr, intptr_t port, bool reuseAddress) {
+intptr_t Socket::CreateBindDatagram(const RawAddr& addr, bool reuseAddress) {
intptr_t fd;
- fd = NO_RETRY_EXPECTED(socket(addr->addr.sa_family, SOCK_DGRAM, IPPROTO_UDP));
+ fd = NO_RETRY_EXPECTED(socket(addr.addr.sa_family, SOCK_DGRAM, IPPROTO_UDP));
if (fd < 0) return -1;
FDUtils::SetCloseOnExec(fd);
@@ -310,9 +307,8 @@
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)));
}
- SocketAddress::SetAddrPort(addr, port);
if (NO_RETRY_EXPECTED(
- bind(fd, &addr->addr, SocketAddress::GetAddrLength(addr))) < 0) {
+ bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
@@ -373,8 +369,7 @@
}
-intptr_t ServerSocket::CreateBindListen(RawAddr addr,
- intptr_t port,
+intptr_t ServerSocket::CreateBindListen(const RawAddr& addr,
intptr_t backlog,
bool v6_only) {
intptr_t fd;
@@ -394,18 +389,17 @@
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)));
}
- SocketAddress::SetAddrPort(&addr, port);
if (NO_RETRY_EXPECTED(
- bind(fd, &addr.addr, SocketAddress::GetAddrLength(&addr))) < 0) {
+ bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
// Test for invalid socket port 65535 (some browsers disallow it).
- if (port == 0 && Socket::GetPort(fd) == 65535) {
+ if (SocketAddress::GetAddrPort(addr) == 0 && Socket::GetPort(fd) == 65535) {
// Don't close the socket until we have created a new socket, ensuring
// that we do not get the bad port number again.
- intptr_t new_fd = CreateBindListen(addr, 0, backlog, v6_only);
+ intptr_t new_fd = CreateBindListen(addr, backlog, v6_only);
int err = errno;
VOID_TEMP_FAILURE_RETRY(close(fd));
errno = err;
@@ -568,18 +562,18 @@
static bool JoinOrLeaveMulticast(intptr_t fd,
- RawAddr* addr,
- RawAddr* interface,
+ const RawAddr& addr,
+ const RawAddr& interface,
int interfaceIndex,
bool join) {
- if (addr->addr.sa_family == AF_INET) {
- ASSERT(interface->addr.sa_family == AF_INET);
+ if (addr.addr.sa_family == AF_INET) {
+ ASSERT(interface.addr.sa_family == AF_INET);
struct ip_mreq mreq;
memmove(&mreq.imr_multiaddr,
- &addr->in.sin_addr,
+ &addr.in.sin_addr,
SocketAddress::GetInAddrLength(addr));
memmove(&mreq.imr_interface,
- &interface->in.sin_addr,
+ &interface.in.sin_addr,
SocketAddress::GetInAddrLength(interface));
if (join) {
return NO_RETRY_EXPECTED(setsockopt(
@@ -589,10 +583,10 @@
fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq))) == 0;
}
} else {
- ASSERT(addr->addr.sa_family == AF_INET6);
+ ASSERT(addr.addr.sa_family == AF_INET6);
struct ipv6_mreq mreq;
memmove(&mreq.ipv6mr_multiaddr,
- &addr->in6.sin6_addr,
+ &addr.in6.sin6_addr,
SocketAddress::GetInAddrLength(addr));
mreq.ipv6mr_interface = interfaceIndex;
if (join) {
@@ -605,14 +599,18 @@
}
}
-bool Socket::JoinMulticast(
- intptr_t fd, RawAddr* addr, RawAddr* interface, int interfaceIndex) {
+bool Socket::JoinMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr& interface,
+ int interfaceIndex) {
return JoinOrLeaveMulticast(fd, addr, interface, interfaceIndex, true);
}
-bool Socket::LeaveMulticast(
- intptr_t fd, RawAddr* addr, RawAddr* interface, int interfaceIndex) {
+bool Socket::LeaveMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr& interface,
+ int interfaceIndex) {
return JoinOrLeaveMulticast(fd, addr, interface, interfaceIndex, false);
}
diff --git a/runtime/bin/socket_win.cc b/runtime/bin/socket_win.cc
index e366430..451d7f6 100644
--- a/runtime/bin/socket_win.cc
+++ b/runtime/bin/socket_win.cc
@@ -23,25 +23,26 @@
// Clear the port before calling WSAAddressToString as WSAAddressToString
// includes the port in the formatted string.
- int err = Socket::FormatNumericAddress(raw, as_string_, INET6_ADDRSTRLEN);
+ int err = Socket::FormatNumericAddress(*raw, as_string_, INET6_ADDRSTRLEN);
if (err != 0) {
as_string_[0] = 0;
}
memmove(reinterpret_cast<void *>(&addr_),
sockaddr,
- SocketAddress::GetAddrLength(raw));
+ SocketAddress::GetAddrLength(*raw));
}
-bool Socket::FormatNumericAddress(RawAddr* addr, char* address, int len) {
+bool Socket::FormatNumericAddress(const RawAddr& addr, char* address, int len) {
socklen_t salen = SocketAddress::GetAddrLength(addr);
DWORD l = len;
- return WSAAddressToStringA(&addr->addr,
- salen,
- NULL,
- address,
- &l) != 0;
+ RawAddr& raw = const_cast<RawAddr&>(addr);
+ return WSAAddressToStringA(&raw.addr,
+ salen,
+ NULL,
+ address,
+ &l) != 0;
}
@@ -75,8 +76,8 @@
}
-intptr_t Socket::RecvFrom(intptr_t fd, void* buffer, intptr_t num_bytes,
- RawAddr* addr) {
+intptr_t Socket::RecvFrom(
+ intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
Handle* handle = reinterpret_cast<Handle*>(fd);
socklen_t addr_len = sizeof(addr->ss);
return handle->RecvFrom(buffer, num_bytes, &addr->addr, addr_len);
@@ -90,10 +91,11 @@
intptr_t Socket::SendTo(
- intptr_t fd, const void* buffer, intptr_t num_bytes, RawAddr addr) {
+ intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
Handle* handle = reinterpret_cast<Handle*>(fd);
+ RawAddr& raw = const_cast<RawAddr&>(addr);
return handle->SendTo(
- buffer, num_bytes, &addr.addr, SocketAddress::GetAddrLength(&addr));
+ buffer, num_bytes, &raw.addr, SocketAddress::GetAddrLength(addr));
}
@@ -107,7 +109,7 @@
&size) == SOCKET_ERROR) {
return 0;
}
- return SocketAddress::GetAddrPort(&raw);
+ return SocketAddress::GetAddrPort(raw);
}
@@ -121,7 +123,7 @@
&size)) {
return NULL;
}
- *port = SocketAddress::GetAddrPort(&raw);
+ *port = SocketAddress::GetAddrPort(raw);
// Clear the port before calling WSAAddressToString as WSAAddressToString
// includes the port in the formatted string.
SocketAddress::SetAddrPort(&raw, 0);
@@ -129,7 +131,7 @@
}
-static intptr_t Create(RawAddr addr) {
+static intptr_t Create(const RawAddr& addr) {
SOCKET s = socket(addr.ss.ss_family, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
return -1;
@@ -153,13 +155,13 @@
static intptr_t Connect(
- intptr_t fd, RawAddr addr, const intptr_t port, RawAddr bind_addr) {
+ intptr_t fd, const RawAddr& addr, const RawAddr& bind_addr) {
ASSERT(reinterpret_cast<Handle*>(fd)->is_client_socket());
ClientSocket* handle = reinterpret_cast<ClientSocket*>(fd);
SOCKET s = handle->socket();
int status = bind(
- s, &bind_addr.addr, SocketAddress::GetAddrLength(&bind_addr));
+ s, &bind_addr.addr, SocketAddress::GetAddrLength(bind_addr));
if (status != NO_ERROR) {
int rc = WSAGetLastError();
handle->mark_closed(); // Destructor asserts that socket is marked closed.
@@ -169,8 +171,6 @@
return -1;
}
- SocketAddress::SetAddrPort(&addr, port);
-
LPFN_CONNECTEX connectEx = NULL;
GUID guid_connect_ex = WSAID_CONNECTEX;
DWORD bytes;
@@ -191,7 +191,7 @@
status = connectEx(s,
&addr.addr,
- SocketAddress::GetAddrLength(&addr),
+ SocketAddress::GetAddrLength(addr),
NULL,
0,
NULL,
@@ -217,7 +217,7 @@
}
-intptr_t Socket::CreateConnect(const RawAddr& addr, const intptr_t port) {
+intptr_t Socket::CreateConnect(const RawAddr& addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
@@ -232,19 +232,18 @@
bind_addr.in6.sin6_addr = in6addr_any;
}
- return Connect(fd, addr, port, bind_addr);
+ return Connect(fd, addr, bind_addr);
}
intptr_t Socket::CreateBindConnect(const RawAddr& addr,
- const intptr_t port,
const RawAddr& source_addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
}
- return Connect(fd, addr, port, source_addr);
+ return Connect(fd, addr, source_addr);
}
@@ -333,13 +332,13 @@
}
-bool Socket::ReverseLookup(RawAddr addr,
+bool Socket::ReverseLookup(const RawAddr& addr,
char* host,
intptr_t host_len,
OSError** os_error) {
ASSERT(host_len >= NI_MAXHOST);
int status = getnameinfo(&addr.addr,
- SocketAddress::GetAddrLength(&addr),
+ SocketAddress::GetAddrLength(addr),
host,
host_len,
NULL,
@@ -370,9 +369,8 @@
}
-intptr_t Socket::CreateBindDatagram(
- RawAddr* addr, intptr_t port, bool reuseAddress) {
- SOCKET s = socket(addr->ss.ss_family, SOCK_DGRAM, IPPROTO_UDP);
+intptr_t Socket::CreateBindDatagram(const RawAddr& addr, bool reuseAddress) {
+ SOCKET s = socket(addr.ss.ss_family, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET) {
return -1;
}
@@ -393,10 +391,8 @@
}
}
- SocketAddress::SetAddrPort(addr, port);
-
status = bind(s,
- &addr->addr,
+ &addr.addr,
SocketAddress::GetAddrLength(addr));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
@@ -468,8 +464,7 @@
}
-intptr_t ServerSocket::CreateBindListen(RawAddr addr,
- intptr_t port,
+intptr_t ServerSocket::CreateBindListen(const RawAddr& addr,
intptr_t backlog,
bool v6_only) {
SOCKET s = socket(addr.ss.ss_family, SOCK_STREAM, IPPROTO_TCP);
@@ -499,10 +494,9 @@
sizeof(optval));
}
- SocketAddress::SetAddrPort(&addr, port);
status = bind(s,
&addr.addr,
- SocketAddress::GetAddrLength(&addr));
+ SocketAddress::GetAddrLength(addr));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
@@ -513,11 +507,11 @@
ListenSocket* listen_socket = new ListenSocket(s);
// Test for invalid socket port 65535 (some browsers disallow it).
- if (port == 0 &&
+ if (SocketAddress::GetAddrPort(addr) == 0 &&
Socket::GetPort(reinterpret_cast<intptr_t>(listen_socket)) == 65535) {
// Don't close fd until we have created new. By doing that we ensure another
// port.
- intptr_t new_s = CreateBindListen(addr, 0, backlog, v6_only);
+ intptr_t new_s = CreateBindListen(addr, backlog, v6_only);
DWORD rc = WSAGetLastError();
closesocket(s);
delete listen_socket;
@@ -687,12 +681,12 @@
bool Socket::JoinMulticast(
- intptr_t fd, RawAddr* addr, RawAddr*, int interfaceIndex) {
+ intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
- int proto = addr->addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
+ int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
- memmove(&mreq.gr_group, &addr->ss, SocketAddress::GetAddrLength(addr));
+ memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
return setsockopt(handle->socket(),
proto,
MCAST_JOIN_GROUP,
@@ -702,12 +696,12 @@
bool Socket::LeaveMulticast(
- intptr_t fd, RawAddr* addr, RawAddr*, int interfaceIndex) {
+ intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
- int proto = addr->addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
+ int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
- memmove(&mreq.gr_group, &addr->ss, SocketAddress::GetAddrLength(addr));
+ memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
return setsockopt(handle->socket(),
proto,
MCAST_LEAVE_GROUP,
diff --git a/runtime/bin/vmservice_impl.cc b/runtime/bin/vmservice_impl.cc
index 1b9654b..4a54291 100644
--- a/runtime/bin/vmservice_impl.cc
+++ b/runtime/bin/vmservice_impl.cc
@@ -266,6 +266,9 @@
snprintf(&buffer[0], kBufferSize-1, "%s/%s", kLibrarySourceNamePrefix, name);
const char* vmservice_source = NULL;
int r = Resources::ResourceLookup(buffer, &vmservice_source);
+ if (r == Resources::kNoSuchInstance) {
+ FATAL1("vm-service: Could not find embedded source file: %s ", buffer);
+ }
ASSERT(r != Resources::kNoSuchInstance);
return Dart_NewStringFromCString(vmservice_source);
}
diff --git a/runtime/lib/bigint.dart b/runtime/lib/bigint.dart
index 7519ac1..cad1562 100644
--- a/runtime/lib/bigint.dart
+++ b/runtime/lib/bigint.dart
@@ -1078,7 +1078,6 @@
Uint32List yt_qd,
Uint32List t_digits,
Uint32List r_digits) {
- assert(y_used > 0 && x_used >= y_used);
// Initialize r_digits to normalized positive dividend.
var r_used = _lShiftDigits(x_digits, x_used, nsh, r_digits);
// For 64-bit processing, make sure y_used, i, and j are even.
@@ -1345,16 +1344,17 @@
if (e < 0) throw new RangeError(e);
if (m <= 0) throw new RangeError(m);
if (e == 0) return 1;
- e = e._toBigint();
m = m._toBigint();
final m_used = m._used;
final m_used2p2 = 2*m_used + 2;
final e_bitlen = e.bitLength;
if (e_bitlen <= 0) return 1;
- if ((e is! _Bigint) || m.isEven) {
- _Reduction z = (e_bitlen < 8 || m.isEven) ?
+ final bool cannotUseMontgomery = m.isEven || _abs() >= m;
+ if (cannotUseMontgomery || e_bitlen < 64) {
+ _Reduction z = (cannotUseMontgomery || e_bitlen < 8) ?
new _Classic(m) : new _Montgomery(m);
- // TODO(regis): Should we use Barrett reduction for an even modulus?
+ // TODO(regis): Should we use Barrett reduction for an even modulus and a
+ // large exponent?
var r_digits = new Uint32List(m_used2p2);
var r2_digits = new Uint32List(m_used2p2);
var g_digits = new Uint32List(m_used + (m_used & 1));
@@ -1382,6 +1382,7 @@
}
return z._revert(r_digits, r_used)._toValidInt();
}
+ e = e._toBigint();
var k;
if (e_bitlen < 18) k = 1;
else if (e_bitlen < 48) k = 3;
@@ -1588,6 +1589,8 @@
// r = x*R mod _m.
// Return r_used.
int _convert(_Bigint x, Uint32List r_digits) {
+ // Montgomery reduction only works if abs(x) < _m.
+ assert(x._abs() < _m);
var r = x._abs()._dlShift(_m._used)._rem(_m);
if (x._neg && !r._neg && r._used > 0) {
r = _m._sub(r);
@@ -1695,7 +1698,7 @@
// _neg_norm_m_digits is read-only and has nm_used digits (possibly
// including several leading zeros) plus a leading zero for 64-bit
// processing.
- _t_digits = new Uint32List(2*nm_used);
+ _t_digits = new Uint32List(2*nm_used + 2);
}
int _convert(_Bigint x, Uint32List r_digits) {
diff --git a/runtime/lib/collection_patch.dart b/runtime/lib/collection_patch.dart
index e100c75..ebaba41 100644
--- a/runtime/lib/collection_patch.dart
+++ b/runtime/lib/collection_patch.dart
@@ -918,6 +918,8 @@
if (equals == null) {
if (_useInternalCached) {
return new _InternalLinkedHashMap<K, V>();
+ } else if (_useCompactCached) {
+ return new _CompactLinkedHashMap<K, V>();
} else {
return new _LinkedHashMap<K, V>();
}
@@ -947,6 +949,8 @@
static final bool _useInternalCached = _useInternal;
static bool get _useInternal native "LinkedHashMap_useInternal";
+ static final bool _useCompactCached = _useCompact;
+ static bool get _useCompact native "LinkedHashMap_useCompact";
}
// Methods that are exactly the same in all three linked hash map variants.
@@ -1063,7 +1067,11 @@
if (isValidKey == null) {
if (hashCode == null) {
if (equals == null) {
- return new _LinkedHashSet<E>();
+ if (LinkedHashMap._useCompactCached) {
+ return new _CompactLinkedHashSet<E>();
+ } else {
+ return new _LinkedHashSet<E>();
+ }
}
hashCode = _defaultHashCode;
} else {
diff --git a/runtime/lib/collection_sources.gypi b/runtime/lib/collection_sources.gypi
index 0e9eb4d..4cb695b 100644
--- a/runtime/lib/collection_sources.gypi
+++ b/runtime/lib/collection_sources.gypi
@@ -5,6 +5,7 @@
{
'sources': [
'collection_patch.dart',
+ 'compact_hash.dart',
'linked_hash_map.cc',
'linked_hash_map.dart',
],
diff --git a/runtime/lib/compact_hash.dart b/runtime/lib/compact_hash.dart
new file mode 100644
index 0000000..0dd7963
--- /dev/null
+++ b/runtime/lib/compact_hash.dart
@@ -0,0 +1,473 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:typed_data';
+
+// Hash table with open addressing that separates the index from keys/values.
+abstract class _HashBase {
+ // Each occupied entry in _index is a fixed-size integer that encodes a pair:
+ // [ hash pattern for key | index of entry in _data ]
+ // The hash pattern is based on hashCode, but is guaranteed to be non-zero.
+ // The length of _index is always a power of two, and there is always at
+ // least one unoccupied entry.
+ Uint32List _index;
+
+ // The number of bits used for each component is determined by table size.
+ // The length of _index is twice the number of entries in _data, and both
+ // are doubled when _data is full. Thus, _index will have a max load factor
+ // of 1/2, which enables one more bit to be used for the hash.
+ // TODO(koda): Consider growing _data by factor sqrt(2), twice as often.
+ static const int _INITIAL_INDEX_BITS = 3;
+ static const int _INITIAL_INDEX_SIZE = 1 << (_INITIAL_INDEX_BITS + 1);
+
+ // Unused and deleted entries are marked by 0 and 1, respectively.
+ static const int _UNUSED_PAIR = 0;
+ static const int _DELETED_PAIR = 1;
+
+ // Cached in-place mask for the hash pattern component. On 32-bit, the top
+ // bits are wasted to avoid Mint allocation.
+ // TODO(koda): Reclaim the bits by making the compiler treat hash patterns
+ // as unsigned words.
+ int _hashMask = int.is64Bit() ?
+ (1 << (32 - _INITIAL_INDEX_BITS)) - 1 :
+ (1 << (30 - _INITIAL_INDEX_BITS)) - 1;
+
+ static int _hashPattern(int fullHash, int hashMask, int size) {
+ final int maskedHash = fullHash & hashMask;
+ // TODO(koda): Consider keeping bit length and use left shift.
+ return (maskedHash == 0) ? (size >> 1) : maskedHash * (size >> 1);
+ }
+
+ // Linear probing.
+ static int _firstProbe(int fullHash, int sizeMask) {
+ final int i = fullHash & sizeMask;
+ // Light, fast shuffle to mitigate bad hashCode (e.g., sequential).
+ return ((i << 1) + i) & sizeMask;
+ }
+ static int _nextProbe(int i, int sizeMask) => (i + 1) & sizeMask;
+
+ // Fixed-length list of keys (set) or key/value at even/odd indices (map).
+ List _data;
+ // Length of _data that is used (i.e., keys + values for a map).
+ int _usedData = 0;
+ // Number of deleted keys.
+ int _deletedKeys = 0;
+
+ // A self-loop is used to mark a deleted key or value.
+ static bool _isDeleted(List data, Object keyOrValue) =>
+ identical(keyOrValue, data);
+ static void _setDeletedAt(List data, int d) {
+ data[d] = data;
+ }
+
+ // Concurrent modification detection relies on this checksum monotonically
+ // increasing between reallocations of _data.
+ int get _checkSum => _usedData + _deletedKeys;
+ bool _isModifiedSince(List oldData, int oldCheckSum) =>
+ !identical(_data, oldData) || (_checkSum != oldCheckSum);
+}
+
+// Map with iteration in insertion order (hence "Linked"). New keys are simply
+// appended to _data.
+class _CompactLinkedHashMap<K, V>
+ extends MapBase<K, V> with _HashBase
+ implements HashMap<K, V>, LinkedHashMap<K, V> {
+
+ _CompactLinkedHashMap() {
+ assert(_HashBase._UNUSED_PAIR == 0);
+ _index = new Uint32List(_HashBase._INITIAL_INDEX_SIZE);
+ _data = new List(_HashBase._INITIAL_INDEX_SIZE);
+ }
+
+ int get length => (_usedData >> 1) - _deletedKeys;
+ bool get isEmpty => length == 0;
+ bool get isNotEmpty => !isEmpty;
+
+ void _rehash() {
+ if ((_deletedKeys << 1) > _usedData) {
+ // TODO(koda): Consider shrinking.
+ // TODO(koda): Consider in-place compaction and more costly CME check.
+ _init(_index.length, _hashMask, _data, _usedData);
+ } else {
+ // TODO(koda): Support 32->64 bit transition (and adjust _hashMask).
+ _init(_index.length << 1, _hashMask >> 1, _data, _usedData);
+ }
+ }
+
+ void clear() {
+ if (!isEmpty) {
+ _init(_index.length, _hashMask);
+ }
+ }
+
+ // Allocate new _index and _data, and optionally copy existing contents.
+ void _init(int size, int hashMask, [List oldData, int oldUsed]) {
+ assert(size & (size - 1) == 0);
+ assert(_HashBase._UNUSED_PAIR == 0);
+ _index = new Uint32List(size);
+ _hashMask = hashMask;
+ _data = new List(size);
+ _usedData = 0;
+ _deletedKeys = 0;
+ if (oldData != null) {
+ for (int i = 0; i < oldUsed; i += 2) {
+ var key = oldData[i];
+ if (!_HashBase._isDeleted(oldData, key)) {
+ // TODO(koda): While there are enough hash bits, avoid hashCode calls.
+ this[key] = oldData[i + 1];
+ }
+ }
+ }
+ }
+
+ void _insert(K key, V value, int hashPattern, int i) {
+ if (_usedData == _data.length) {
+ _rehash();
+ this[key] = value;
+ } else {
+ assert(1 <= hashPattern && hashPattern < (1 << 32));
+ final int index = _usedData >> 1;
+ assert((index & hashPattern) == 0);
+ _index[i] = hashPattern | index;
+ _data[_usedData++] = key;
+ _data[_usedData++] = value;
+ }
+ }
+
+ // If key is present, returns the index of the value in _data, else returns
+ // the negated insertion point in _index.
+ int _findValueOrInsertPoint(K key, int fullHash, int hashPattern, int size) {
+ final int sizeMask = size - 1;
+ final int maxEntries = size >> 1;
+ int i = _HashBase._firstProbe(fullHash, sizeMask);
+ int firstDeleted = -1;
+ int pair = _index[i];
+ while (pair != _HashBase._UNUSED_PAIR) {
+ if (pair == _HashBase._DELETED_PAIR) {
+ if (firstDeleted < 0){
+ firstDeleted = i;
+ }
+ } else {
+ final int entry = hashPattern ^ pair;
+ if (entry < maxEntries) {
+ final int d = entry << 1;
+ if (key == _data[d]) {
+ return d + 1;
+ }
+ }
+ }
+ i = _HashBase._nextProbe(i, sizeMask);
+ pair = _index[i];
+ }
+ return firstDeleted >= 0 ? -firstDeleted : -i;
+ }
+
+ void operator[]=(K key, V value) {
+ final int size = _index.length;
+ final int sizeMask = size - 1;
+ final int fullHash = key.hashCode;
+ final int hashPattern = _HashBase._hashPattern(fullHash, _hashMask, size);
+ final int d = _findValueOrInsertPoint(key, fullHash, hashPattern, size);
+ if (d > 0) {
+ _data[d] = value;
+ } else {
+ final int i = -d;
+ _insert(key, value, hashPattern, i);
+ }
+ }
+
+ V putIfAbsent(K key, V ifAbsent()) {
+ final int size = _index.length;
+ final int sizeMask = size - 1;
+ final int maxEntries = size >> 1;
+ final int fullHash = key.hashCode;
+ final int hashPattern = _HashBase._hashPattern(fullHash, _hashMask, size);
+ final int d = _findValueOrInsertPoint(key, fullHash, hashPattern, size);
+ if (d > 0) {
+ return _data[d];
+ }
+ // 'ifAbsent' is allowed to modify the map.
+ List oldData = _data;
+ int oldCheckSum = _checkSum;
+ V value = ifAbsent();
+ if (_isModifiedSince(oldData, oldCheckSum)) {
+ this[key] = value;
+ } else {
+ final int i = -d;
+ _insert(key, value, hashPattern, i);
+ }
+ return value;
+ }
+
+ V remove(Object key) {
+ final int size = _index.length;
+ final int sizeMask = size - 1;
+ final int maxEntries = size >> 1;
+ final int fullHash = key.hashCode;
+ final int hashPattern = _HashBase._hashPattern(fullHash, _hashMask, size);
+ int i = _HashBase._firstProbe(fullHash, sizeMask);
+ int pair = _index[i];
+ while (pair != _HashBase._UNUSED_PAIR) {
+ if (pair != _HashBase._DELETED_PAIR) {
+ final int entry = hashPattern ^ pair;
+ if (entry < maxEntries) {
+ final int d = entry << 1;
+ if (key == _data[d]) {
+ _index[i] = _HashBase._DELETED_PAIR;
+ _HashBase._setDeletedAt(_data, d);
+ V value = _data[d + 1];
+ _HashBase._setDeletedAt(_data, d + 1);
+ ++_deletedKeys;
+ return value;
+ }
+ }
+ }
+ i = _HashBase._nextProbe(i, sizeMask);
+ pair = _index[i];
+ }
+ return null;
+ }
+
+ // If key is absent, return _data (which is never a value).
+ Object _getValueOrData(Object key) {
+ final int size = _index.length;
+ final int sizeMask = size - 1;
+ final int maxEntries = size >> 1;
+ final int fullHash = key.hashCode;
+ final int hashPattern = _HashBase._hashPattern(fullHash, _hashMask, size);
+ int i = _HashBase._firstProbe(fullHash, sizeMask);
+ int pair = _index[i];
+ while (pair != _HashBase._UNUSED_PAIR) {
+ if (pair != _HashBase._DELETED_PAIR) {
+ final int entry = hashPattern ^ pair;
+ if (entry < maxEntries) {
+ final int d = entry << 1;
+ if (key == _data[d]) {
+ return _data[d + 1];
+ }
+ }
+ }
+ i = _HashBase._nextProbe(i, sizeMask);
+ pair = _index[i];
+ }
+ return _data;
+ }
+
+ bool containsKey(Object key) => !identical(_data, _getValueOrData(key));
+
+ V operator[](Object key) {
+ var v = _getValueOrData(key);
+ return identical(_data, v) ? null : v;
+ }
+
+ bool containsValue(Object value) {
+ for (var v in values) {
+ if (v == value) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void forEach(void f(K key, V value)) {
+ var ki = keys.iterator;
+ var vi = values.iterator;
+ while (ki.moveNext()) {
+ vi.moveNext();
+ f(ki.current, vi.current);
+ }
+ }
+
+ Iterable<K> get keys =>
+ new _CompactIterable<K>(this, _data, _usedData, -2, 2);
+ Iterable<V> get values =>
+ new _CompactIterable<V>(this, _data, _usedData, -1, 2);
+}
+
+// Iterates through _data[_offset + _step], _data[_offset + 2*_step], ...
+// and checks for concurrent modification.
+class _CompactIterable<E> extends IterableBase<E> {
+ final _table;
+ final List _data;
+ final int _len;
+ final int _offset;
+ final int _step;
+
+ _CompactIterable(this._table, this._data, this._len,
+ this._offset, this._step);
+
+ Iterator<E> get iterator =>
+ new _CompactIterator<E>(_table, _data, _len, _offset, _step);
+
+ int get length => _table.length;
+ bool get isEmpty => length == 0;
+ bool get isNotEmpty => !isEmpty;
+}
+
+class _CompactIterator<E> implements Iterator<E> {
+ final _table;
+ final List _data;
+ final int _len;
+ int _offset;
+ final int _step;
+ final int _checkSum;
+ E current;
+
+ _CompactIterator(table, this._data, this._len, this._offset, this._step) :
+ _table = table, _checkSum = table._checkSum;
+
+ bool moveNext() {
+ if (_table._isModifiedSince(_data, _checkSum)) {
+ throw new ConcurrentModificationError(_table);
+ }
+ do {
+ _offset += _step;
+ } while (_offset < _len && _HashBase._isDeleted(_data, _data[_offset]));
+ if (_offset < _len) {
+ current = _data[_offset];
+ return true;
+ } else {
+ current = null;
+ return false;
+ }
+ }
+}
+
+// Set implementation, analogous to _CompactLinkedHashMap.
+class _CompactLinkedHashSet<K>
+ extends SetBase<K> with _HashBase
+ implements HashSet<K>, LinkedHashSet<K> {
+
+ _CompactLinkedHashSet() {
+ assert(_HashBase._UNUSED_PAIR == 0);
+ _index = new Uint32List(_HashBase._INITIAL_INDEX_SIZE);
+ _data = new List(_HashBase._INITIAL_INDEX_SIZE >> 1);
+ }
+
+ int get length => _usedData - _deletedKeys;
+
+ void _rehash() {
+ if ((_deletedKeys << 1) > _usedData) {
+ _init(_index.length, _hashMask, _data, _usedData);
+ } else {
+ _init(_index.length << 1, _hashMask >> 1, _data, _usedData);
+ }
+ }
+
+ void clear() {
+ if (!isEmpty) {
+ _init(_index.length, _hashMask);
+ }
+ }
+
+ void _init(int size, int hashMask, [List oldData, int oldUsed]) {
+ _index = new Uint32List(size);
+ _hashMask = hashMask;
+ _data = new List(size >> 1);
+ _usedData = 0;
+ _deletedKeys = 0;
+ if (oldData != null) {
+ for (int i = 0; i < oldUsed; i += 1) {
+ var key = oldData[i];
+ if (!_HashBase._isDeleted(oldData, key)) {
+ add(key);
+ }
+ }
+ }
+ }
+
+ bool add(Object key) {
+ final int size = _index.length;
+ final int sizeMask = size - 1;
+ final int maxEntries = size >> 1;
+ final int fullHash = key.hashCode;
+ final int hashPattern = _HashBase._hashPattern(fullHash, _hashMask, size);
+ int i = _HashBase._firstProbe(fullHash, sizeMask);
+ int firstDeleted = -1;
+ int pair = _index[i];
+ while (pair != _HashBase._UNUSED_PAIR) {
+ if (pair == _HashBase._DELETED_PAIR) {
+ if (firstDeleted < 0){
+ firstDeleted = i;
+ }
+ } else {
+ final int d = hashPattern ^ pair;
+ if (d < maxEntries && key == _data[d]) {
+ return false;
+ }
+ }
+ i = _HashBase._nextProbe(i, sizeMask);
+ pair = _index[i];
+ }
+ if (_usedData == _data.length) {
+ _rehash();
+ add(key);
+ } else {
+ final int insertionPoint = (firstDeleted >= 0) ? firstDeleted : i;
+ assert(1 <= hashPattern && hashPattern < (1 << 32));
+ assert((hashPattern & _usedData) == 0);
+ _index[insertionPoint] = hashPattern | _usedData;
+ _data[_usedData++] = key;
+ }
+ return true;
+ }
+
+ // If key is absent, return _data (which is never a value).
+ Object _getKeyOrData(Object key) {
+ final int size = _index.length;
+ final int sizeMask = size - 1;
+ final int maxEntries = size >> 1;
+ final int fullHash = key.hashCode;
+ final int hashPattern = _HashBase._hashPattern(fullHash, _hashMask, size);
+ int i = _HashBase._firstProbe(fullHash, sizeMask);
+ int pair = _index[i];
+ while (pair != _HashBase._UNUSED_PAIR) {
+ if (pair != _HashBase._DELETED_PAIR) {
+ final int d = hashPattern ^ pair;
+ if (d < maxEntries && key == _data[d]) {
+ return _data[d]; // Note: Must return the existing key.
+ }
+ }
+ i = _HashBase._nextProbe(i, sizeMask);
+ pair = _index[i];
+ }
+ return _data;
+ }
+
+ K lookup(Object key) {
+ var k = _getKeyOrData(key);
+ return identical(_data, k) ? null : k;
+ }
+
+ bool contains(Object key) => !identical(_data, _getKeyOrData(key));
+
+ bool remove(Object key) {
+ final int size = _index.length;
+ final int sizeMask = size - 1;
+ final int maxEntries = size >> 1;
+ final int fullHash = key.hashCode;
+ final int hashPattern = _HashBase._hashPattern(fullHash, _hashMask, size);
+ int i = _HashBase._firstProbe(fullHash, sizeMask);
+ int pair = _index[i];
+ while (pair != _HashBase._UNUSED_PAIR) {
+ if (pair != _HashBase._DELETED_PAIR) {
+ final int d = hashPattern ^ pair;
+ if (d < maxEntries && key == _data[d]) {
+ _index[i] = _HashBase._DELETED_PAIR;
+ _HashBase._setDeletedAt(_data, d);
+ ++_deletedKeys;
+ return true;
+ }
+ }
+ i = _HashBase._nextProbe(i, sizeMask);
+ pair = _index[i];
+ }
+ return false;
+ }
+
+ Iterator<K> get iterator =>
+ new _CompactIterator<K>(this, _data, _usedData, -1, 1);
+
+ Set<K> toSet() => new Set<K>()..addAll(this);
+}
diff --git a/runtime/lib/core_patch.dart b/runtime/lib/core_patch.dart
index 5f1f828..4d434b7 100644
--- a/runtime/lib/core_patch.dart
+++ b/runtime/lib/core_patch.dart
@@ -5,6 +5,10 @@
import "dart:math";
import "dart:typed_data";
+// Equivalent of calling FATAL from C++ code.
+_fatal(msg) native "DartCore_fatal";
+
+
// We need to pass the exception and stack trace objects as second and third
// parameter to the continuation. See vm/ast_transformer.cc for usage.
void _asyncCatchHelper(catchFunction, continuation) {
diff --git a/runtime/lib/core_sources.gypi b/runtime/lib/core_sources.gypi
index 96a7b19..d5be47e 100644
--- a/runtime/lib/core_sources.gypi
+++ b/runtime/lib/core_sources.gypi
@@ -47,7 +47,7 @@
'regexp_jsc.h',
'regexp_patch.dart',
'stacktrace.cc',
- 'stacktrace_patch.dart',
+ 'stacktrace.dart',
'stopwatch.cc',
'stopwatch_patch.dart',
'string.cc',
diff --git a/runtime/lib/linked_hash_map.cc b/runtime/lib/linked_hash_map.cc
index d8a5a89..a669bff 100644
--- a/runtime/lib/linked_hash_map.cc
+++ b/runtime/lib/linked_hash_map.cc
@@ -14,6 +14,8 @@
namespace dart {
DEFINE_FLAG(bool, use_internal_hash_map, false, "Use internal hash map.");
+DEFINE_FLAG(bool, use_compact_hash, true, "Use compact hash map and set.");
+>>>>>>> .merge-right.r43886
DEFINE_NATIVE_ENTRY(LinkedHashMap_allocate, 1) {
const TypeArguments& type_arguments =
@@ -90,7 +92,14 @@
DEFINE_NATIVE_ENTRY(LinkedHashMap_useInternal, 0) {
+ ASSERT(!(FLAG_use_internal_hash_map && FLAG_use_compact_hash));
return Bool::Get(FLAG_use_internal_hash_map).raw();
}
+
+DEFINE_NATIVE_ENTRY(LinkedHashMap_useCompact, 0) {
+ ASSERT(!(FLAG_use_internal_hash_map && FLAG_use_compact_hash));
+ return Bool::Get(FLAG_use_compact_hash).raw();
+}
+
} // namespace dart
diff --git a/runtime/lib/mirrors.cc b/runtime/lib/mirrors.cc
index 3a5ba02..079a1d0 100644
--- a/runtime/lib/mirrors.cc
+++ b/runtime/lib/mirrors.cc
@@ -381,7 +381,8 @@
static RawInstance* CreateLibraryDependencyMirror(const Instance& importer,
const Namespace& ns,
const String& prefix,
- bool is_import) {
+ const bool is_import,
+ const bool is_deferred) {
const Library& importee = Library::Handle(ns.library());
const Instance& importee_mirror =
Instance::Handle(CreateLibraryMirror(importee));
@@ -414,14 +415,14 @@
UNREACHABLE();
}
- const Array& args = Array::Handle(Array::New(6));
+ const Array& args = Array::Handle(Array::New(7));
args.SetAt(0, importer);
args.SetAt(1, importee_mirror);
args.SetAt(2, combinators);
args.SetAt(3, prefix);
args.SetAt(4, Bool::Get(is_import));
- args.SetAt(5, metadata);
- // is_deferred?
+ args.SetAt(5, Bool::Get(is_deferred));
+ args.SetAt(6, metadata);
return CreateMirror(Symbols::_LocalLibraryDependencyMirror(), args);
}
@@ -443,7 +444,7 @@
for (intptr_t i = 0; i < ports.Length(); i++) {
ns ^= ports.At(i);
if (!ns.IsNull()) {
- dep = CreateLibraryDependencyMirror(lib_mirror, ns, prefix, true);
+ dep = CreateLibraryDependencyMirror(lib_mirror, ns, prefix, true, false);
if (!dep.IsNull()) {
deps.Add(dep);
}
@@ -454,7 +455,7 @@
ports = lib.exports();
for (intptr_t i = 0; i < ports.Length(); i++) {
ns ^= ports.At(i);
- dep = CreateLibraryDependencyMirror(lib_mirror, ns, prefix, false);
+ dep = CreateLibraryDependencyMirror(lib_mirror, ns, prefix, false, false);
if (!dep.IsNull()) {
deps.Add(dep);
}
@@ -472,7 +473,8 @@
for (intptr_t i = 0; i < ports.Length(); i++) {
ns ^= ports.At(i);
if (!ns.IsNull()) {
- dep = CreateLibraryDependencyMirror(lib_mirror, ns, prefix, true);
+ dep = CreateLibraryDependencyMirror(lib_mirror, ns, prefix, true,
+ lib_prefix.is_deferred_load());
if (!dep.IsNull()) {
deps.Add(dep);
}
@@ -1902,23 +1904,86 @@
}
-DEFINE_NATIVE_ENTRY(MethodMirror_location, 1) {
- GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0));
- const Function& func = Function::Handle(ref.GetFunctionReferent());
- if (func.IsImplicitConstructor() || func.IsSignatureFunction()) {
- // These are synthetic methods; they have no source.
- return Instance::null();
+DEFINE_NATIVE_ENTRY(DeclarationMirror_location, 1) {
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, reflectee, arguments->NativeArgAt(0));
+ Object& decl = Object::Handle();
+ if (reflectee.IsMirrorReference()) {
+ const MirrorReference& decl_ref = MirrorReference::Cast(reflectee);
+ decl = decl_ref.referent();
+ } else if (reflectee.IsTypeParameter()) {
+ decl = reflectee.raw();
+ } else {
+ UNREACHABLE();
}
- const Script& script = Script::Handle(func.script());
+
+ Script& script = Script::Handle();
+ intptr_t token_pos = Scanner::kNoSourcePos;
+
+ if (decl.IsFunction()) {
+ const Function& func = Function::Cast(decl);
+ if (func.IsImplicitConstructor() || func.IsSignatureFunction()) {
+ // These are synthetic methods; they have no source.
+ return Instance::null();
+ }
+ script = func.script();
+ token_pos = func.token_pos();
+ } else if (decl.IsClass()) {
+ const Class& cls = Class::Cast(decl);
+ const bool is_typedef = cls.IsSignatureClass() &&
+ !cls.IsCanonicalSignatureClass();
+ if (cls.is_synthesized_class() &&
+ !is_typedef &&
+ !cls.is_mixin_app_alias() &&
+ !cls.is_enum_class()) {
+ return Instance::null(); // Synthetic.
+ }
+ script = cls.script();
+ token_pos = cls.token_pos();
+ } else if (decl.IsField()) {
+ const Field& field = Field::Cast(decl);
+ const Class& owner = Class::Handle(field.owner());
+ script = owner.script();
+ token_pos = field.token_pos();
+ } else if (decl.IsTypeParameter()) {
+ const TypeParameter& type_var = TypeParameter::Cast(decl);
+ const Class& owner = Class::Handle(type_var.parameterized_class());
+ script = owner.script();
+ token_pos = type_var.token_pos();
+ } else if (decl.IsLibrary()) {
+ const Library& lib = Library::Cast(decl);
+ if (lib.raw() == Library::NativeWrappersLibrary()) {
+ return Instance::null(); // No source.
+ }
+ const Array& scripts = Array::Handle(lib.LoadedScripts());
+ for (intptr_t i = 0; i < scripts.Length(); i++) {
+ script ^= scripts.At(i);
+ if (script.kind() == RawScript::kLibraryTag) break;
+ }
+ ASSERT(!script.IsNull());
+ const String& libname = String::Handle(lib.name());
+ if (libname.Length() == 0) {
+ // No library declaration.
+ const String& uri = String::Handle(script.url());
+ return CreateSourceLocation(uri, 1, 1);
+ }
+ const TokenStream& stream = TokenStream::Handle(script.tokens());
+ TokenStream::Iterator tkit(stream, 0);
+ if (tkit.CurrentTokenKind() == Token::kSCRIPTTAG) tkit.Advance();
+ token_pos = tkit.CurrentPosition();
+ }
+
+ ASSERT(!script.IsNull());
+ ASSERT(token_pos != Scanner::kNoSourcePos);
+
const String& uri = String::Handle(script.url());
intptr_t from_line = 0;
intptr_t from_col = 0;
if (script.HasSource()) {
- script.GetTokenLocation(func.token_pos(), &from_line, &from_col);
+ script.GetTokenLocation(token_pos, &from_line, &from_col);
} else {
// Avoid the slow path of printing the token stream when precise source
// information is not available.
- script.GetTokenLocation(func.token_pos(), &from_line, NULL);
+ script.GetTokenLocation(token_pos, &from_line, NULL);
}
// We should always have at least the line number.
ASSERT(from_line != 0);
diff --git a/runtime/lib/mirrors_impl.dart b/runtime/lib/mirrors_impl.dart
index acdfaff..fb43637 100644
--- a/runtime/lib/mirrors_impl.dart
+++ b/runtime/lib/mirrors_impl.dart
@@ -80,6 +80,9 @@
return buf.toString();
}
+SourceLocation _location(reflectee)
+ native "DeclarationMirror_location";
+
List _metadata(reflectee)
native 'DeclarationMirror_metadata';
@@ -325,9 +328,9 @@
[new _SyntheticSetterParameter(this, this._target)]);
}
+ SourceLocation get location => null;
List<InstanceMirror> get metadata => emptyList;
String get source => null;
- SourceLocation get location => null;
}
class _SyntheticSetterParameter implements ParameterMirror {
@@ -349,8 +352,8 @@
bool get isPrivate => false;
bool get hasDefaultValue => false;
InstanceMirror get defaultValue => null;
+ SourceLocation get location => null;
List<InstanceMirror> get metadata => emptyList;
- SourceLocation get location => throw new UnimplementedError();
}
abstract class _LocalObjectMirror extends _LocalMirror implements ObjectMirror {
@@ -637,7 +640,7 @@
final bool isTopLevel = true;
SourceLocation get location {
- throw new UnimplementedError('ClassMirror.location is not implemented');
+ return _location(_reflectee);
}
ClassMirror _trueSuperclassField;
@@ -1044,6 +1047,10 @@
bool get isPrivate => _n(simpleName).startsWith('_');
+ SourceLocation get location {
+ return _location(_reflectee);
+ }
+
List<InstanceMirror> get metadata {
// Get the metadata objects, convert them into InstanceMirrors using
// reflect() and then make them into a Dart list.
@@ -1076,11 +1083,6 @@
bool get isStatic => false;
bool get isTopLevel => false;
- SourceLocation get location {
- throw new UnimplementedError(
- 'TypeVariableMirror.location is not implemented');
- }
-
TypeMirror _upperBound = null;
TypeMirror get upperBound {
if (_upperBound == null) {
@@ -1155,10 +1157,6 @@
return _owner;
}
- SourceLocation get location {
- throw new UnimplementedError('TypedefMirror.location is not implemented');
- }
-
TypeMirror _referent = null;
TypeMirror get referent {
if (_referent == null) {
@@ -1264,10 +1262,6 @@
Type get _instantiator => null;
- SourceLocation get location {
- throw new UnimplementedError('LibraryMirror.location is not implemented');
- }
-
Map<Symbol, DeclarationMirror> _declarations;
Map<Symbol, DeclarationMirror> get declarations {
if (_declarations != null) return _declarations;
@@ -1283,6 +1277,10 @@
return _cachedMembers;
}
+ SourceLocation get location {
+ return _location(_reflectee);
+ }
+
List<InstanceMirror> get metadata {
// Get the metadata objects, convert them into InstanceMirrors using
// reflect() and then make them into a Dart list.
@@ -1329,6 +1327,7 @@
final List<CombinatorMirror> combinators;
final Symbol prefix;
final bool isImport;
+ final bool isDeferred;
final List<InstanceMirror> metadata;
_LocalLibraryDependencyMirror(this.sourceLibrary,
@@ -1336,6 +1335,7 @@
this.combinators,
prefixString,
this.isImport,
+ this.isDeferred,
unwrappedMetadata)
: prefix = _s(prefixString),
metadata = new UnmodifiableListView(unwrappedMetadata.map(reflect));
@@ -1400,14 +1400,6 @@
bool get isTopLevel => owner is LibraryMirror;
bool get isSynthetic => false;
- SourceLocation _location;
- SourceLocation get location {
- if (_location == null) {
- _location = _MethodMirror_location(_reflectee);
- }
- return _location;
- }
-
Type get _instantiator {
var o = owner;
while (o is MethodMirror) o = o.owner;
@@ -1490,9 +1482,6 @@
static String _MethodMirror_source(reflectee)
native "MethodMirror_source";
-
- static SourceLocation _MethodMirror_location(reflectee)
- native "MethodMirror_location";
}
class _LocalVariableMirror extends _LocalDeclarationMirror
@@ -1513,10 +1502,6 @@
bool get isTopLevel => owner is LibraryMirror;
- SourceLocation get location {
- throw new UnimplementedError('VariableMirror.location is not implemented');
- }
-
Type get _instantiator {
return owner._instantiator;
}
@@ -1574,6 +1559,10 @@
bool get hasDefaultValue => _defaultValueReflectee != null;
+ SourceLocation get location {
+ throw new UnsupportedError("ParameterMirror.location unimplemented");
+ }
+
List<InstanceMirror> get metadata {
if (_unmirroredMetadata == null) return emptyList;
return new UnmodifiableListView(_unmirroredMetadata.map(reflect));
@@ -1611,6 +1600,7 @@
DeclarationMirror get owner => null;
+ SourceLocation get location => null;
List<InstanceMirror> get metadata => emptyList;
bool get hasReflectedType => simpleName == #dynamic;
@@ -1625,10 +1615,6 @@
bool get isOriginalDeclaration => true;
TypeMirror get originalDeclaration => this;
- SourceLocation get location {
- throw new UnimplementedError('TypeMirror.location is not implemented');
- }
-
Symbol get qualifiedName => simpleName;
// TODO(11955): Remove once dynamicType and voidType are canonical objects in
diff --git a/runtime/lib/object.cc b/runtime/lib/object.cc
index da6c08e..3113f94 100644
--- a/runtime/lib/object.cc
+++ b/runtime/lib/object.cc
@@ -20,6 +20,19 @@
DECLARE_FLAG(bool, trace_type_checks);
DECLARE_FLAG(bool, warn_on_javascript_compatibility);
+// Helper function in stacktrace.cc.
+void _printCurrentStacktrace();
+
+DEFINE_NATIVE_ENTRY(DartCore_fatal, 1) {
+ // The core library code entered an unrecoverable state.
+ const Instance& instance = Instance::CheckedHandle(arguments->NativeArgAt(0));
+ const char* msg = instance.ToCString();
+ OS::PrintErr("Fatal error in dart:core\n");
+ _printCurrentStacktrace();
+ FATAL(msg);
+ return Object::null();
+}
+
DEFINE_NATIVE_ENTRY(Object_equals, 1) {
// Implemented in the flow graph builder.
diff --git a/runtime/lib/stacktrace.cc b/runtime/lib/stacktrace.cc
index 6c40ecc..f376ed3 100644
--- a/runtime/lib/stacktrace.cc
+++ b/runtime/lib/stacktrace.cc
@@ -10,27 +10,6 @@
namespace dart {
-// Get a full stack trace.
-// Arg0: stack trace object.
-// Return value: String that represents the full stack trace.
-DEFINE_NATIVE_ENTRY(Stacktrace_getFullStacktrace, 1) {
- const Stacktrace& trace =
- Stacktrace::CheckedHandle(arguments->NativeArgAt(0));
- return trace.FullStacktrace();
-}
-
-
-// Get a concise and pertinent stack trace.
-// Arg0: stack trace object.
-// Return value: String that represents the concise and pertinent stack trace.
-DEFINE_NATIVE_ENTRY(Stacktrace_getStacktrace, 1) {
- const Stacktrace& trace =
- Stacktrace::CheckedHandle(arguments->NativeArgAt(0));
- intptr_t frame_index = 0;
- return String::New(trace.ToCStringInternal(&frame_index));
-}
-
-
static void IterateFrames(const GrowableObjectArray& code_list,
const GrowableObjectArray& pc_offset_list) {
StackFrameIterator frames(StackFrameIterator::kDontValidateFrames);
@@ -38,42 +17,18 @@
ASSERT(frame != NULL); // We expect to find a dart invocation frame.
Code& code = Code::Handle();
Smi& offset = Smi::Handle();
- intptr_t frames_to_skip = 2; // _setupFullStackTrace and the catch frame.
while (frame != NULL) {
if (frame->IsDartFrame()) {
code = frame->LookupDartCode();
offset = Smi::New(frame->pc() - code.EntryPoint());
- if (frames_to_skip > 0) {
- frames_to_skip--;
- } else {
- code_list.Add(code);
- pc_offset_list.Add(offset);
- }
+ code_list.Add(code);
+ pc_offset_list.Add(offset);
}
frame = frames.NextFrame();
}
}
-// Setup a full stack trace.
-// Arg0: stack trace object.
-// Return value: None.
-DEFINE_NATIVE_ENTRY(Stacktrace_setupFullStacktrace, 1) {
- const Stacktrace& trace =
- Stacktrace::CheckedHandle(arguments->NativeArgAt(0));
- const GrowableObjectArray& code_list =
- GrowableObjectArray::Handle(GrowableObjectArray::New());
- const GrowableObjectArray& pc_offset_list =
- GrowableObjectArray::Handle(GrowableObjectArray::New());
- IterateFrames(code_list, pc_offset_list);
- const Array& code_array = Array::Handle(Array::MakeArray(code_list));
- const Array& pc_offset_array =
- Array::Handle(Array::MakeArray(pc_offset_list));
- trace.SetCatchStacktrace(code_array, pc_offset_array);
- return Object::null();
-}
-
-
// An utility method for convenient printing of dart stack traces when
// inside 'gdb'. Note: This function will only work when there is a
// valid exit frame information. It will not work when a breakpoint is
@@ -90,7 +45,8 @@
Array::Handle(Array::MakeArray(pc_offset_list));
const Stacktrace& stacktrace = Stacktrace::Handle(
Stacktrace::New(code_array, pc_offset_array));
- OS::Print("%s\n", stacktrace.ToCString());
+ OS::PrintErr("=== Current Trace:\n%s===\n", stacktrace.ToCString());
+>>>>>>> .merge-right.r43886
}
} // namespace dart
diff --git a/runtime/lib/stacktrace.dart b/runtime/lib/stacktrace.dart
new file mode 100644
index 0000000..c893d09
--- /dev/null
+++ b/runtime/lib/stacktrace.dart
@@ -0,0 +1,9 @@
+// Copyright (c) 2013, 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.
+
+// VM internal StackTrace implementation.
+class _StackTrace implements StackTrace {
+ // toString() is overridden on the C++ side.
+}
+
diff --git a/runtime/lib/stacktrace_patch.dart b/runtime/lib/stacktrace_patch.dart
deleted file mode 100644
index a545a9c..0000000
--- a/runtime/lib/stacktrace_patch.dart
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright (c) 2013, 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.
-
-patch class StackTrace {
- /* patch */ String get _fullStackTrace native "Stacktrace_getFullStacktrace";
-
- /* patch */ String get _stackTrace native "Stacktrace_getStacktrace";
-
- /* patch */ void _setupFullStackTrace()
- native "Stacktrace_setupFullStacktrace";
-}
-
diff --git a/runtime/lib/string_patch.dart b/runtime/lib/string_patch.dart
index 9d938c5..bef6a18 100644
--- a/runtime/lib/string_patch.dart
+++ b/runtime/lib/string_patch.dart
@@ -87,6 +87,13 @@
int get hashCode native "String_getHashCode";
+ bool get _isOneByte {
+ // Alternatively return false and override it on one-byte string classes.
+ int id = ClassID.getID(this);
+ return id == ClassID.cidOneByteString ||
+ id == ClassID.cidExternalOneByteString;
+ }
+
/**
* Create the most efficient string representation for specified
* [charCodes].
@@ -559,9 +566,7 @@
if (startIndex is! int) {
throw new ArgumentError("${startIndex} is not an int");
}
- if ((startIndex < 0) || (startIndex > this.length)) {
- throw new RangeError.range(startIndex, 0, this.length);
- }
+ RangeError.checkValueInInterval(startIndex, 0, this.length, "startIndex");
Iterator iterator =
startIndex == 0 ? pattern.allMatches(this).iterator
: pattern.allMatches(this, startIndex).iterator;
@@ -608,15 +613,12 @@
}
}
length += _addReplaceSlice(matches, startIndex, this.length);
- bool replacementIsOneByte = (replacement is _OneByteString) ||
- (replacement is _ExternalOneByteString);
- if (replacementIsOneByte && length < _maxJoinReplaceOneByteStringLength) {
+ bool replacementIsOneByte = replacement._isOneByte;
+ if (replacementIsOneByte &&
+ length < _maxJoinReplaceOneByteStringLength &&
+ this._isOneByte) {
// TODO(lrn): Is there a cut-off point, or is runtime always faster?
- bool thisIsOneByte = (this is _OneByteString) ||
- (this is _ExternalOneByteString);
- if (replacementIsOneByte && thisIsOneByte) {
- return _joinReplaceAllOneByteResult(this, matches, length);
- }
+ return _joinReplaceAllOneByteResult(this, matches, length);
}
return _joinReplaceAllResult(this, matches, length,
replacementIsOneByte);
@@ -688,27 +690,54 @@
bool replacementStringsAreOneByte = true;
for (Match match in pattern.allMatches(this)) {
length += _addReplaceSlice(matches, startIndex, match.start);
- String replacement = replace(match).toString();
+ var replacement = "${replace(match)}";
matches.add(replacement);
length += replacement.length;
- replacementStringsAreOneByte = replacementStringsAreOneByte &&
- (replacement is _OneByteString ||
- replacement is _ExternalOneByteString);
+ replacementStringsAreOneByte =
+ replacementStringsAreOneByte && replacement._isOneByte;
startIndex = match.end;
}
+ if (matches.isEmpty) return this;
length += _addReplaceSlice(matches, startIndex, this.length);
if (replacementStringsAreOneByte &&
- length < _maxJoinReplaceOneByteStringLength) {
- bool thisIsOneByte = (this is _OneByteString) ||
- (this is _ExternalOneByteString);
- if (thisIsOneByte) {
- return _joinReplaceAllOneByteResult(this, matches, length);
- }
+ length < _maxJoinReplaceOneByteStringLength &&
+ this._isOneByte) {
+ return _joinReplaceAllOneByteResult(this, matches, length);
}
return _joinReplaceAllResult(this, matches, length,
replacementStringsAreOneByte);
}
+ String replaceFirstMapped(Pattern pattern, String replace(Match match),
+ [int startIndex = 0]) {
+ if (pattern == null) throw new ArgumentError.notNull("pattern");
+ if (replace == null) throw new ArgumentError.notNull("replace");
+ if (startIndex == null) throw new ArgumentError.notNull("startIndex");
+ RangeError.checkValueInInterval(startIndex, 0, this.length, "startIndex");
+
+ var matches = pattern.allMatches(this, startIndex).iterator;
+ if (!matches.moveNext()) return this;
+ var match = matches.current;
+ var replacement = "${replace(match)}";
+ var slices = [];
+ int length = 0;
+ if (match.start > 0) {
+ length += _addReplaceSlice(slices, 0, match.start);
+ }
+ slices.add(replacement);
+ length += replacement.length;
+ if (match.end < this.length) {
+ length += _addReplaceSlice(slices, match.end, this.length);
+ }
+ bool replacementIsOneByte = replacement._isOneByte;
+ if (replacementIsOneByte &&
+ length < _maxJoinReplaceOneByteStringLength &&
+ this._isOneByte) {
+ return _joinReplaceAllOneByteResult(this, slices, length);
+ }
+ return _joinReplaceAllResult(this, slices, length, replacementIsOneByte);
+ }
+
static String _matchString(Match match) => match[0];
static String _stringIdentity(String string) => string;
@@ -770,7 +799,7 @@
static String _interpolateSingle(Object o) {
final s = o.toString();
if (s is! String) {
- throw new ArgumentError(o);
+ throw new ArgumentError(s);
}
return s;
}
diff --git a/runtime/observatory/.gitignore b/runtime/observatory/.gitignore
index d4d0502..c73eaff 100644
--- a/runtime/observatory/.gitignore
+++ b/runtime/observatory/.gitignore
@@ -2,3 +2,4 @@
out
build
.pub
+.idea
diff --git a/runtime/observatory/lib/debugger.dart b/runtime/observatory/lib/debugger.dart
new file mode 100644
index 0000000..d432e88
--- /dev/null
+++ b/runtime/observatory/lib/debugger.dart
@@ -0,0 +1,11 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library debugger;
+
+import 'dart:async';
+import 'package:observatory/service.dart';
+
+part 'src/debugger/debugger.dart';
+part 'src/debugger/source_location.dart';
diff --git a/runtime/observatory/lib/src/cli/command.dart b/runtime/observatory/lib/src/cli/command.dart
index 8c54a64..30a7874 100644
--- a/runtime/observatory/lib/src/cli/command.dart
+++ b/runtime/observatory/lib/src/cli/command.dart
@@ -40,7 +40,7 @@
//
// Given a list of arguments to this command, provide a list of
// possible completions for those arguments.
- List<String> complete(List<String> args) => [];
+ Future<List<String>> complete(List<String> args) => new Future.value([]);
// Override in subclasses to provide command-specific execution.
Future run(List<String> args);
@@ -82,16 +82,19 @@
}
// Builds a list of completions for this command.
- List<String> _buildCompletions(List<String> args,
- bool addEmptyString) {
- var completions = complete(args.sublist(_depth, args.length));
- if (addEmptyString && completions.isEmpty && args[args.length - 1] == '') {
- // Special case allowance for an empty particle at the end of
- // the command.
- completions = [''];
- }
- var prefix = _concatArgs(args, _depth);
- return completions.map((str) => '${prefix}${str}').toList();
+ Future<List<String>> _buildCompletions(List<String> args,
+ bool addEmptyString) {
+ return complete(args.sublist(_depth, args.length))
+ .then((completions) {
+ if (addEmptyString && completions.isEmpty &&
+ args[args.length - 1] == '') {
+ // Special case allowance for an empty particle at the end of
+ // the command.
+ completions = [''];
+ }
+ var prefix = _concatArgs(args, _depth);
+ return completions.map((str) => '${prefix}${str}').toList();
+ });
}
}
@@ -101,7 +104,7 @@
RootCommand(List<Command> children) : super(children);
// Provides a list of possible completions for a line of text.
- List<String> completeCommand(String line) {
+ Future<List<String>> completeCommand(String line) {
var args = _splitLine(line);
bool showAll = line.endsWith(' ') || args.isEmpty;
if (showAll) {
@@ -112,7 +115,7 @@
var commands = _match(args, false);
if (commands.isEmpty) {
// No matching commands.
- return [];
+ return new Future.value([]);
}
int matchLen = commands[0]._depth;
if (matchLen < args.length) {
@@ -125,7 +128,7 @@
} else {
// An ambiguous prefix match leaves us nowhere. The user is
// typing a bunch of stuff that we don't know how to complete.
- return [];
+ return new Future.value([]);
}
}
@@ -137,13 +140,18 @@
if (showAll && matchLen == args.length) {
// If we are showing all possiblities, also include local
// completions for the parent command.
- completions.addAll(commands[0]._parent._buildCompletions(args, false));
+ return commands[0]._parent._buildCompletions(args, false)
+ .then((localCompletions) {
+ completions.addAll(localCompletions);
+ return completions;
+ });
}
- return completions;
+ return new Future.value(completions);
}
// Runs a command.
Future runCommand(String line) {
+ _historyAdvance(line);
var args = _splitLine(line);
var commands = _match(args, true);
if (commands.isEmpty) {
@@ -157,6 +165,49 @@
}
}
+ // Find all matching commands. Useful for implementing help systems.
+ List<Command> matchCommand(List<String> args, bool preferExact) {
+ if (args.isEmpty) {
+ // Adding an empty string to the end causes us to match all
+ // subcommands of the last command.
+ args.add('');
+ }
+ return _match(args, preferExact);
+ }
+
+ // Command line history always contains one slot to hold the current
+ // line, so we start off with one entry.
+ List<String> history = [''];
+ int historyPos = 0;
+
+ String historyPrev(String line) {
+ if (historyPos == 0) {
+ return line;
+ }
+ history[historyPos] = line;
+ historyPos--;
+ return history[historyPos];
+ }
+
+ String historyNext(String line) {
+ if (historyPos == history.length - 1) {
+ return line;
+ }
+ history[historyPos] = line;
+ historyPos++;
+ return history[historyPos];
+ }
+
+ void _historyAdvance(String line) {
+ // Replace the last history line.
+ historyPos = history.length - 1;
+ history[historyPos] = line;
+
+ // Create an empty spot for the next line.
+ history.add('');
+ historyPos++;
+ }
+
Future run(List<String> args) {
throw 'should-not-execute-the-root-command';
}
@@ -168,7 +219,15 @@
abstract class Command extends _CommandBase {
Command(this.name, List<Command> children) : super(children);
- final name;
+ final String name;
+ String get fullName {
+ if (_parent is RootCommand) {
+ return name;
+ } else {
+ Command parent = _parent;
+ return '${parent.fullName} $name';
+ }
+ }
toString() => 'Command(${name})';
}
diff --git a/runtime/observatory/lib/src/debugger/debugger.dart b/runtime/observatory/lib/src/debugger/debugger.dart
new file mode 100644
index 0000000..d028c36
--- /dev/null
+++ b/runtime/observatory/lib/src/debugger/debugger.dart
@@ -0,0 +1,11 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+part of debugger;
+
+// TODO(turnidge): Move more of ObservatoryDebugger to this class.
+abstract class Debugger {
+ Isolate get isolate;
+ ServiceMap get stack;
+}
diff --git a/runtime/observatory/lib/src/debugger/source_location.dart b/runtime/observatory/lib/src/debugger/source_location.dart
new file mode 100644
index 0000000..07ab3f6
--- /dev/null
+++ b/runtime/observatory/lib/src/debugger/source_location.dart
@@ -0,0 +1,367 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+part of debugger;
+
+class SourceLocation {
+ SourceLocation.file(this.script, this.line, this.col);
+ SourceLocation.func(this.function);
+ SourceLocation.error(this.errorMessage);
+
+ static RegExp sourceLocMatcher = new RegExp(r'^([^\d:][^:]+:)?(\d+)(:\d+)?');
+ static RegExp functionMatcher = new RegExp(r'^([^.]+)([.][^.]+)?');
+
+ /// Parses a source location description.
+ ///
+ /// Formats:
+ /// '' - current position
+ /// 13 - line 13, current script
+ /// 13:20 - line 13, col 20, current script
+ /// script.dart:13 - line 13, script.dart
+ /// script.dart:13:20 - line 13, col 20, script.dart
+ /// main - function
+ /// FormatException - constructor
+ /// _SHA1._updateHash - method
+ static Future<SourceLocation> parse(Debugger debugger, String locDesc) {
+ if (locDesc == '') {
+ // Special case: '' means return current location.
+ return _currentLocation(debugger);
+ }
+
+ // Parse the location description.
+ var match = sourceLocMatcher.firstMatch(locDesc);
+ if (match != null) {
+ return _parseScriptLine(debugger, match);
+ }
+ match = functionMatcher.firstMatch(locDesc);
+ if (match != null) {
+ return _parseFunction(debugger, match);
+ }
+ return new Future.value(new SourceLocation.error(
+ "Invalid source location '${locDesc}'"));
+ }
+
+ static Future<SourceLocation> _currentLocation(Debugger debugger) {
+ ServiceMap stack = debugger.stack;
+ if (stack == null || stack['frames'].length == 0) {
+ return new Future.value(new SourceLocation.error(
+ 'A script must be provided when the stack is empty'));
+ }
+ var frame = stack['frames'][0];
+ Script script = frame['script'];
+ return script.load().then((_) {
+ var line = script.tokenToLine(frame['tokenPos']);
+ // TODO(turnidge): Pass in the column here once the protocol supports it.
+ return new Future.value(new SourceLocation.file(script, line, null));
+ });
+ }
+
+ static Future<SourceLocation> _parseScriptLine(Debugger debugger,
+ Match match) {
+ var scriptName = match.group(1);
+ if (scriptName != null) {
+ scriptName = scriptName.substring(0, scriptName.length - 1);
+ }
+ var lineStr = match.group(2);
+ assert(lineStr != null);
+ var colStr = match.group(3);
+ if (colStr != null) {
+ colStr = colStr.substring(1);
+ }
+ var line = int.parse(lineStr, onError:(_) => -1);
+ var col = (colStr != null
+ ? int.parse(colStr, onError:(_) => -1)
+ : null);
+ if (line == -1) {
+ return new Future.value(new SourceLocation.error(
+ "Line '${lineStr}' must be an integer"));
+ }
+ if (col == -1) {
+ return new Future.value(new SourceLocation.error(
+ "Column '${colStr}' must be an integer"));
+ }
+
+ if (scriptName != null) {
+ // Resolve the script.
+ return _lookupScript(debugger.isolate, scriptName).then((scripts) {
+ if (scripts.length == 0) {
+ return new SourceLocation.error("Script '${scriptName}' not found");
+ } else if (scripts.length == 1) {
+ return new SourceLocation.file(scripts[0], line, col);
+ } else {
+ // TODO(turnidge): Allow the user to disambiguate.
+ return new SourceLocation.error("Script '${scriptName}' is ambigous");
+ }
+ });
+ } else {
+ // No script provided. Default to top of stack for now.
+ ServiceMap stack = debugger.stack;
+ if (stack == null || stack['frames'].length == 0) {
+ return new Future.value(new SourceLocation.error(
+ 'A script must be provided when the stack is empty'));
+ }
+ Script script = stack['frames'][0]['script'];
+ return new Future.value(new SourceLocation.file(script, line, col));
+ }
+ }
+
+ static Future<List<Script>> _lookupScript(Isolate isolate,
+ String name,
+ {bool allowPrefix: false}) {
+ var pending = [];
+ for (var lib in isolate.libraries) {
+ if (!lib.loaded) {
+ pending.add(lib.load());
+ }
+ }
+ return Future.wait(pending).then((_) {
+ List matches = [];
+ for (var lib in isolate.libraries) {
+ for (var script in lib.scripts) {
+ if (allowPrefix) {
+ if (script.name.startsWith(name)) {
+ matches.add(script);
+ }
+ } else {
+ if (name == script.name) {
+ matches.add(script);
+ }
+ }
+ }
+ }
+ return matches;
+ });
+ }
+
+ static List<ServiceFunction> _lookupFunction(Isolate isolate,
+ String name,
+ { bool allowPrefix: false }) {
+ var matches = [];
+ for (var lib in isolate.libraries) {
+ assert(lib.loaded);
+ for (var function in lib.functions) {
+ if (allowPrefix) {
+ if (function.name.startsWith(name)) {
+ matches.add(function);
+ }
+ } else {
+ if (name == function.name) {
+ matches.add(function);
+ }
+ }
+ }
+ }
+ return matches;
+ }
+
+ static Future<List<Class>> _lookupClass(Isolate isolate,
+ String name,
+ { bool allowPrefix: false }) {
+ var pending = [];
+ for (var lib in isolate.libraries) {
+ assert(lib.loaded);
+ for (var cls in lib.classes) {
+ if (!cls.loaded) {
+ pending.add(cls.load());
+ }
+ }
+ }
+ return Future.wait(pending).then((_) {
+ var matches = [];
+ for (var lib in isolate.libraries) {
+ for (var cls in lib.classes) {
+ if (allowPrefix) {
+ if (cls.name.startsWith(name)) {
+ matches.add(cls);
+ }
+ } else {
+ if (name == cls.name) {
+ matches.add(cls);
+ }
+ }
+ }
+ }
+ return matches;
+ });
+ }
+
+ static ServiceFunction _getConstructor(Class cls, String name) {
+ var matches = [];
+ for (var function in cls.functions) {
+ assert(cls.loaded);
+ if (name == function.name) {
+ return function;
+ }
+ }
+ return null;
+ }
+
+ // TODO(turnidge): This does not handle named functions which are
+ // inside of named functions, e.g. foo.bar.baz.
+ static Future<SourceLocation> _parseFunction(Debugger debugger,
+ Match match) {
+ Isolate isolate = debugger.isolate;
+ var base = match.group(1);
+ var qualifier = match.group(2);
+ assert(base != null);
+
+ return _lookupClass(isolate, base).then((classes) {
+ var functions = [];
+ if (qualifier == null) {
+ // Unqualified name is either a function or a constructor.
+ functions.addAll(_lookupFunction(isolate, base));
+
+ for (var cls in classes) {
+ // Look for a self-named constructor.
+ var constructor = _getConstructor(cls, cls.name);
+ if (constructor != null) {
+ functions.add(constructor);
+ }
+ }
+ } else {
+ // Qualified name.
+ var functionName = qualifier.substring(1);
+ for (var cls in classes) {
+ assert(cls.loaded);
+ for (var function in cls.functions) {
+ if (function.kind == FunctionKind.kConstructor) {
+ // Constructor names are class-qualified.
+ if (match.group(0) == function.name) {
+ functions.add(function);
+ }
+ } else {
+ if (functionName == function.name) {
+ functions.add(function);
+ }
+ }
+ }
+ }
+ }
+ if (functions.length == 0) {
+ return new SourceLocation.error(
+ "Function '${match.group(0)}' not found");
+ } else if (functions.length == 1) {
+ return new SourceLocation.func(functions[0]);
+ } else {
+ // TODO(turnidge): Allow the user to disambiguate.
+ return new SourceLocation.error(
+ "Function '${match.group(0)}' is ambigous");
+ }
+ return new SourceLocation.error('foo');
+ });
+ }
+
+ static RegExp partialSourceLocMatcher =
+ new RegExp(r'^([^\d:]?[^:]+[:]?)?(\d+)?([:]\d+)?');
+ static RegExp partialFunctionMatcher = new RegExp(r'^([^.]*)([.][^.]*)?');
+
+ /// Completes a partial source location description.
+ static Future<List<String>> complete(Debugger debugger, String locDesc) {
+ List<Future<List<String>>> pending = [];
+ var match = partialFunctionMatcher.firstMatch(locDesc);
+ if (match != null) {
+ pending.add(_completeFunction(debugger, match));
+ }
+
+ match = partialSourceLocMatcher.firstMatch(locDesc);
+ if (match != null) {
+ pending.add(_completeFile(debugger, match));
+ }
+
+ return Future.wait(pending).then((List<List<String>> responses) {
+ var completions = [];
+ for (var response in responses) {
+ completions.addAll(response);
+ }
+ return completions;
+ });
+ }
+
+ static Future<List<String>> _completeFunction(Debugger debugger,
+ Match match) {
+ Isolate isolate = debugger.isolate;
+ var base = match.group(1);
+ var qualifier = match.group(2);
+ base = (base == null ? '' : base);
+
+ if (qualifier == null) {
+ return _lookupClass(isolate, base, allowPrefix:true).then((classes) {
+ var completions = [];
+
+ // Complete top-level function names.
+ var functions = _lookupFunction(isolate, base, allowPrefix:true);
+ var funcNames = functions.map((f) => f.name).toList();
+ funcNames.sort();
+ completions.addAll(funcNames);
+
+ // Complete class names.
+ var classNames = classes.map((f) => f.name).toList();
+ classNames.sort();
+ completions.addAll(classNames);
+
+ return completions;
+ });
+ } else {
+ return _lookupClass(isolate, base, allowPrefix:false).then((classes) {
+ var completions = [];
+ for (var cls in classes) {
+ for (var function in cls.functions) {
+ if (function.kind == FunctionKind.kConstructor) {
+ if (function.name.startsWith(match.group(0))) {
+ completions.add(function.name);
+ }
+ } else {
+ if (function.qualifiedName.startsWith(match.group(0))) {
+ completions.add(function.qualifiedName);
+ }
+ }
+ }
+ }
+ completions.sort();
+ return completions;
+ });
+ }
+ }
+
+ static Future<List<String>> _completeFile(Debugger debugger, Match match) {
+ var scriptName = match.group(1);
+ var lineStr = match.group(2);
+ var colStr = match.group(3);
+ if (lineStr != null || colStr != null) {
+ // TODO(turnidge): Complete valid line and column numbers.
+ return new Future.value([]);
+ }
+ scriptName = (scriptName == null ? '' : scriptName);
+
+ return _lookupScript(debugger.isolate, scriptName, allowPrefix:true)
+ .then((scripts) {
+ List completions = [];
+ for (var script in scripts) {
+ completions.add(script.name + ':');
+ }
+ completions.sort();
+ return completions;
+ });
+ }
+
+ String toString() {
+ if (valid) {
+ if (function != null) {
+ return '${function.qualifiedName}';
+ } else if (col != null) {
+ return '${script.name}:${line}:${col}';
+ } else {
+ return '${script.name}:${line}';
+ }
+ }
+ return 'invalid source location (${errorMessage})';
+ }
+
+ Script script;
+ int line;
+ int col;
+ ServiceFunction function;
+ String errorMessage;
+ bool get valid => (errorMessage == null);
+}
diff --git a/runtime/observatory/lib/src/elements/debugger.dart b/runtime/observatory/lib/src/elements/debugger.dart
index 9c18f94..e9d1623 100644
--- a/runtime/observatory/lib/src/elements/debugger.dart
+++ b/runtime/observatory/lib/src/elements/debugger.dart
@@ -8,37 +8,90 @@
import 'dart:html';
import 'observatory_element.dart';
import 'package:observatory/cli.dart';
+import 'package:observatory/debugger.dart';
import 'package:observatory/service.dart';
import 'package:polymer/polymer.dart';
-// TODO(turnidge): Move Debugger, DebuggerCommand to their own lib.
+// TODO(turnidge): Move Debugger, DebuggerCommand to debugger library.
abstract class DebuggerCommand extends Command {
- Debugger debugger;
+ ObservatoryDebugger debugger;
DebuggerCommand(this.debugger, name, children)
: super(name, children);
+
+ String get helpShort;
+ String get helpLong;
}
+// TODO(turnidge): Rewrite HelpCommand so that it is a general utility
+// provided by the cli library.
class HelpCommand extends DebuggerCommand {
HelpCommand(Debugger debugger) : super(debugger, 'help', []);
Future run(List<String> args) {
var con = debugger.console;
- con.printLine('List of commands:');
- con.newline();
+ if (args.length == 0) {
+ // Print list of all top-level commands.
+ var commands = debugger.cmd.matchCommand([], false);
+ commands.sort((a, b) => a.name.compareTo(b.name));
+ con.print('List of commands:\n');
+ for (var command in commands) {
+ con.print('${command.name.padRight(12)} - ${command.helpShort}');
+ }
+ con.print(
+ "\nFor more information on a specific command type 'help <command>'\n"
+ "\n"
+ "Command prefixes are accepted (e.g. 'h' for 'help')\n"
+ "Hit [TAB] to complete a command (try 'i[TAB][TAB]')\n"
+ "Hit [ENTER] to repeat the last command\n");
+ return new Future.value(null);
+ } else {
+ // Print any matching commands.
+ var commands = debugger.cmd.matchCommand(args, true);
+ commands.sort((a, b) => a.name.compareTo(b.name));
+ if (commands.isEmpty) {
+ var line = args.join(' ');
+ con.print("No command matches '${line}'");
+ return new Future.value(null);
+ }
+ con.print('');
+ for (var command in commands) {
+ con.printBold(command.fullName);
+ con.print(command.helpLong);
- // TODO(turnidge): Build a real help system.
- List completions = debugger.cmd.completeCommand('');
- completions = completions.map((s )=> s.trimRight()).toList();
- completions.sort();
- con.printLine(completions.toString());
- con.newline();
- con.printLine("Command prefixes are accepted (e.g. 'h' for 'help')");
- con.printLine("Hit [TAB] to complete a command (try 'i[TAB][TAB]')");
- con.printLine("Hit [ENTER] to repeat the last command");
-
- return new Future.value(null);
+ var newArgs = [];
+ newArgs.addAll(args.take(args.length - 1));
+ newArgs.add(command.name);
+ newArgs.add('');
+ var subCommands = debugger.cmd.matchCommand(newArgs, false);
+ subCommands.remove(command);
+ if (subCommands.isNotEmpty) {
+ subCommands.sort((a, b) => a.name.compareTo(b.name));
+ con.print('Subcommands:\n');
+ for (var subCommand in subCommands) {
+ con.print(' ${subCommand.fullName.padRight(16)} '
+ '- ${subCommand.helpShort}');
+ }
+ con.print('');
+ }
+ }
+ return new Future.value(null);
+ }
}
+
+ Future<List<String>> complete(List<String> args) {
+ var commands = debugger.cmd.matchCommand(args, false);
+ var result = commands.map((command) => '${command.fullName} ');
+ return new Future.value(result);
+ }
+
+ String helpShort = 'List commands or provide details about a specific command';
+
+ String helpLong =
+ 'List commands or provide details about a specific command.\n'
+ '\n'
+ 'Syntax: help - Show a list of all commands\n'
+ ' help <command> - Help for a specific command\n';
}
class PauseCommand extends DebuggerCommand {
@@ -48,10 +101,17 @@
if (!debugger.isolatePaused()) {
return debugger.isolate.pause();
} else {
- debugger.console.printLine('The program is already paused');
+ debugger.console.print('The program is already paused');
return new Future.value(null);
}
}
+
+ String helpShort = 'Pause the isolate';
+
+ String helpLong =
+ 'Pause the isolate.\n'
+ '\n'
+ 'Syntax: pause\n';
}
class ContinueCommand extends DebuggerCommand {
@@ -63,10 +123,17 @@
debugger.warnOutOfDate();
});
} else {
- debugger.console.printLine('The program must be paused');
+ debugger.console.print('The program must be paused');
return new Future.value(null);
}
}
+
+ String helpShort = 'Resume execution of the isolate';
+
+ String helpLong =
+ 'Continue running the isolate.\n'
+ '\n'
+ 'Syntax: continue\n';
}
class NextCommand extends DebuggerCommand {
@@ -76,19 +143,29 @@
if (debugger.isolatePaused()) {
var event = debugger.isolate.pauseEvent;
if (event.eventType == 'IsolateCreated') {
- debugger.console.printLine("Type 'continue' to start the isolate");
+ debugger.console.print("Type 'continue' to start the isolate");
return new Future.value(null);
}
if (event.eventType == 'IsolateShutdown') {
- debugger.console.printLine("Type 'continue' to exit the isolate");
+ debugger.console.print("Type 'continue' to exit the isolate");
return new Future.value(null);
}
return debugger.isolate.stepOver();
} else {
- debugger.console.printLine('The program is already running');
+ debugger.console.print('The program is already running');
return new Future.value(null);
}
}
+
+ String helpShort =
+ 'Continue running the isolate until it reaches the next source location '
+ 'in the current function';
+
+ String helpLong =
+ 'Continue running the isolate until it reaches the next source location '
+ 'in the current function.\n'
+ '\n'
+ 'Syntax: next\n';
}
class StepCommand extends DebuggerCommand {
@@ -98,19 +175,28 @@
if (debugger.isolatePaused()) {
var event = debugger.isolate.pauseEvent;
if (event.eventType == 'IsolateCreated') {
- debugger.console.printLine("Type 'continue' to start the isolate");
+ debugger.console.print("Type 'continue' to start the isolate");
return new Future.value(null);
}
if (event.eventType == 'IsolateShutdown') {
- debugger.console.printLine("Type 'continue' to exit the isolate");
+ debugger.console.print("Type 'continue' to exit the isolate");
return new Future.value(null);
}
return debugger.isolate.stepInto();
} else {
- debugger.console.printLine('The program is already running');
+ debugger.console.print('The program is already running');
return new Future.value(null);
}
}
+
+ String helpShort =
+ 'Continue running the isolate until it reaches the next source location';
+
+ String helpLong =
+ 'Continue running the isolate until it reaches the next source '
+ 'location.\n'
+ '\n'
+ 'Syntax: step\n';
}
class FinishCommand extends DebuggerCommand {
@@ -120,10 +206,193 @@
if (debugger.isolatePaused()) {
return debugger.isolate.stepOut();
} else {
- debugger.console.printLine('The program is already running');
+ debugger.console.print('The program is already running');
return new Future.value(null);
}
}
+
+ String helpShort =
+ 'Continue running the isolate until the current function exits';
+
+ String helpLong =
+ 'Continue running the isolate until the current function exits.\n'
+ '\n'
+ 'Syntax: finish\n';
+}
+
+class BreakCommand extends DebuggerCommand {
+ BreakCommand(Debugger debugger) : super(debugger, 'break', []);
+
+ Future run(List<String> args) {
+ if (args.length > 1) {
+ debugger.console.print('not implemented');
+ return new Future.value(null);
+ }
+ var arg = (args.length == 0 ? '' : args[0]);
+ return SourceLocation.parse(debugger, arg).then((loc) {
+ if (loc.valid) {
+ if (loc.function != null) {
+ return debugger.isolate.addBreakpointAtEntry(loc.function)
+ .then((result) => _handleBreakpointResult(loc, result));
+ } else {
+ assert(loc.script != null);
+ if (loc.col != null) {
+ // TODO(turnidge): Add tokenPos breakpoint support.
+ debugger.console.print(
+ 'Ignoring column: '
+ 'adding breakpoint at a specific column not yet implemented');
+ }
+ return debugger.isolate.addBreakpoint(loc.script, loc.line)
+ .then((result) => _handleBreakpointResult(loc, result));
+ }
+ } else {
+ debugger.console.print(loc.errorMessage);
+ }
+ });
+ }
+
+ Future _handleBreakpointResult(loc, result) {
+ if (result is DartError) {
+ debugger.console.print('Unable to set breakpoint at ${loc}');
+ } else {
+ // TODO(turnidge): Adding a duplicate breakpoint is
+ // currently ignored. May want to change the protocol to
+ // inform us when this happens.
+
+ // The BreakpointResolved event prints resolved
+ // breakpoints already. Just print the unresolved ones here.
+ Breakpoint bpt = result;
+ if (!bpt.resolved) {
+ return debugger._reportBreakpointAdded(bpt);
+ }
+ }
+ return new Future.value(null);
+ }
+
+ Future<List<String>> complete(List<String> args) {
+ if (args.length != 1) {
+ return new Future.value([]);
+ }
+ // TODO - fix SourceLocation complete
+ return new Future.value(SourceLocation.complete(debugger, args[0]));
+ }
+
+ String helpShort = 'Add a breakpoint by source location or function name';
+
+ String helpLong =
+ 'Add a breakpoint by source location or function name.\n'
+ '\n'
+ 'Syntax: break '
+ '- Break at the current position\n'
+ ' break <line> '
+ '- Break at a line in the current script\n'
+ ' '
+ ' (e.g \'break 11\')\n'
+ ' break <line>:<col> '
+ '- Break at a line:col in the current script\n'
+ ' '
+ ' (e.g \'break 11:8\')\n'
+ ' break <script>:<line> '
+ '- Break at a line:col in a specific script\n'
+ ' '
+ ' (e.g \'break test.dart:11\')\n'
+ ' break <script>:<line>:<col> '
+ '- Break at a line:col in a specific script\n'
+ ' '
+ ' (e.g \'break test.dart:11:8\')\n'
+ ' break <function> '
+ '- Break at the named function\n'
+ ' '
+ ' (e.g \'break main\' or \'break Class.someFunction\')\n';
+}
+
+class ClearCommand extends DebuggerCommand {
+ ClearCommand(Debugger debugger) : super(debugger, 'clear', []);
+
+ Future run(List<String> args) {
+ if (args.length > 1) {
+ debugger.console.print('not implemented');
+ return new Future.value(null);
+ }
+ var arg = (args.length == 0 ? '' : args[0]);
+ return SourceLocation.parse(debugger, arg).then((loc) {
+ if (loc.valid) {
+ if (loc.function != null) {
+ debugger.console.print(
+ 'Ignoring breakpoint at $loc: '
+ 'Function entry breakpoints not yet implemented');
+ return null;
+ }
+ if (loc.col != null) {
+ // TODO(turnidge): Add tokenPos clear support.
+ debugger.console.print(
+ 'Ignoring column: '
+ 'clearing breakpoint at a specific column not yet implemented');
+ }
+
+ for (var bpt in debugger.isolate.breakpoints) {
+ var script = bpt.script;
+ if (script.id == loc.script.id) {
+ assert(script.loaded);
+ var line = script.tokenToLine(bpt.tokenPos);
+ if (line == loc.line) {
+ return debugger.isolate.removeBreakpoint(bpt).then((result) {
+ if (result is DartError) {
+ debugger.console.print(
+ 'Unable to clear breakpoint at ${loc}: ${result.message}');
+ return;
+ } else {
+ // TODO(turnidge): Add a BreakpointRemoved event to
+ // the service instead of printing here.
+ var bpId = bpt.number;
+ debugger.console.print('Breakpoint ${bpId} removed at ${loc}');
+ return;
+ }
+ });
+ }
+ }
+ }
+ debugger.console.print('No breakpoint found at ${loc}');
+ } else {
+ debugger.console.print(loc.errorMessage);
+ }
+ });
+ }
+
+ Future<List<String>> complete(List<String> args) {
+ if (args.length != 1) {
+ return new Future.value([]);
+ }
+ return new Future.value(SourceLocation.complete(debugger, args[0]));
+ }
+
+ String helpShort = 'Remove a breakpoint by source location or function name';
+
+ String helpLong =
+ 'Remove a breakpoint by source location or function name.\n'
+ '\n'
+ 'Syntax: clear '
+ '- Clear at the current position\n'
+ ' clear <line> '
+ '- Clear at a line in the current script\n'
+ ' '
+ ' (e.g \'clear 11\')\n'
+ ' clear <line>:<col> '
+ '- Clear at a line:col in the current script\n'
+ ' '
+ ' (e.g \'clear 11:8\')\n'
+ ' clear <script>:<line> '
+ '- Clear at a line:col in a specific script\n'
+ ' '
+ ' (e.g \'clear test.dart:11\')\n'
+ ' clear <script>:<line>:<col> '
+ '- Clear at a line:col in a specific script\n'
+ ' '
+ ' (e.g \'clear test.dart:11:8\')\n'
+ ' clear <function> '
+ '- Clear at the named function\n'
+ ' '
+ ' (e.g \'clear main\' or \'clear Class.someFunction\')\n';
}
// TODO(turnidge): Add argument completion.
@@ -132,34 +401,42 @@
Future run(List<String> args) {
if (args.length < 1) {
- debugger.console.printLine('delete expects one or more arguments');
+ debugger.console.print('delete expects one or more arguments');
return new Future.value(null);
}
- List toDelete = [];
+ List toRemove = [];
for (var arg in args) {
int id = int.parse(arg);
- var bpt = null;
- for (var candidate in debugger.isolate.breakpoints) {
- if (candidate['breakpointNumber'] == id) {
- bpt = candidate;
+ var bptToRemove = null;
+ for (var bpt in debugger.isolate.breakpoints) {
+ if (bpt.number == id) {
+ bptToRemove = bpt;
break;
}
}
- if (bpt == null) {
- debugger.console.printLine("Invalid breakpoint id '${id}'");
+ if (bptToRemove == null) {
+ debugger.console.print("Invalid breakpoint id '${id}'");
return new Future.value(null);
}
- toDelete.add(bpt);
+ toRemove.add(bptToRemove);
}
List pending = [];
- for (var bpt in toDelete) {
+ for (var bpt in toRemove) {
pending.add(debugger.isolate.removeBreakpoint(bpt).then((_) {
- var id = bpt['breakpointNumber'];
- debugger.console.printLine("Removed breakpoint $id");
+ var id = bpt.number;
+ debugger.console.print("Removed breakpoint $id");
}));
}
return Future.wait(pending);
}
+
+ String helpShort = 'Remove a breakpoint by breakpoint id';
+
+ String helpLong =
+ 'Remove a breakpoint by breakpoint id.\n'
+ '\n'
+ 'Syntax: delete <bp-id>\n'
+ ' delete <bp-id> <bp-id> ...\n';
}
class InfoBreakpointsCommand extends DebuggerCommand {
@@ -169,19 +446,33 @@
Future run(List<String> args) {
return debugger.isolate.reloadBreakpoints().then((_) {
if (debugger.isolate.breakpoints.isEmpty) {
- debugger.console.printLine('No breakpoints');
+ debugger.console.print('No breakpoints');
}
for (var bpt in debugger.isolate.breakpoints) {
- var bpId = bpt['breakpointNumber'];
- var script = bpt['location']['script'];
- var tokenPos = bpt['location']['tokenPos'];
+ var bpId = bpt.number;
+ var script = bpt.script;
+ var tokenPos = bpt.tokenPos;
var line = script.tokenToLine(tokenPos);
var col = script.tokenToCol(tokenPos);
- debugger.console.printLine(
- 'Breakpoint ${bpId} at ${script.name}:${line}:${col}');
+ var extras = new StringBuffer();
+ if (!bpt.resolved) {
+ extras.write(' unresolved');
+ }
+ if (!bpt.enabled) {
+ extras.write(' disabled');
+ }
+ debugger.console.print(
+ 'Breakpoint ${bpId} at ${script.name}:${line}:${col}${extras}');
}
});
}
+
+ String helpShort = 'List all breakpoints';
+
+ String helpLong =
+ 'List all breakpoints.\n'
+ '\n'
+ 'Syntax: info breakpoints\n';
}
class InfoIsolatesCommand extends DebuggerCommand {
@@ -189,11 +480,19 @@
Future run(List<String> args) {
for (var isolate in debugger.isolate.vm.isolates) {
- debugger.console.printLine(
- "Isolate ${isolate.id} '${isolate.name}'");
+ String current = (isolate == debugger.isolate ? ' *' : '');
+ debugger.console.print(
+ "Isolate ${isolate.id} '${isolate.name}'${current}");
}
return new Future.value(null);
}
+
+ String helpShort = 'List all isolates';
+
+ String helpLong =
+ 'List all isolates.\n'
+ '\n'
+ 'Syntax: info isolates\n';
}
class InfoCommand extends DebuggerCommand {
@@ -203,9 +502,16 @@
]);
Future run(List<String> args) {
- debugger.console.printLine("Invalid info command");
+ debugger.console.print("'info' expects a subcommand (see 'help info')");
return new Future.value(null);
}
+
+ String helpShort = 'Show information on a variety of topics';
+
+ String helpLong =
+ 'Show information on a variety of topics.\n'
+ '\n'
+ 'Syntax: info <subcommand>\n';
}
class RefreshCoverageCommand extends DebuggerCommand {
@@ -216,31 +522,65 @@
List pending = [];
for (var script in scripts) {
pending.add(script.refreshCoverage().then((_) {
- debugger.console.printLine('Refreshed coverage for ${script.name}');
+ debugger.console.print('Refreshed coverage for ${script.name}');
}));
}
return Future.wait(pending);
}
+
+ String helpShort = 'Refresh code coverage information for current frames';
+
+ String helpLong =
+ 'Refresh code coverage information for current frames.\n'
+ '\n'
+ 'Syntax: refresh coverage\n\n';
+}
+
+class RefreshStackCommand extends DebuggerCommand {
+ RefreshStackCommand(Debugger debugger) : super(debugger, 'stack', []);
+
+ Future run(List<String> args) {
+ Set<Script> scripts = debugger.stackElement.activeScripts();
+ List pending = [];
+ return debugger.refreshStack();
+ }
+
+ String helpShort = 'Refresh isolate stack';
+
+ String helpLong =
+ 'Refresh isolate stack.\n'
+ '\n'
+ 'Syntax: refresh stack\n';
}
class RefreshCommand extends DebuggerCommand {
RefreshCommand(Debugger debugger) : super(debugger, 'refresh', [
new RefreshCoverageCommand(debugger),
+ new RefreshStackCommand(debugger),
]);
Future run(List<String> args) {
- return debugger.refreshStack();
+ debugger.console.print("'refresh' expects a subcommand (see 'help refresh')");
+ return new Future.value(null);
}
+
+ String helpShort = 'Refresh debugging information of various sorts';
+
+ String helpLong =
+ 'Refresh debugging information of various sorts.\n'
+ '\n'
+ 'Syntax: refresh <subcommand>\n';
}
// Tracks the state for an isolate debugging session.
-class Debugger {
+class ObservatoryDebugger extends Debugger {
RootCommand cmd;
DebuggerConsoleElement console;
DebuggerStackElement stackElement;
ServiceMap stack;
+ int currentFrame = 0;
- Debugger() {
+ ObservatoryDebugger() {
cmd = new RootCommand([
new HelpCommand(this),
new PauseCommand(this),
@@ -248,6 +588,8 @@
new NextCommand(this),
new StepCommand(this),
new FinishCommand(this),
+ new BreakCommand(this),
+ new ClearCommand(this),
new DeleteCommand(this),
new InfoCommand(this),
new RefreshCommand(this),
@@ -258,9 +600,19 @@
_isolate = iso;
if (_isolate != null) {
_isolate.reload().then((_) {
- _isolate.vm.events.stream.listen(_onEvent);
- _refreshStack(isolate.pauseEvent).then((_) {
- reportStatus();
+ // TODO(turnidge): Currently the debugger relies on all libs
+ // being loaded. Fix this.
+ var pending = [];
+ for (var lib in _isolate.libraries) {
+ if (!lib.loaded) {
+ pending.add(lib.load());
+ }
+ }
+ Future.wait(pending).then((_) {
+ _isolate.vm.events.stream.listen(_onEvent);
+ _refreshStack(isolate.pauseEvent).then((_) {
+ reportStatus();
+ });
});
});
}
@@ -300,29 +652,28 @@
stack = result;
// TODO(turnidge): Replace only the changed part of the stack to
// reduce flicker.
- // stackElement.stack = stack;
stackElement.updateStack(stack, pauseEvent);
});
}
void reportStatus() {
if (_isolate.idle) {
- console.printLine('Isolate is idle');
+ console.print('Isolate is idle');
} else if (_isolate.running) {
- console.printLine("Isolate is running (type 'pause' to interrupt)");
+ console.print("Isolate is running (type 'pause' to interrupt)");
} else if (_isolate.pauseEvent != null) {
_reportPause(_isolate.pauseEvent);
} else {
- console.printLine('Isolate is in unknown state');
+ console.print('Isolate is in unknown state');
}
}
void _reportPause(ServiceEvent event) {
if (event.eventType == 'IsolateCreated') {
- console.printLine(
+ console.print(
"Paused at isolate start (type 'continue' to start the isolate')");
} else if (event.eventType == 'IsolateShutdown') {
- console.printLine(
+ console.print(
"Paused at isolate exit (type 'continue' to exit the isolate')");
}
if (stack['frames'].length > 0) {
@@ -332,26 +683,46 @@
var line = script.tokenToLine(frame['tokenPos']);
var col = script.tokenToCol(frame['tokenPos']);
if (event.breakpoint != null) {
- var bpId = event.breakpoint['breakpointNumber'];
- console.printLine('Breakpoint ${bpId} at ${script.name}:${line}:${col}');
+ var bpId = event.breakpoint.number;
+ console.print('Breakpoint ${bpId} at ${script.name}:${line}:${col}');
} else if (event.exception != null) {
// TODO(turnidge): Test this.
- console.printLine(
+ console.print(
'Exception ${event.exception} at ${script.name}:${line}:${col}');
} else {
- console.printLine('Paused at ${script.name}:${line}:${col}');
+ console.print('Paused at ${script.name}:${line}:${col}');
}
});
}
}
+ Future _reportBreakpointAdded(Breakpoint bpt) {
+ var script = bpt.script;
+ return script.load().then((_) {
+ var bpId = bpt.number;
+ var tokenPos = bpt.tokenPos;
+ var line = script.tokenToLine(tokenPos);
+ var col = script.tokenToCol(tokenPos);
+ if (bpt.resolved) {
+ // TODO(turnidge): If this was a future breakpoint before, we
+ // should change the message to say that the breakpoint was 'resolved',
+ // rather than 'added'.
+ console.print(
+ 'Breakpoint ${bpId} added at ${script.name}:${line}:${col}');
+ } else {
+ console.print(
+ 'Future breakpoint ${bpId} added at ${script.name}:${line}:${col}');
+ }
+ });
+ }
+
void _onEvent(ServiceEvent event) {
if (event.owner != isolate) {
return;
}
switch(event.eventType) {
case 'IsolateShutdown':
- console.printLine('Isolate shutdown');
+ console.print('Isolate shutdown');
isolate = null;
break;
@@ -364,59 +735,86 @@
break;
case 'IsolateResumed':
- console.printLine('Continuing...');
+ console.print('Continuing...');
+ break;
+
+ case 'BreakpointResolved':
+ _reportBreakpointAdded(event.breakpoint);
break;
case '_Graph':
- case 'BreakpointResolved':
case 'IsolateCreated':
case 'GC':
// Ignore these events for now.
break;
default:
- console.printLine('Unrecognized event: $event');
+ console.print('Unrecognized event: $event');
break;
}
}
- String complete(String line) {
- List<String> completions = cmd.completeCommand(line);
- if (completions.length == 0) {
- // No completions. Leave the line alone.
- return line;
- } else if (completions.length == 1) {
- // Unambiguous completion.
- return completions[0];
- } else {
- // Ambigous completion.
- completions = completions.map((s )=> s.trimRight()).toList();
- completions.sort();
- console.printBold(completions.toString());
-
- // TODO(turnidge): Complete to common prefix of all completions.
- return line;
+ static String _commonPrefix(String a, String b) {
+ int pos = 0;
+ while (pos < a.length && pos < b.length) {
+ if (a.codeUnitAt(pos) != b.codeUnitAt(pos)) {
+ break;
+ }
+ pos++;
}
+ return a.substring(0, pos);
+ }
+
+ static String _foldCompletions(List<String> values) {
+ if (values.length == 0) {
+ return '';
+ }
+ var prefix = values[0];
+ for (int i = 1; i < values.length; i++) {
+ prefix = _commonPrefix(prefix, values[i]);
+ }
+ return prefix;
+ }
+
+ Future<String> complete(String line) {
+ return cmd.completeCommand(line).then((completions) {
+ if (completions.length == 0) {
+ // No completions. Leave the line alone.
+ return line;
+ } else if (completions.length == 1) {
+ // Unambiguous completion.
+ return completions[0];
+ } else {
+ // Ambigous completion.
+ completions = completions.map((s )=> s.trimRight()).toList();
+ console.printBold(completions.toString());
+ return _foldCompletions(completions);
+ }
+ });
}
// TODO(turnidge): Implement real command line history.
String lastCommand;
- bool busy = false;
Future run(String command) {
- assert(!busy);
- busy = true;
- if (command == '') {
+ if (command == '' && lastCommand != null) {
command = lastCommand;
}
- lastCommand = command;
console.printBold('\$ $command');
return cmd.runCommand(command).then((_) {
- busy = false;
- }).catchError((e) {
- console.printLine('ERROR $e');
+ lastCommand = command;
+ }).catchError((e, s) {
+ console.print('ERROR $e\n$s');
});
}
+
+ String historyPrev(String command) {
+ return cmd.historyPrev(command);
+ }
+
+ String historyNext(String command) {
+ return cmd.historyNext(command);
+ }
}
@CustomTag('debugger-page')
@@ -428,7 +826,7 @@
debugger.isolate = isolate;
}
}
- Debugger debugger = new Debugger();
+ ObservatoryDebugger debugger = new ObservatoryDebugger();
DebuggerPageElement.created() : super.created();
@@ -468,7 +866,7 @@
@published Isolate isolate;
@observable bool hasStack = false;
@observable bool isSampled = false;
- Debugger debugger = null;
+ ObservatoryDebugger debugger;
_addFrame(List frameList, ObservableMap frameInfo, bool expand) {
DebuggerFrameElement frameElement = new Element.tag('debugger-frame');
@@ -625,20 +1023,24 @@
DebuggerConsoleElement.created() : super.created();
- void printLine(String line) {
- var div = new DivElement();
- div.classes.add('normal');
- div.appendText(line);
- $['consoleText'].children.add(div);
- div.scrollIntoView();
+ void print(String line, { bool newline:true }) {
+ var span = new SpanElement();
+ span.classes.add('normal');
+ span.appendText(line);
+ if (newline) {
+ span.appendText('\n');
+ }
+ $['consoleText'].children.add(span);
+ span.scrollIntoView();
}
- void printBold(String line) {
- var div = new DivElement();
- div.classes.add('bold');
- div.appendText(line);
- $['consoleText'].children.add(div);
- div.scrollIntoView();
+ void printBold(String line, { bool newline:true }) {
+ var span = new SpanElement();
+ span.classes.add('bold');
+ span.appendText(line);
+ span.appendText('\n');
+ $['consoleText'].children.add(span);
+ span.scrollIntoView();
}
void newline() {
@@ -652,7 +1054,8 @@
class DebuggerInputElement extends ObservatoryElement {
@published Isolate isolate;
@published String text = '';
- @observable Debugger debugger;
+ @observable ObservatoryDebugger debugger;
+ @observable bool busy = false;
@override
void ready() {
@@ -660,20 +1063,46 @@
var textBox = $['textBox'];
textBox.select();
textBox.onKeyDown.listen((KeyboardEvent e) {
+ if (busy) {
+ e.preventDefault();
+ return;
+ }
+ busy = true;
switch (e.keyCode) {
case KeyCode.TAB:
e.preventDefault();
int cursorPos = textBox.selectionStart;
- var completion = debugger.complete(text.substring(0, cursorPos));
- text = completion + text.substring(cursorPos);
- // TODO(turnidge): Move the cursor to the end of the
- // completion, rather than the end of the string.
+ debugger.complete(text.substring(0, cursorPos)).then((completion) {
+ text = completion + text.substring(cursorPos);
+ // TODO(turnidge): Move the cursor to the end of the
+ // completion, rather than the end of the string.
+ }).whenComplete(() {
+ busy = false;
+ });
break;
+
case KeyCode.ENTER:
- if (!debugger.busy) {
- debugger.run(text);
+ var command = text;
+ debugger.run(command).whenComplete(() {
text = '';
- }
+ busy = false;
+ });
+ break;
+
+ case KeyCode.UP:
+ e.preventDefault();
+ text = debugger.historyPrev(text);
+ busy = false;
+ break;
+
+ case KeyCode.DOWN:
+ e.preventDefault();
+ text = debugger.historyNext(text);
+ busy = false;
+ break;
+
+ default:
+ busy = false;
break;
}
});
diff --git a/runtime/observatory/lib/src/elements/debugger.html b/runtime/observatory/lib/src/elements/debugger.html
index 997ff77..9beb7fe 100644
--- a/runtime/observatory/lib/src/elements/debugger.html
+++ b/runtime/observatory/lib/src/elements/debugger.html
@@ -233,10 +233,12 @@
}
.normal {
font: normal 14px consolas, courier, monospace;
+ white-space: pre;
line-height: 125%;
}
.bold {
font: bold 14px consolas, courier, monospace;
+ white-space: pre;
line-height: 125%;
}
.spacer {
diff --git a/runtime/observatory/lib/src/elements/nav_bar.html b/runtime/observatory/lib/src/elements/nav_bar.html
index 97c300a..a1e40fc 100644
--- a/runtime/observatory/lib/src/elements/nav_bar.html
+++ b/runtime/observatory/lib/src/elements/nav_bar.html
@@ -325,7 +325,7 @@
_href="{{ gotoLink('/inspect', event.isolate) }}">{{ event.isolate.name }}</a>
is paused
<template if="{{ event.breakpoint != null }}">
- at breakpoint {{ event.breakpoint['breakpointNumber'] }}
+ at breakpoint {{ event.breakpoint.number }}
</template>
<template if="{{ event.eventType == 'ExceptionThrown' }}">
at exception
diff --git a/runtime/observatory/lib/src/elements/script_inset.html b/runtime/observatory/lib/src/elements/script_inset.html
index e01110a..0c00d89 100644
--- a/runtime/observatory/lib/src/elements/script_inset.html
+++ b/runtime/observatory/lib/src/elements/script_inset.html
@@ -160,13 +160,13 @@
</div>
</template>
- <template if="{{ line.bpt != null && !line.bpt['resolved'] && !busy}}">
+ <template if="{{ line.bpt != null && !line.bpt.resolved && !busy}}">
<div class="unresolvedBreakpoint">
<a on-click="{{ toggleBreakpoint }}">B</a>
</div>
</template>
- <template if="{{ line.bpt != null && line.bpt['resolved'] && !busy}}">
+ <template if="{{ line.bpt != null && line.bpt.resolved && !busy}}">
<div class="resolvedBreakpoint">
<a on-click="{{ toggleBreakpoint }}">B</a>
</div>
diff --git a/runtime/observatory/lib/src/service/object.dart b/runtime/observatory/lib/src/service/object.dart
index 47e45be..460a372 100644
--- a/runtime/observatory/lib/src/service/object.dart
+++ b/runtime/observatory/lib/src/service/object.dart
@@ -123,6 +123,9 @@
var obj = null;
assert(type != 'VM');
switch (type) {
+ case 'Breakpoint':
+ obj = new Breakpoint._empty(owner);
+ break;
case 'Class':
obj = new Class._empty(owner);
break;
@@ -1021,11 +1024,11 @@
return node;
}
- ObservableList breakpoints = new ObservableList();
+ ObservableList<Breakpoint> breakpoints = new ObservableList();
- void _removeBreakpoint(ServiceMap bpt) {
- var script = bpt['location']['script'];
- var tokenPos = bpt['location']['tokenPos'];
+ void _removeBreakpoint(Breakpoint bpt) {
+ var script = bpt.script;
+ var tokenPos = bpt.tokenPos;
assert(tokenPos != null);
if (script.loaded) {
var line = script.tokenToLine(tokenPos);
@@ -1037,9 +1040,9 @@
}
}
- void _addBreakpoint(ServiceMap bpt) {
- var script = bpt['location']['script'];
- var tokenPos = bpt['location']['tokenPos'];
+ void _addBreakpoint(Breakpoint bpt) {
+ var script = bpt.script;
+ var tokenPos = bpt.tokenPos;
assert(tokenPos != null);
if (script.loaded) {
var line = script.tokenToLine(tokenPos);
@@ -1069,7 +1072,7 @@
breakpoints.addAll(newBreakpoints['breakpoints']);
// Sort the breakpoints by breakpointNumber.
- breakpoints.sort((a, b) => (a['breakpointNumber'] - b['breakpointNumber']));
+ breakpoints.sort((a, b) => (a.number - b.number));
}
Future<ServiceObject> _inProgressReloadBpts;
@@ -1090,16 +1093,32 @@
Future<ServiceObject> addBreakpoint(Script script, int line) {
// TODO(turnidge): Pass line as an int instead of a string.
- return invokeRpc('addBreakpoint',
- { 'script': script.id, 'line': '$line' }).then((result) {
- if (result is ServiceMap &&
- result.type == 'Breakpoint' &&
- result['resolved'] &&
- script.loaded &&
- script.tokenToLine(result['location']['tokenPos']) != line) {
- // Unable to set a breakpoint at desired line.
- script.lines[line - 1].possibleBpt = false;
- }
+ Map params = {
+ 'scriptId': script.id,
+ 'line': '$line',
+ };
+ return invokeRpc('addBreakpoint', params).then((result) {
+ if (result is DartError) {
+ return result;
+ }
+ Breakpoint bpt = result;
+ if (bpt.resolved &&
+ script.loaded &&
+ script.tokenToLine(result.tokenPos) != line) {
+ // Unable to set a breakpoint at desired line.
+ script.lines[line - 1].possibleBpt = false;
+ }
+ // TODO(turnidge): Instead of reloading all of the breakpoints,
+ // rely on events to update the breakpoint list.
+ return reloadBreakpoints().then((_) {
+ return result;
+ });
+ });
+ }
+
+ Future<ServiceObject> addBreakpointAtEntry(ServiceFunction function) {
+ return invokeRpc('addBreakpointAtEntry',
+ { 'functionId': function.id }).then((result) {
// TODO(turnidge): Instead of reloading all of the breakpoints,
// rely on events to update the breakpoint list.
return reloadBreakpoints().then((_) {
@@ -1108,16 +1127,17 @@
});
}
- Future removeBreakpoint(ServiceMap bpt) {
+ Future removeBreakpoint(Breakpoint bpt) {
return invokeRpc('removeBreakpoint',
{ 'breakpointId': bpt.id }).then((result) {
if (result is DartError) {
// TODO(turnidge): Handle this more gracefully.
Logger.root.severe(result.message);
+ return result;
}
if (pauseEvent != null &&
pauseEvent.breakpoint != null &&
- (pauseEvent.breakpoint['id'] == bpt['id'])) {
+ (pauseEvent.breakpoint.id == bpt.id)) {
return isolate.reload();
} else {
return reloadBreakpoints();
@@ -1420,7 +1440,7 @@
}
@observable String eventType;
- @observable ServiceMap breakpoint;
+ @observable Breakpoint breakpoint;
@observable ServiceMap exception;
@observable ByteData data;
@observable int count;
@@ -1451,6 +1471,48 @@
}
}
+class Breakpoint extends ServiceObject {
+ Breakpoint._empty(ServiceObjectOwner owner) : super._empty(owner);
+
+ // TODO(turnidge): Add state to track if a breakpoint has been
+ // removed from the program. Remove from the cache when deleted.
+ bool get canCache => true;
+ bool get immutable => false;
+
+ // A unique integer identifier for this breakpoint.
+ @observable int number;
+
+ // Source location information.
+ @observable Script script;
+ @observable int tokenPos;
+
+ // The breakpoint has been assigned to a final source location.
+ @observable bool resolved;
+
+ // The breakpoint is active.
+ @observable bool enabled;
+
+ void _update(ObservableMap map, bool mapIsRef) {
+ _loaded = true;
+ _upgradeCollection(map, owner);
+
+ number = map['breakpointNumber'];
+ script = map['location']['script'];
+ tokenPos = map['location']['tokenPos'];
+
+ resolved = map['resolved'];
+ enabled = map['enabled'];
+ }
+
+ String toString() {
+ if (number != null) {
+ return 'Breakpoint ${number} at ${script.name}(token:${tokenPos})';
+ } else {
+ return 'Uninitialized breakpoint';
+ }
+ }
+}
+
class Library extends ServiceObject with Coverage {
@observable String url;
@reflectable final imports = new ObservableList<Library>();
@@ -1816,6 +1878,14 @@
kind = FunctionKind.fromJSON(map['kind']);
isDart = !kind.isFake();
+ if (parent == null) {
+ qualifiedName = (owningClass != null) ?
+ "${owningClass.name}.${name}" :
+ name;
+ } else {
+ qualifiedName = "${parent.qualifiedName}.${name}";
+ }
+
if (mapIsRef) { return; }
isStatic = map['static'];
@@ -1831,14 +1901,6 @@
deoptimizations = map['deoptimizations'];
usageCounter = map['usageCounter'];
- if (parent == null) {
- qualifiedName = (owningClass != null) ?
- "${owningClass.name}.${name}" :
- name;
- } else {
- qualifiedName = "${parent.qualifiedName}.${name}";
- }
-
}
}
@@ -1896,7 +1958,7 @@
final int line;
final String text;
@observable int hits;
- @observable ServiceMap bpt;
+ @observable Breakpoint bpt;
@observable bool possibleBpt = true;
bool get isBlank {
@@ -1945,10 +2007,8 @@
// TODO(turnidge): This is not so efficient. Consider improving.
for (var bpt in this.script.isolate.breakpoints) {
- var bptScript = bpt['location']['script'];
- var bptTokenPos = bpt['location']['tokenPos'];
- if (bptScript == this.script &&
- bptScript.tokenToLine(bptTokenPos) == line) {
+ if (bpt.script == this.script &&
+ bpt.script.tokenToLine(bpt.tokenPos) == line) {
this.bpt = bpt;
}
}
diff --git a/runtime/observatory/maintainers/pubspec.template b/runtime/observatory/maintainers/pubspec.template
index f2aca69..c6b306c 100644
--- a/runtime/observatory/maintainers/pubspec.template
+++ b/runtime/observatory/maintainers/pubspec.template
@@ -1,16 +1,17 @@
name: observatory
version: 1.6.0-dev.1
-dependencies:
- args: any
- polymer: any
- unittest: any
transformers:
- polymer:
entry_points:
- web/index.html
- - web/index_devtools.html
inline_stylesheets:
lib/src/elements/css/shared.css: false
- $dart2js:
suppressWarnings: false
$exclude: web/main.dart
+ commandLineOptions: [--show-package-warnings]
+dependencies:
+ args: any
+ polymer: any
+ unittest: any
+ usage: any
diff --git a/runtime/observatory/maintainers/snapshot_dependencies.sh b/runtime/observatory/maintainers/snapshot_dependencies.sh
index cd13564..68803cf 100755
--- a/runtime/observatory/maintainers/snapshot_dependencies.sh
+++ b/runtime/observatory/maintainers/snapshot_dependencies.sh
@@ -59,4 +59,8 @@
echo '***'
echo -n 'Now run: rsync -a --delete observatory_pub_packages/ '
echo '~/workspace/dart-third_party/observatory_pub_packages/'
+echo 'Then: '
+echo 'cd ~/workspace/dart-third_party/observatory_pub_packages/'
+echo "svn status | grep ^? | sed 's/? //' | xargs svn add"
+echo "svn st | grep ^! | sed 's/! //' | xargs svn rm"
echo '***'
diff --git a/runtime/observatory/observatory.status b/runtime/observatory/observatory.status
index 441a22c..e7bb129 100644
--- a/runtime/observatory/observatory.status
+++ b/runtime/observatory/observatory.status
@@ -8,4 +8,4 @@
observatory/test/*: Skip
[ $browser ]
-observatory/test/*: Skip # Uses dart:io
+observatory/test/*: SkipByDesign # Uses dart:io
diff --git a/runtime/observatory/pubspec.yaml b/runtime/observatory/pubspec.yaml
index e237f6e..ccdc3f7 100644
--- a/runtime/observatory/pubspec.yaml
+++ b/runtime/observatory/pubspec.yaml
@@ -1,9 +1,20 @@
name: observatory
version: 1.6.0-dev.1
+transformers:
+- polymer:
+ entry_points:
+ - web/index.html
+ inline_stylesheets:
+ lib/src/elements/css/shared.css: false
+- $dart2js:
+ suppressWarnings: false
+ $exclude: web/main.dart
+ commandLineOptions: [--show-package-warnings]
dependencies:
args: any
polymer: any
unittest: any
+ usage: any
dependency_overrides:
analyzer:
path: ../../third_party/observatory_pub_packages/analyzer
@@ -13,14 +24,22 @@
path: ../../third_party/observatory_pub_packages/barback
browser:
path: ../../third_party/observatory_pub_packages/browser
+ cli_util:
+ path: ../../third_party/observatory_pub_packages/cli_util
code_transformers:
path: ../../third_party/observatory_pub_packages/code_transformers
collection:
path: ../../third_party/observatory_pub_packages/collection
csslib:
path: ../../third_party/observatory_pub_packages/csslib
+ dart_style:
+ path: ../../third_party/observatory_pub_packages/dart_style
+ glob:
+ path: ../../third_party/observatory_pub_packages/glob
html5lib:
path: ../../third_party/observatory_pub_packages/html5lib
+ initialize:
+ path: ../../third_party/observatory_pub_packages/initialize
logging:
path: ../../third_party/observatory_pub_packages/logging
matcher:
@@ -49,21 +68,17 @@
path: ../../third_party/observatory_pub_packages/template_binding
unittest:
path: ../../third_party/observatory_pub_packages/unittest
+ usage:
+ path: ../../third_party/observatory_pub_packages/usage
utf:
path: ../../third_party/observatory_pub_packages/utf
watcher:
path: ../../third_party/observatory_pub_packages/watcher
web_components:
path: ../../third_party/observatory_pub_packages/web_components
+ when:
+ path: ../../third_party/observatory_pub_packages/when
+ which:
+ path: ../../third_party/observatory_pub_packages/which
yaml:
path: ../../third_party/observatory_pub_packages/yaml
-transformers:
-- polymer:
- entry_points:
- - web/index.html
- - web/index_devtools.html
- inline_stylesheets:
- lib/src/elements/css/shared.css: false
-- $dart2js:
- suppressWarnings: false
- $exclude: web/main.dart
diff --git a/runtime/observatory/test/call_site_data_test.dart b/runtime/observatory/test/call_site_data_test.dart
new file mode 100644
index 0000000..2bd23f7
--- /dev/null
+++ b/runtime/observatory/test/call_site_data_test.dart
@@ -0,0 +1,118 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library call_site_data_test;
+
+import 'package:observatory/service_io.dart';
+import 'package:unittest/unittest.dart';
+import 'test_helper.dart';
+import 'dart:async';
+
+class A { foo() => 'A'; }
+class B { foo() => 'B'; }
+class C { foo() => 'C'; }
+class D { foo() => 'D'; }
+class E { foo() => 'E'; }
+class F { foo() => 'F'; }
+class G { foo() => 'G'; }
+class H { foo() => 'H'; }
+
+monomorphic(fooable) {
+ fooable.foo();
+ return null;
+}
+polymorphic(fooable) {
+ fooable.foo();
+ return null;
+}
+megamorphic(fooable) {
+ fooable.foo();
+ return null;
+}
+
+script() {
+ for (int i = 0; i < 10; i++) monomorphic(new A());
+
+ for (int i = 0; i < 10; i++) polymorphic(new A());
+ for (int i = 0; i < 20; i++) polymorphic(new B());
+ for (int i = 0; i < 30; i++) polymorphic(new C());
+
+ for (int i = 0; i < 10; i++) megamorphic(new A());
+ for (int i = 0; i < 20; i++) megamorphic(new B());
+ for (int i = 0; i < 30; i++) megamorphic(new C());
+ for (int i = 0; i < 40; i++) megamorphic(new D());
+ for (int i = 0; i < 50; i++) megamorphic(new E());
+ for (int i = 0; i < 60; i++) megamorphic(new F());
+ for (int i = 0; i < 70; i++) megamorphic(new G());
+ for (int i = 0; i < 80; i++) megamorphic(new H());
+}
+
+
+Set<String> stringifyCacheEntries(Map callSite) {
+ return callSite['cacheEntries'].map((entry) {
+ return "${entry['receiverClass']['name']}:${entry['count']}";
+ }).toSet();
+}
+
+var tests = [
+(Isolate isolate) {
+ return isolate.rootLib.load().then((Library lib) {
+ var monomorphic = lib.functions.singleWhere((f) => f.name == 'monomorphic');
+ var polymorphic = lib.functions.singleWhere((f) => f.name == 'polymorphic');
+ var megamorphic = lib.functions.singleWhere((f) => f.name == 'megamorphic');
+
+ List tests = [];
+ tests.add(isolate.invokeRpcNoUpgrade('getCallSiteData',
+ { 'targetId': monomorphic.id })
+ .then((Map response) {
+ print("Monomorphic: $response");
+ expect(response['type'], equals('_CallSiteData'));
+ expect(response['function']['id'], equals(monomorphic.id));
+ expect(response['callSites'], isList);
+ expect(response['callSites'], hasLength(1));
+ Map callSite = response['callSites'].single;
+ expect(callSite['name'], equals('foo'));
+ // expect(callSite['deoptReasons'], equals(''));
+ expect(stringifyCacheEntries(callSite),
+ equals(['A:10'].toSet()));
+ }));
+
+ tests.add(isolate.invokeRpcNoUpgrade('getCallSiteData',
+ { 'targetId': polymorphic.id })
+ .then((Map response) {
+ print("Polymorphic: $response");
+ expect(response['type'], equals('_CallSiteData'));
+ expect(response['function']['id'], equals(polymorphic.id));
+ expect(response['callSites'], isList);
+ expect(response['callSites'], hasLength(1));
+ Map callSite = response['callSites'].single;
+ expect(callSite['name'], equals('foo'));
+ // expect(callSite['deoptReasons'], equals(''));
+ expect(stringifyCacheEntries(callSite),
+ equals(['A:10', 'B:20', 'C:30'].toSet()));
+ }));
+
+ tests.add(isolate.invokeRpcNoUpgrade('getCallSiteData',
+ { 'targetId': megamorphic.id })
+ .then((Map response) {
+ print("Megamorphic: $response");
+ expect(response['type'], equals('_CallSiteData'));
+ expect(response['function']['id'], equals(megamorphic.id));
+ expect(response['callSites'], isList);
+ expect(response['callSites'], hasLength(1));
+ Map callSite = response['callSites'].single;
+ expect(callSite['name'], equals('foo'));
+ // expect(callSite['deoptReasons'], equals(''));
+ expect(stringifyCacheEntries(callSite),
+ equals(['A:10', 'B:20', 'C:30', 'D:40',
+ 'E:50', 'F:60', 'G:70', 'H:80'].toSet()));
+ }));
+
+ return Future.wait(tests);
+ });
+},
+
+];
+
+main(args) => runIsolateTests(args, tests, testeeBefore: script);
diff --git a/runtime/observatory/test/command_test.dart b/runtime/observatory/test/command_test.dart
index b87631e..8159981 100644
--- a/runtime/observatory/test/command_test.dart
+++ b/runtime/observatory/test/command_test.dart
@@ -21,9 +21,10 @@
TestCompleteCommand(this.out, name, children) : super(name, children);
StringBuffer out;
- List<String> complete(List<String> args) {
+ Future<List<String>> complete(List<String> args) {
var possibles = ['one ', 'two ', 'three '];
- return possibles.where((possible) => possible.startsWith(args[0])).toList();
+ return new Future.value(
+ possibles.where((possible) => possible.startsWith(args[0])).toList());
}
Future run(List<String> args) {
@@ -49,79 +50,98 @@
new TestCommand(null, 'chocula', [])])]);
// Show all commands.
- expect(cmd.completeCommand(''),
- equals(['alpha ', 'game ', 'gamera ', 'count ']));
+ cmd.completeCommand('').then((result) {
+ expect(result, equals(['alpha ', 'game ', 'gamera ', 'count ']));
+ });
// Substring completion.
- expect(cmd.completeCommand('al'),
- equals(['alpha ']));
+ cmd.completeCommand('al').then((result) {
+ expect(result, equals(['alpha ']));
+ });
// Full string completion.
- expect(cmd.completeCommand('alpha'),
- equals(['alpha ']));
+ cmd.completeCommand('alpha').then((result) {
+ expect(result, equals(['alpha ']));
+ });
// Extra space, no subcommands.
- expect(cmd.completeCommand('alpha '),
- equals(['alpha ']));
+ cmd.completeCommand('alpha ').then((result) {
+ expect(result, equals(['alpha ']));
+ });
// Ambiguous completion.
- expect(cmd.completeCommand('g'),
- equals(['game ', 'gamera ']));
+ cmd.completeCommand('g').then((result) {
+ expect(result, equals(['game ', 'gamera ']));
+ });
// Ambiguous completion, exact match not preferred.
- expect(cmd.completeCommand('game'),
- equals(['game ', 'gamera ']));
+ cmd.completeCommand('game').then((result) {
+ expect(result, equals(['game ', 'gamera ']));
+ });
// Show all subcommands.
- expect(cmd.completeCommand('gamera '),
- equals(['gamera london ', 'gamera tokyo ', 'gamera topeka ']));
+ cmd.completeCommand('gamera ').then((result) {
+ expect(result, equals(['gamera london ', 'gamera tokyo ', 'gamera topeka ']));
+ });
// Subcommand completion.
- expect(cmd.completeCommand('gamera l'),
- equals(['gamera london ']));
+ cmd.completeCommand('gamera l').then((result) {
+ expect(result, equals(['gamera london ']));
+ });
// Extra space, with subcommand.
- expect(cmd.completeCommand('gamera london '),
- equals(['gamera london ']));
+ cmd.completeCommand('gamera london ').then((result) {
+ expect(result, equals(['gamera london ']));
+ });
// Ambiguous subcommand completion.
- expect(cmd.completeCommand('gamera t'),
- equals(['gamera tokyo ', 'gamera topeka ']));
+ cmd.completeCommand('gamera t').then((result) {
+ expect(result, equals(['gamera tokyo ', 'gamera topeka ']));
+ });
// Ambiguous subcommand completion with substring prefix.
// Note that the prefix is left alone.
- expect(cmd.completeCommand('gamer t'),
- equals(['gamer tokyo ', 'gamer topeka ']));
+ cmd.completeCommand('gamer t').then((result) {
+ expect(result, equals(['gamer tokyo ', 'gamer topeka ']));
+ });
// Ambiguous but exact prefix is preferred.
- expect(cmd.completeCommand('game chec'),
- equals(['game checkers ']));
+ cmd.completeCommand('game chec').then((result) {
+ expect(result, equals(['game checkers ']));
+ });
// Ambiguous non-exact prefix means no matches.
- expect(cmd.completeCommand('gam chec'),
- equals([]));
+ cmd.completeCommand('gam chec').then((result) {
+ expect(result, equals([]));
+ });
// Locals + subcommands, show all.
- expect(cmd.completeCommand('count '),
- equals(['count chocula ',
- 'count one ',
- 'count two ',
- 'count three ']));
+ cmd.completeCommand('count ').then((result) {
+ expect(result, equals(['count chocula ',
+ 'count one ',
+ 'count two ',
+ 'count three ']));
+ });
// Locals + subcommands, single local match.
- expect(cmd.completeCommand('count th '),
- equals(['count three ']));
+ cmd.completeCommand('count th ').then((result) {
+ expect(result, equals(['count three ']));
+ });
// Locals + subcommands, ambiguous local match.
- expect(cmd.completeCommand('count t'),
- equals(['count two ', 'count three ']));
+ cmd.completeCommand('count t').then((result) {
+ expect(result, equals(['count two ', 'count three ']));
+ });
// Locals + subcommands, single command match.
- expect(cmd.completeCommand('co choc'),
- equals(['co chocula ']));
+ cmd.completeCommand('co choc').then((result) {
+ expect(result, equals(['co chocula ']));
+ });
// We gobble spare spaces, even in the prefix.
- expect(cmd.completeCommand(' game chec'), equals(['game checkers ']));
+ cmd.completeCommand(' game chec').then((result) {
+ expect(result, equals(['game checkers ']));
+ });
}
void testCommandRunSimple() {
diff --git a/runtime/observatory/test/debugging_test.dart b/runtime/observatory/test/debugging_test.dart
index ac6b48c..51204e7 100644
--- a/runtime/observatory/test/debugging_test.dart
+++ b/runtime/observatory/test/debugging_test.dart
@@ -7,11 +7,15 @@
import 'test_helper.dart';
import 'dart:async';
+void helper(i) {
+ print(i);
+}
+
void testFunction() {
int i = 0;
while (true) {
if (++i % 100000000 == 0) {
- print(i); // line 14
+ helper(i); // line 18
}
}
}
@@ -43,13 +47,15 @@
// Set up a listener to wait for breakpoint events.
Completer completer = new Completer();
List events = [];
- isolate.vm.events.stream.listen((ServiceEvent event) {
+ var subscription;
+ subscription = isolate.vm.events.stream.listen((ServiceEvent event) {
if (event.eventType.startsWith('Breakpoint')) {
events.add(event);
if (events.length == 2) {
expect(events[0].eventType, equals('BreakpointResolved'));
expect(events[1].eventType, equals('BreakpointReached'));
print('Breakpoint reached');
+ subscription.cancel();
completer.complete();
}
}
@@ -57,12 +63,12 @@
// Add the breakpoint.
var script = isolate.rootLib.scripts[0];
- return isolate.addBreakpoint(script, 14).then((ServiceObject bpt) {
- expect(bpt is ServiceMap, isTrue);
- ServiceMap m = bpt;
- expect(m.type, equals('Breakpoint'));
- expect(m['location']['script'].id, equals(script.id));
- expect(m['location']['tokenPos'], equals(51));
+ return isolate.addBreakpoint(script, 18).then((result) {
+ expect(result is Breakpoint, isTrue);
+ Breakpoint bpt = result;
+ expect(bpt.type, equals('Breakpoint'));
+ expect(bpt.script.id, equals(script.id));
+ expect(bpt.tokenPos, equals(67));
expect(isolate.breakpoints.length, equals(1));
return completer.future; // Wait for breakpoint events.
});
@@ -83,10 +89,11 @@
// Set up a listener to wait for breakpoint events.
Completer completer = new Completer();
List events = [];
- isolate.vm.events.stream.listen((ServiceEvent event) {
- if (event.eventType.startsWith('Breakpoint')) {
- expect(event.eventType, equals('BreakpointReached'));
+ var subscription;
+ subscription = isolate.vm.events.stream.listen((ServiceEvent event) {
+ if (event.eventType.startsWith('BreakpointReached')) {
print('Breakpoint reached');
+ subscription.cancel();
completer.complete();
}
});
@@ -96,12 +103,12 @@
});
},
-// Get the stack trace again. We are in 'print'.
+// Get the stack trace again. We are in 'helper'.
(Isolate isolate) {
return isolate.getStack().then((ServiceMap stack) {
expect(stack.type, equals('Stack'));
expect(stack['frames'].length, greaterThanOrEqualTo(2));
- expect(stack['frames'][0]['function'].name, equals('print'));
+ expect(stack['frames'][0]['function'].name, equals('helper'));
});
},
@@ -114,6 +121,44 @@
});
},
+// Resume
+(Isolate isolate) {
+ return isolate.resume().then((_) {
+ expect(isolate.pauseEvent == null, isTrue);
+ });
+},
+
+// Add breakpoint at function entry
+(Isolate isolate) {
+ // Set up a listener to wait for breakpoint events.
+ Completer completer = new Completer();
+ List events = [];
+ var subscription;
+ subscription = isolate.vm.events.stream.listen((ServiceEvent event) {
+ if (event.eventType.startsWith('BreakpointReached')) {
+ print('Breakpoint reached');
+ subscription.cancel();
+ completer.complete();
+ }
+ });
+
+ // Find a specific function.
+ ServiceFunction function = isolate.rootLib.functions.firstWhere(
+ (f) => f.name == 'helper');
+ expect(function, isNotNull);
+
+ // Add the breakpoint at function entry
+ return isolate.addBreakpointAtEntry(function).then((result) {
+ expect(result is Breakpoint, isTrue);
+ Breakpoint bpt = result;
+ expect(bpt.type, equals('Breakpoint'));
+ expect(bpt.script.name, equals('debugging_test.dart'));
+ expect(bpt.tokenPos, equals(29));
+ expect(isolate.breakpoints.length, equals(1));
+ return completer.future; // Wait for breakpoint events.
+ });
+},
+
];
main(args) => runIsolateTests(args, tests, testeeConcurrent: testFunction);
diff --git a/runtime/observatory/test/source_location_test.dart b/runtime/observatory/test/source_location_test.dart
new file mode 100644
index 0000000..5c24d32
--- /dev/null
+++ b/runtime/observatory/test/source_location_test.dart
@@ -0,0 +1,278 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:observatory/service_io.dart';
+import 'package:observatory/debugger.dart';
+import 'package:unittest/unittest.dart';
+import 'test_helper.dart';
+import 'dart:async';
+
+void testFunction() {
+ int i = 0;
+ while (true) {
+ if (++i % 100000000 == 0) { // line 14
+ print(i);
+ }
+ }
+}
+
+class TestDebugger extends Debugger {
+ TestDebugger(this.isolate, this.stack);
+
+ Isolate isolate;
+ ServiceMap stack;
+}
+
+void source_location_dummy_function() {
+}
+
+class SourceLocationTestFoo {
+ SourceLocationTestFoo(this.field);
+ SourceLocationTestFoo.named();
+
+ void method() {}
+ void madness() {}
+
+ int field;
+}
+
+class SourceLocationTestBar {
+}
+
+Future<Debugger> initDebugger(Isolate isolate) {
+ return isolate.getStack().then((stack) {
+ return new TestDebugger(isolate, stack);
+ });
+}
+
+var tests = [
+
+// Bring the isolate to a breakpoint at line 14.
+(Isolate isolate) {
+ return isolate.rootLib.load().then((_) {
+ // Listen for breakpoint event.
+ Completer completer = new Completer();
+ isolate.vm.events.stream.listen((ServiceEvent event) {
+ if (event.eventType == 'BreakpointReached') {
+ completer.complete();
+ }
+ });
+
+ // Add the breakpoint.
+ var script = isolate.rootLib.scripts[0];
+ return isolate.addBreakpoint(script, 14).then((ServiceObject bpt) {
+ return completer.future; // Wait for breakpoint events.
+ });
+ });
+},
+
+// Parse '' => current position
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, '').then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ expect(loc.toString(), equals('source_location_test.dart:14'));
+ });
+ });
+},
+
+// Parse line
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, '15').then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ expect(loc.toString(), equals('source_location_test.dart:15'));
+ });
+ });
+},
+
+// Parse line + col
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, '15:11').then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ expect(loc.toString(), equals('source_location_test.dart:15:11'));
+ });
+ });
+},
+
+// Parse script + line
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'unittest.dart:15')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ expect(loc.toString(), equals('unittest.dart:15'));
+ });
+ });
+},
+
+// Parse script + line + col
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'unittest.dart:15:10')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ expect(loc.toString(), equals('unittest.dart:15:10'));
+ });
+ });
+},
+
+// Parse bad script
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'bad.dart:15')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isFalse);
+ expect(loc.toString(), equals(
+ 'invalid source location (Script \'bad.dart\' not found)'));
+ });
+ });
+},
+
+// Parse function
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'testFunction')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ expect(loc.toString(), equals('testFunction'));
+ });
+ });
+},
+
+// Parse bad function
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'doesNotReallyExit')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isFalse);
+ expect(loc.toString(), equals(
+ 'invalid source location (Function \'doesNotReallyExit\' not found)'));
+ });
+ });
+},
+
+// Parse constructor
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'SourceLocationTestFoo')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ // TODO(turnidge): Printing a constructor currently adds
+ // another class qualifier at the front. Do we want to change
+ // this to be more consistent?
+ expect(loc.toString(), equals(
+ 'SourceLocationTestFoo.SourceLocationTestFoo'));
+ });
+ });
+},
+
+// Parse named constructor
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'SourceLocationTestFoo.named')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ // TODO(turnidge): Printing a constructor currently adds
+ // another class qualifier at the front. Do we want to change
+ // this to be more consistent?
+ expect(loc.toString(), equals(
+ 'SourceLocationTestFoo.SourceLocationTestFoo.named'));
+ });
+ });
+},
+
+// Parse method
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'SourceLocationTestFoo.method')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ expect(loc.toString(), equals('SourceLocationTestFoo.method'));
+ });
+ });
+},
+
+// Parse method
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'SourceLocationTestFoo.field=')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isTrue);
+ expect(loc.toString(), equals('SourceLocationTestFoo.field='));
+ });
+ });
+},
+
+// Parse bad method
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.parse(debugger, 'SourceLocationTestFoo.missing')
+ .then((SourceLocation loc) {
+ expect(loc.valid, isFalse);
+ expect(loc.toString(), equals(
+ 'invalid source location '
+ '(Function \'SourceLocationTestFoo.missing\' not found)'));
+ });
+ });
+},
+
+// Complete function + script
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.complete(debugger, 'source_loc')
+ .then((List<String> completions) {
+ expect(completions.toString(), equals(
+ '[source_location_dummy_function, '
+ 'source_location.dart:, source_location_test.dart:]'));
+ });
+ });
+},
+
+// Complete class
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.complete(debugger, 'SourceLocationTe')
+ .then((List<String> completions) {
+ expect(completions.toString(), equals(
+ '[SourceLocationTestBar, SourceLocationTestFoo]'));
+ });
+ });
+},
+
+// No completions: unqualified name
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.complete(debugger, 'source_locXYZZY')
+ .then((List<String> completions) {
+ expect(completions.toString(), equals('[]'));
+ });
+ });
+},
+
+// Complete method
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.complete(debugger, 'SourceLocationTestFoo.m')
+ .then((List<String> completions) {
+ expect(completions.toString(), equals(
+ '[SourceLocationTestFoo.madness, SourceLocationTestFoo.method]'));
+ });
+ });
+},
+
+// No completions: qualified name
+(Isolate isolate) {
+ return initDebugger(isolate).then((debugger) {
+ return SourceLocation.complete(debugger, 'SourceLocationTestFoo.q')
+ .then((List<String> completions) {
+ expect(completions.toString(), equals('[]'));
+ });
+ });
+},
+
+];
+
+main(args) => runIsolateTests(args, tests, testeeConcurrent: testFunction);
diff --git a/runtime/platform/assert.cc b/runtime/platform/assert.cc
index 5410046..41f42f4 100644
--- a/runtime/platform/assert.cc
+++ b/runtime/platform/assert.cc
@@ -22,7 +22,7 @@
va_list arguments;
va_start(arguments, format);
- char buffer[2 * KB];
+ char buffer[4 * KB];
vsnprintf(buffer, sizeof(buffer), format, arguments);
va_end(arguments);
stream << buffer << std::endl;
diff --git a/runtime/platform/assert.h b/runtime/platform/assert.h
index 7aee9c3..54eb652 100644
--- a/runtime/platform/assert.h
+++ b/runtime/platform/assert.h
@@ -237,6 +237,9 @@
#define FATAL2(format, p1, p2) \
dart::Assert(__FILE__, __LINE__).Fail(format, (p1), (p2))
+#define FATAL3(format, p1, p2, p3) \
+ dart::Assert(__FILE__, __LINE__).Fail(format, (p1), (p2), (p3))
+
#define UNIMPLEMENTED() \
FATAL("unimplemented code")
diff --git a/runtime/vm/allocation.cc b/runtime/vm/allocation.cc
index f3afc1e..8b8a00d 100644
--- a/runtime/vm/allocation.cc
+++ b/runtime/vm/allocation.cc
@@ -35,4 +35,15 @@
return Allocate(size, zone);
}
+<<<<<<< .working
+
+void StackResource::UnwindAbove(Isolate* isolate, StackResource* new_top) {
+ StackResource* current_resource = isolate->top_resource();
+ while (current_resource != new_top) {
+ current_resource->~StackResource();
+ current_resource = isolate->top_resource();
+ }
+}
+
+>>>>>>> .merge-right.r43886
} // namespace dart
diff --git a/runtime/vm/allocation.h b/runtime/vm/allocation.h
index be59ce6..d65e0df 100644
--- a/runtime/vm/allocation.h
+++ b/runtime/vm/allocation.h
@@ -65,6 +65,12 @@
// StackResource is to break the header include cycles.
Isolate* isolate() const { return reinterpret_cast<Isolate*>(isolate_); }
+ // Destroy stack resources of isolate until top exit frame.
+ static void Unwind(Isolate* isolate) { UnwindAbove(isolate, NULL); }
+ // Destroy stack resources of isolate above new_top, exclusive.
+ static void UnwindAbove(Isolate* isolate, StackResource* new_top);
+
+>>>>>>> .merge-right.r43886
private:
BaseIsolate* const isolate_; // Current isolate for this stack resource.
StackResource* previous_;
diff --git a/runtime/vm/ast.cc b/runtime/vm/ast.cc
index bc70777..1dd6a8c 100644
--- a/runtime/vm/ast.cc
+++ b/runtime/vm/ast.cc
@@ -324,7 +324,7 @@
if (left_val == NULL) {
return NULL;
}
- if (!left_val->IsNumber() && !left_val->IsBool()) {
+ if (!left_val->IsNumber() && !left_val->IsBool() && !left_val->IsString()) {
return NULL;
}
const Instance* right_val = this->right()->EvalConstExpr();
@@ -333,6 +333,10 @@
}
switch (kind_) {
case Token::kADD:
+ if (left_val->IsString()) {
+ return right_val->IsString() ? left_val : NULL;
+ }
+ // Fall-through intentional.
case Token::kSUB:
case Token::kMUL:
case Token::kDIV:
@@ -531,6 +535,23 @@
}
+bool InstanceGetterNode::IsPotentiallyConst() const {
+ return field_name().Equals(Symbols::Length()) &&
+ receiver()->IsPotentiallyConst();
+}
+
+
+const Instance* InstanceGetterNode::EvalConstExpr() const {
+ if (field_name().Equals(Symbols::Length())) {
+ const Instance* receiver_val = receiver()->EvalConstExpr();
+ if ((receiver_val != NULL) && receiver_val->IsString()) {
+ return &Instance::ZoneHandle(Smi::New(1));
+ }
+ }
+ return NULL;
+}
+
+
AstNode* LoadIndexedNode::MakeAssignmentNode(AstNode* rhs) {
return new StoreIndexedNode(token_pos(), array(), index_expr(),
rhs, super_class());
diff --git a/runtime/vm/ast.h b/runtime/vm/ast.h
index b81ae74..c6761fd 100644
--- a/runtime/vm/ast.h
+++ b/runtime/vm/ast.h
@@ -129,6 +129,14 @@
return NULL;
}
+ // Returns true if this node can be a compile-time constant, assuming
+ // that all nodes it depends on are also compile-time constants of
+ // the proper types and values.
+ // See the concept of "potentially constant expression" in the language spec.
+ // The purpose of IsPotentiallyConst is to detect cases where the node is
+ // known NOT to be a constant expression, in which case false is returned and
+ // a compile-time error is reported by the compiler. Otherwise, an error may
+ // still be reported at run-time depending on actual values.
virtual bool IsPotentiallyConst() const { return false; }
// Analyzes an expression to determine whether it is a compile time
@@ -1423,6 +1431,9 @@
virtual AstNode* MakeAssignmentNode(AstNode* rhs);
+ virtual bool IsPotentiallyConst() const;
+ virtual const Instance* EvalConstExpr() const;
+
DECLARE_COMMON_NODE_FUNCTIONS(InstanceGetterNode);
private:
diff --git a/runtime/vm/ast_transformer.cc b/runtime/vm/ast_transformer.cc
index 31d4a57..f829dae 100644
--- a/runtime/vm/ast_transformer.cc
+++ b/runtime/vm/ast_transformer.cc
@@ -186,7 +186,7 @@
preamble_->Add(new (Z) StoreLocalNode(
Scanner::kNoSourcePos,
result_param,
- new(Z) InstanceCallNode(Scanner::kNoSourcePos,
+ new(Z) InstanceCallNode(node->token_pos(),
load_result_param,
Symbols::FutureThen(),
args)));
diff --git a/runtime/vm/base_isolate.h b/runtime/vm/base_isolate.h
index eeaee60..5abe170 100644
--- a/runtime/vm/base_isolate.h
+++ b/runtime/vm/base_isolate.h
@@ -5,6 +5,8 @@
#ifndef VM_BASE_ISOLATE_H_
#define VM_BASE_ISOLATE_H_
+#include "vm/globals.h"
+
namespace dart {
class HandleScope;
@@ -18,6 +20,9 @@
public:
StackResource* top_resource() const { return top_resource_; }
void set_top_resource(StackResource* value) { top_resource_ = value; }
+ static intptr_t top_resource_offset() {
+ return OFFSET_OF(BaseIsolate, top_resource_);
+ }
// DEPRECATED: Use Thread::current_zone.
Zone* current_zone() const { return current_zone_; }
diff --git a/runtime/vm/bootstrap_natives.h b/runtime/vm/bootstrap_natives.h
index 32719ac..11307ab 100644
--- a/runtime/vm/bootstrap_natives.h
+++ b/runtime/vm/bootstrap_natives.h
@@ -13,6 +13,7 @@
// List of bootstrap native entry points used in the core dart library.
#define BOOTSTRAP_NATIVE_LIST(V) \
+ V(DartCore_fatal, 1) \
V(Object_equals, 2) \
V(Object_getHash, 1) \
V(Object_setHash, 2) \
@@ -140,9 +141,6 @@
V(TypeError_throwNew, 5) \
V(FallThroughError_throwNew, 1) \
V(AbstractClassInstantiationError_throwNew, 2) \
- V(Stacktrace_getFullStacktrace, 1) \
- V(Stacktrace_getStacktrace, 1) \
- V(Stacktrace_setupFullStacktrace, 1) \
V(Stopwatch_now, 0) \
V(Stopwatch_frequency, 0) \
V(TypedData_Int8Array_new, 1) \
@@ -331,6 +329,7 @@
V(LibraryMirror_invokeSetter, 4) \
V(TypeVariableMirror_owner, 1) \
V(TypeVariableMirror_upper_bound, 1) \
+ V(DeclarationMirror_location, 1) \
V(DeclarationMirror_metadata, 1) \
V(FunctionTypeMirror_call_method, 2) \
V(FunctionTypeMirror_parameters, 2) \
@@ -339,7 +338,6 @@
V(MethodMirror_parameters, 2) \
V(MethodMirror_return_type, 2) \
V(MethodMirror_source, 1) \
- V(MethodMirror_location, 1) \
V(ParameterMirror_type, 3) \
V(TypedefMirror_referent, 1) \
V(TypedefMirror_declaration, 1) \
@@ -362,6 +360,7 @@
V(LinkedHashMap_toArray, 1) \
V(LinkedHashMap_getModMark, 2) \
V(LinkedHashMap_useInternal, 0) \
+ V(LinkedHashMap_useCompact, 0) \
V(WeakProperty_new, 2) \
V(WeakProperty_getKey, 1) \
V(WeakProperty_getValue, 1) \
diff --git a/runtime/vm/code_generator.cc b/runtime/vm/code_generator.cc
index 38b5f2f..63a80ca 100644
--- a/runtime/vm/code_generator.cc
+++ b/runtime/vm/code_generator.cc
@@ -639,8 +639,8 @@
DEFINE_RUNTIME_ENTRY(ReThrow, 2) {
const Instance& exception =
Instance::CheckedHandle(isolate, arguments.ArgAt(0));
- const Stacktrace& stacktrace =
- Stacktrace::CheckedHandle(isolate, arguments.ArgAt(1));
+ const Instance& stacktrace =
+ Instance::CheckedHandle(isolate, arguments.ArgAt(1));
Exceptions::ReThrow(isolate, exception, stacktrace);
}
@@ -1112,7 +1112,7 @@
#if defined(USING_SIMULATOR)
uword stack_pos = Simulator::Current()->get_register(SPREG);
#else
- uword stack_pos = reinterpret_cast<uword>(&arguments);
+ uword stack_pos = Isolate::GetCurrentStackPointer();
#endif
// Always clear the stack overflow flags. They are meant for this
// particular stack overflow runtime call and are not meant to
diff --git a/runtime/vm/compiler.cc b/runtime/vm/compiler.cc
index 0a2269d..168bd37 100644
--- a/runtime/vm/compiler.cc
+++ b/runtime/vm/compiler.cc
@@ -657,6 +657,9 @@
DeadCodeElimination::EliminateDeadPhis(flow_graph);
DEBUG_ASSERT(flow_graph->VerifyUseLists());
+ FlowGraphTypePropagator::Propagate(flow_graph);
+ DEBUG_ASSERT(flow_graph->VerifyUseLists());
+
// Ensure that all phis inserted by optimization passes have consistent
// representations.
optimizer.SelectRepresentations();
diff --git a/runtime/vm/constant_propagator.cc b/runtime/vm/constant_propagator.cc
index 8cbb12d..08f80d8 100644
--- a/runtime/vm/constant_propagator.cc
+++ b/runtime/vm/constant_propagator.cc
@@ -957,20 +957,29 @@
}
+void ConstantPropagator::VisitUnaryIntegerOp(UnaryIntegerOpInstr* unary_op) {
+ const Object& value = unary_op->value()->definition()->constant_value();
+ if (IsConstant(value) && value.IsInteger()) {
+ const Integer& value_int = Integer::Cast(value);
+ const Integer& result =
+ Integer::Handle(I, unary_op->Evaluate(value_int));
+ if (!result.IsNull()) {
+ SetValue(unary_op, Integer::ZoneHandle(I, result.raw()));
+ return;
+ }
+ }
+
+ SetValue(unary_op, non_constant_);
+}
+
+
void ConstantPropagator::VisitUnaryMintOp(UnaryMintOpInstr* instr) {
- // TODO(kmillikin): Handle unary operations.
- SetValue(instr, non_constant_);
+ VisitUnaryIntegerOp(instr);
}
void ConstantPropagator::VisitUnarySmiOp(UnarySmiOpInstr* instr) {
- const Object& value = instr->value()->definition()->constant_value();
- if (IsNonConstant(value)) {
- SetValue(instr, non_constant_);
- } else if (IsConstant(value)) {
- // TODO(kmillikin): Handle unary operations.
- SetValue(instr, non_constant_);
- }
+ VisitUnaryIntegerOp(instr);
}
diff --git a/runtime/vm/constant_propagator.h b/runtime/vm/constant_propagator.h
index c8a2b59..024cbef 100644
--- a/runtime/vm/constant_propagator.h
+++ b/runtime/vm/constant_propagator.h
@@ -60,6 +60,7 @@
}
void VisitBinaryIntegerOp(BinaryIntegerOpInstr* binary_op);
+ void VisitUnaryIntegerOp(UnaryIntegerOpInstr* unary_op);
virtual void VisitBlocks() { UNREACHABLE(); }
diff --git a/runtime/vm/dart.cc b/runtime/vm/dart.cc
index 2d86044..b497da0 100644
--- a/runtime/vm/dart.cc
+++ b/runtime/vm/dart.cc
@@ -20,7 +20,7 @@
#include "vm/object_id_ring.h"
#include "vm/port.h"
#include "vm/profiler.h"
-#include "vm/service.h"
+#include "vm/service_isolate.h"
#include "vm/simulator.h"
#include "vm/snapshot.h"
#include "vm/stub_code.h"
@@ -112,7 +112,8 @@
{
ASSERT(vm_isolate_ == NULL);
ASSERT(Flags::Initialized());
- vm_isolate_ = Isolate::Init("vm-isolate");
+ const bool is_vm_isolate = true;
+ vm_isolate_ = Isolate::Init("vm-isolate", is_vm_isolate);
StackZone zone(vm_isolate_);
HandleScope handle_scope(vm_isolate_);
Heap::Init(vm_isolate_,
@@ -124,6 +125,8 @@
Object::InitOnce(vm_isolate_);
ArgumentsDescriptor::InitOnce();
StubCode::InitOnce();
+ // Now that the needed stub has been generated, set the stack limit.
+ vm_isolate_->InitializeStackLimit();
Symbols::InitOnce(vm_isolate_);
Scanner::InitOnce();
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)
@@ -146,7 +149,7 @@
Isolate::SetUnhandledExceptionCallback(unhandled);
Isolate::SetShutdownCallback(shutdown);
- Service::RunService();
+ ServiceIsolate::Run();
return NULL;
}
@@ -261,9 +264,9 @@
isolate->class_table()->Print();
}
- Service::MaybeInjectVMServiceLibrary(isolate);
+ ServiceIsolate::MaybeInjectVMServiceLibrary(isolate);
- Service::SendIsolateStartupMessage();
+ ServiceIsolate::SendIsolateStartupMessage();
isolate->debugger()->NotifyIsolateCreated();
// Create tag table.
@@ -281,7 +284,7 @@
Isolate* isolate = Isolate::Current();
void* callback_data = isolate->init_callback_data();
Dart_IsolateShutdownCallback callback = Isolate::ShutdownCallback();
- Service::SendIsolateShutdownMessage();
+ ServiceIsolate::SendIsolateShutdownMessage();
if (callback != NULL) {
(callback)(callback_data);
}
diff --git a/runtime/vm/dart_api_impl.cc b/runtime/vm/dart_api_impl.cc
index 64b96c80..a67ed54 100644
--- a/runtime/vm/dart_api_impl.cc
+++ b/runtime/vm/dart_api_impl.cc
@@ -30,6 +30,7 @@
#include "vm/profiler.h"
#include "vm/resolver.h"
#include "vm/reusable_handles.h"
+#include "vm/service_isolate.h"
#include "vm/service.h"
#include "vm/stack_frame.h"
#include "vm/symbols.h"
@@ -1252,7 +1253,7 @@
}
}
- if (Service::IsServiceIsolateName(script_uri)) {
+ if (ServiceIsolate::NameEquals(script_uri)) {
return strdup(script_uri);
}
@@ -5457,12 +5458,12 @@
DART_EXPORT bool Dart_IsServiceIsolate(Dart_Isolate isolate) {
Isolate* iso = reinterpret_cast<Isolate*>(isolate);
- return Service::IsServiceIsolate(iso);
+ return ServiceIsolate::IsServiceIsolate(iso);
}
DART_EXPORT Dart_Port Dart_ServiceWaitForLoadPort() {
- return Service::WaitForLoadPort();
+ return ServiceIsolate::WaitForLoadPort();
}
diff --git a/runtime/vm/dart_entry.cc b/runtime/vm/dart_entry.cc
index 6a14928..b14ded6 100644
--- a/runtime/vm/dart_entry.cc
+++ b/runtime/vm/dart_entry.cc
@@ -31,19 +31,17 @@
class ScopedIsolateStackLimits : public ValueObject {
public:
explicit ScopedIsolateStackLimits(Isolate* isolate)
- : isolate_(isolate) {
+ : isolate_(isolate), stack_base_(Isolate::GetCurrentStackPointer()) {
ASSERT(isolate_ != NULL);
ASSERT(isolate_ == Isolate::Current());
- uword stack_base = reinterpret_cast<uword>(this);
- if (stack_base >= isolate_->stack_base()) {
- isolate_->SetStackLimitFromStackBase(stack_base);
+ if (stack_base_ >= isolate_->stack_base()) {
+ isolate_->SetStackLimitFromStackBase(stack_base_);
}
}
~ScopedIsolateStackLimits() {
ASSERT(isolate_ == Isolate::Current());
- uword stack_base = reinterpret_cast<uword>(this);
- if (isolate_->stack_base() == stack_base) {
+ if (isolate_->stack_base() == stack_base_) {
// Bottomed out.
isolate_->ClearStackLimit();
}
@@ -51,6 +49,7 @@
private:
Isolate* isolate_;
+ uword stack_base_;
};
diff --git a/runtime/vm/debugger.cc b/runtime/vm/debugger.cc
index 3734659..d9a8d97 100644
--- a/runtime/vm/debugger.cc
+++ b/runtime/vm/debugger.cc
@@ -19,6 +19,7 @@
#include "vm/object_store.h"
#include "vm/os.h"
#include "vm/port.h"
+#include "vm/service_isolate.h"
#include "vm/service.h"
#include "vm/stack_frame.h"
#include "vm/stub_code.h"
@@ -1069,7 +1070,7 @@
delete bpt;
}
// Signal isolate shutdown event.
- if (!Service::IsServiceIsolate(isolate_)) {
+ if (!ServiceIsolate::IsServiceIsolate(isolate_)) {
SignalIsolateEvent(DebuggerEvent::kIsolateShutdown);
}
}
@@ -2131,7 +2132,7 @@
if (!func.is_debuggable()) {
return false;
}
- if (Service::IsRunning()) {
+ if (ServiceIsolate::IsRunning()) {
return true;
}
const Class& cls = Class::Handle(func.Owner());
@@ -2269,7 +2270,7 @@
void Debugger::NotifyIsolateCreated() {
// Signal isolate creation event.
- if (!Service::IsServiceIsolate(isolate_)) {
+ if (!ServiceIsolate::IsServiceIsolate(isolate_)) {
SignalIsolateEvent(DebuggerEvent::kIsolateCreated);
}
}
diff --git a/runtime/vm/disassembler_ia32.cc b/runtime/vm/disassembler_ia32.cc
index b81fdde..7d24929 100644
--- a/runtime/vm/disassembler_ia32.cc
+++ b/runtime/vm/disassembler_ia32.cc
@@ -1024,6 +1024,7 @@
case 0xF5: mnem = "fprem1"; break;
case 0xF8: mnem = "fprem"; break;
case 0xF7: mnem = "fincstp"; break;
+ case 0xFB: mnem = "fsincos"; break;
case 0xFE: mnem = "fsin"; break;
case 0xFF: mnem = "fcos"; break;
}
diff --git a/runtime/vm/exceptions.cc b/runtime/vm/exceptions.cc
index d863b24..7247d0f 100644
--- a/runtime/vm/exceptions.cc
+++ b/runtime/vm/exceptions.cc
@@ -31,59 +31,30 @@
StacktraceBuilder() { }
virtual ~StacktraceBuilder() { }
- virtual void AddFrame(const Code& code,
- const Smi& offset,
- bool is_catch_frame) = 0;
-
- virtual bool FullStacktrace() const = 0;
+ virtual void AddFrame(const Code& code, const Smi& offset) = 0;
};
class RegularStacktraceBuilder : public StacktraceBuilder {
public:
- explicit RegularStacktraceBuilder(bool full_stacktrace)
- : code_list_(GrowableObjectArray::Handle(GrowableObjectArray::New())),
+ explicit RegularStacktraceBuilder(Isolate* isolate)
+ : code_list_(
+ GrowableObjectArray::Handle(isolate, GrowableObjectArray::New())),
pc_offset_list_(
- GrowableObjectArray::Handle(GrowableObjectArray::New())),
- catch_code_list_(
- full_stacktrace ?
- GrowableObjectArray::Handle(GrowableObjectArray::New()) :
- GrowableObjectArray::Handle()),
- catch_pc_offset_list_(
- full_stacktrace ?
- GrowableObjectArray::Handle(GrowableObjectArray::New()) :
- GrowableObjectArray::Handle()),
- full_stacktrace_(full_stacktrace) { }
+ GrowableObjectArray::Handle(isolate, GrowableObjectArray::New())) { }
~RegularStacktraceBuilder() { }
const GrowableObjectArray& code_list() const { return code_list_; }
const GrowableObjectArray& pc_offset_list() const { return pc_offset_list_; }
- const GrowableObjectArray& catch_code_list() const {
- return catch_code_list_;
- }
- const GrowableObjectArray& catch_pc_offset_list() const {
- return catch_pc_offset_list_;
- }
- virtual bool FullStacktrace() const { return full_stacktrace_; }
- virtual void AddFrame(const Code& code,
- const Smi& offset,
- bool is_catch_frame) {
- if (is_catch_frame) {
- catch_code_list_.Add(code);
- catch_pc_offset_list_.Add(offset);
- } else {
- code_list_.Add(code);
- pc_offset_list_.Add(offset);
- }
+ virtual void AddFrame(const Code& code, const Smi& offset) {
+ code_list_.Add(code);
+ pc_offset_list_.Add(offset);
}
private:
const GrowableObjectArray& code_list_;
const GrowableObjectArray& pc_offset_list_;
- const GrowableObjectArray& catch_code_list_;
- const GrowableObjectArray& catch_pc_offset_list_;
- bool full_stacktrace_;
DISALLOW_COPY_AND_ASSIGN(RegularStacktraceBuilder);
};
@@ -91,22 +62,18 @@
class PreallocatedStacktraceBuilder : public StacktraceBuilder {
public:
- explicit PreallocatedStacktraceBuilder(const Stacktrace& stacktrace)
- : stacktrace_(stacktrace),
+ explicit PreallocatedStacktraceBuilder(const Instance& stacktrace)
+ : stacktrace_(Stacktrace::Cast(stacktrace)),
cur_index_(0) {
ASSERT(stacktrace_.raw() ==
Isolate::Current()->object_store()->preallocated_stack_trace());
}
~PreallocatedStacktraceBuilder() { }
- virtual void AddFrame(const Code& code,
- const Smi& offset,
- bool is_catch_frame);
-
- virtual bool FullStacktrace() const { return false; }
+ virtual void AddFrame(const Code& code, const Smi& offset);
private:
- static const int kNumTopframes = 3;
+ static const int kNumTopframes = Stacktrace::kPreallocatedStackdepth / 2;
const Stacktrace& stacktrace_;
intptr_t cur_index_;
@@ -116,8 +83,7 @@
void PreallocatedStacktraceBuilder::AddFrame(const Code& code,
- const Smi& offset,
- bool is_catch_frame) {
+ const Smi& offset) {
if (cur_index_ >= Stacktrace::kPreallocatedStackdepth) {
// The number of frames is overflowing the preallocated stack trace object.
Code& frame_code = Code::Handle();
@@ -151,38 +117,11 @@
ASSERT(frame != NULL); // We expect to find a dart invocation frame.
Code& code = Code::Handle();
Smi& offset = Smi::Handle();
- bool dart_handler_found = false;
- bool handler_pc_set = false;
while (frame != NULL) {
- while (!frame->IsEntryFrame()) {
- if (frame->IsDartFrame()) {
- code = frame->LookupDartCode();
- offset = Smi::New(frame->pc() - code.EntryPoint());
- builder->AddFrame(code, offset, dart_handler_found);
- bool needs_stacktrace = false;
- bool is_catch_all = false;
- uword handler_pc = kUwordMax;
- if (!handler_pc_set &&
- frame->FindExceptionHandler(isolate,
- &handler_pc,
- &needs_stacktrace,
- &is_catch_all)) {
- handler_pc_set = true;
- dart_handler_found = true;
- if (!builder->FullStacktrace()) {
- return;
- }
- }
- }
- frame = frames.NextFrame();
- ASSERT(frame != NULL);
- }
- ASSERT(frame->IsEntryFrame());
- if (!handler_pc_set) {
- handler_pc_set = true;
- if (!builder->FullStacktrace()) {
- return;
- }
+ if (frame->IsDartFrame()) {
+ code = frame->LookupDartCode();
+ offset = Smi::New(frame->pc() - code.EntryPoint());
+ builder->AddFrame(code, offset);
}
frame = frames.NextFrame();
}
@@ -281,11 +220,8 @@
#else
// Prepare for unwinding frames by destroying all the stack resources
// in the previous frames.
-
- while (isolate->top_resource() != NULL &&
- (reinterpret_cast<uword>(isolate->top_resource()) < stack_pointer)) {
- isolate->top_resource()->~StackResource();
- }
+ StackResource::Unwind(isolate);
+>>>>>>> .merge-right.r43886
// Call a stub to set up the exception object in kExceptionObjectReg,
// to set up the stacktrace object in kStackTraceObjectReg, and to
@@ -339,7 +275,7 @@
RawStacktrace* Exceptions::CurrentStacktrace() {
Isolate* isolate = Isolate::Current();
- RegularStacktraceBuilder frame_builder(true);
+ RegularStacktraceBuilder frame_builder(isolate);
BuildStackTrace(isolate, &frame_builder);
// Create arrays for code and pc_offset tuples of each frame.
@@ -347,21 +283,15 @@
Array::MakeArray(frame_builder.code_list()));
const Array& full_pc_offset_array = Array::Handle(isolate,
Array::MakeArray(frame_builder.pc_offset_list()));
- const Array& full_catch_code_array = Array::Handle(isolate,
- Array::MakeArray(frame_builder.catch_code_list()));
- const Array& full_catch_pc_offset_array = Array::Handle(isolate,
- Array::MakeArray(frame_builder.catch_pc_offset_list()));
const Stacktrace& full_stacktrace = Stacktrace::Handle(
Stacktrace::New(full_code_array, full_pc_offset_array));
- full_stacktrace.SetCatchStacktrace(full_catch_code_array,
- full_catch_pc_offset_array);
return full_stacktrace.raw();
}
static void ThrowExceptionHelper(Isolate* isolate,
const Instance& incoming_exception,
- const Stacktrace& existing_stacktrace,
+ const Instance& existing_stacktrace,
const bool is_rethrow) {
bool use_preallocated_stacktrace = false;
Instance& exception = Instance::Handle(isolate, incoming_exception.raw());
@@ -375,7 +305,7 @@
uword handler_pc = 0;
uword handler_sp = 0;
uword handler_fp = 0;
- Stacktrace& stacktrace = Stacktrace::Handle(isolate);
+ Instance& stacktrace = Instance::Handle(isolate);
bool handler_exists = false;
bool handler_needs_stacktrace = false;
if (use_preallocated_stacktrace) {
@@ -390,54 +320,35 @@
BuildStackTrace(isolate, &frame_builder);
}
} else {
- // Get stacktrace field of class Error.
+ // Get stacktrace field of class Error. This is needed to determine whether
+ // we have a subclass of Error which carries around its stack trace.
const Field& stacktrace_field =
Field::Handle(isolate, LookupStacktraceField(exception));
+
+ // Find the exception handler and determine if the handler needs a
+ // stacktrace.
handler_exists = FindExceptionHandler(isolate,
&handler_pc,
&handler_sp,
&handler_fp,
&handler_needs_stacktrace);
- if (!stacktrace_field.IsNull() || handler_needs_stacktrace) {
- Array& code_array = Array::Handle(isolate, Object::empty_array().raw());
- Array& pc_offset_array =
- Array::Handle(isolate, Object::empty_array().raw());
- // If we have an error with a stacktrace field then collect the full stack
- // trace and store it into the field.
- if (!stacktrace_field.IsNull()) {
- if (exception.GetField(stacktrace_field) == Object::null()) {
- // This is an error object and we need to capture the full stack trace
- // here implicitly, so we set up the stack trace. The stack trace
- // field is set only once, it is not overriden.
- const Stacktrace& full_stacktrace =
- Stacktrace::Handle(isolate, Exceptions::CurrentStacktrace());
- exception.SetField(stacktrace_field, full_stacktrace);
- }
- }
- if (handler_needs_stacktrace) {
- RegularStacktraceBuilder frame_builder(false);
- BuildStackTrace(isolate, &frame_builder);
-
- // Create arrays for code and pc_offset tuples of each frame.
- code_array = Array::MakeArray(frame_builder.code_list());
- pc_offset_array = Array::MakeArray(frame_builder.pc_offset_list());
- }
- if (existing_stacktrace.IsNull()) {
- stacktrace = Stacktrace::New(code_array, pc_offset_array);
- } else {
- ASSERT(is_rethrow);
- stacktrace = existing_stacktrace.raw();
- if (pc_offset_array.Length() != 0) {
- // Skip the first frame during a rethrow. This is the catch clause
- // with the rethrow statement, which is not part of the original
- // trace a rethrow is supposed to preserve.
- stacktrace.Append(code_array, pc_offset_array, 1);
- }
- // Since we are re throwing and appending to the existing stack trace
- // we clear out the catch trace collected in the existing stack trace
- // as that trace will not be valid anymore.
- stacktrace.SetCatchStacktrace(Object::empty_array(),
- Object::empty_array());
+ if (!existing_stacktrace.IsNull()) {
+ // If we have an existing stack trace then this better be a rethrow. The
+ // reverse is not necessarily true (e.g. Dart_PropagateError can cause
+ // a rethrow being called without an existing stacktrace.)
+ ASSERT(is_rethrow);
+ ASSERT(stacktrace_field.IsNull() ||
+ (exception.GetField(stacktrace_field) != Object::null()));
+ stacktrace = existing_stacktrace.raw();
+ } else if (!stacktrace_field.IsNull() || handler_needs_stacktrace) {
+ // Collect the stacktrace if needed.
+ ASSERT(existing_stacktrace.IsNull());
+ stacktrace = Exceptions::CurrentStacktrace();
+ // If we have an Error object, then set its stackTrace field only if it
+ // not yet initialized.
+ if (!stacktrace_field.IsNull() &&
+ (exception.GetField(stacktrace_field) == Object::null())) {
+ exception.SetField(stacktrace_field, stacktrace);
}
}
}
@@ -579,7 +490,7 @@
void Exceptions::ReThrow(Isolate* isolate,
const Instance& exception,
- const Stacktrace& stacktrace) {
+ const Instance& stacktrace) {
// Null object is a valid exception object.
ThrowExceptionHelper(isolate, exception, stacktrace, true);
}
@@ -593,7 +504,7 @@
// rethrow the exception in the normal fashion.
const UnhandledException& uhe = UnhandledException::Cast(error);
const Instance& exc = Instance::Handle(isolate, uhe.exception());
- const Stacktrace& stk = Stacktrace::Handle(isolate, uhe.stacktrace());
+ const Instance& stk = Instance::Handle(isolate, uhe.stacktrace());
Exceptions::ReThrow(isolate, exc, stk);
} else {
// Return to the invocation stub and return this error object. The
diff --git a/runtime/vm/exceptions.h b/runtime/vm/exceptions.h
index 9743ca8..de7e9e3 100644
--- a/runtime/vm/exceptions.h
+++ b/runtime/vm/exceptions.h
@@ -34,7 +34,7 @@
static void Throw(Isolate* isolate, const Instance& exception);
static void ReThrow(Isolate* isolate,
const Instance& exception,
- const Stacktrace& stacktrace);
+ const Instance& stacktrace);
static void PropagateError(const Error& error);
// Helpers to create and throw errors.
diff --git a/runtime/vm/flow_graph_builder.cc b/runtime/vm/flow_graph_builder.cc
index dad8cef..b765f5f 100644
--- a/runtime/vm/flow_graph_builder.cc
+++ b/runtime/vm/flow_graph_builder.cc
@@ -4000,7 +4000,7 @@
void EffectGraphVisitor::VisitCatchClauseNode(CatchClauseNode* node) {
InlineBailout("EffectGraphVisitor::VisitCatchClauseNode (exception)");
- // Restores current context from local variable ':saved_context'.
+ // Restores current context from local variable ':saved_try_context_var'.
BuildRestoreContext(node->context_var());
EffectGraphVisitor for_catch(owner());
@@ -4016,7 +4016,7 @@
ASSERT(try_handler_index != original_handler_index);
owner()->set_try_index(try_handler_index);
- // Preserve current context into local variable '%saved_context'.
+ // Preserve current context into local variable ':saved_try_context_var'.
BuildSaveContext(node->context_var());
EffectGraphVisitor for_try(owner());
@@ -4057,25 +4057,26 @@
catch_block->Visit(&for_catch);
owner()->set_catch_try_index(prev_catch_try_index);
- // NOTE: The implicit variables ':saved_context', ':exception_var'
- // and ':stacktrace_var' can never be captured variables.
+ // NOTE: The implicit variables ':saved_try_context_var', ':exception_var'
+ // and ':stack_trace_var' can never be captured variables.
+ ASSERT(!catch_block->context_var().is_captured());
ASSERT(!catch_block->exception_var().is_captured());
ASSERT(!catch_block->stacktrace_var().is_captured());
CatchBlockEntryInstr* catch_entry =
new(I) CatchBlockEntryInstr(owner()->AllocateBlockId(),
- catch_handler_index,
- catch_block->handler_types(),
- try_handler_index,
- catch_block->exception_var(),
- catch_block->stacktrace_var(),
- catch_block->needs_stacktrace());
+ catch_handler_index,
+ catch_block->handler_types(),
+ try_handler_index,
+ catch_block->exception_var(),
+ catch_block->stacktrace_var(),
+ catch_block->needs_stacktrace());
owner()->AddCatchEntry(catch_entry);
AppendFragment(catch_entry, for_catch);
if (for_catch.is_open()) {
JoinEntryInstr* join = new(I) JoinEntryInstr(owner()->AllocateBlockId(),
- original_handler_index);
+ original_handler_index);
for_catch.Goto(join);
if (is_open()) Goto(join);
exit_ = join;
@@ -4107,12 +4108,12 @@
types.SetAt(0, Type::Handle(I, Type::DynamicType()));
CatchBlockEntryInstr* finally_entry =
new(I) CatchBlockEntryInstr(owner()->AllocateBlockId(),
- original_handler_index,
- types,
- catch_handler_index,
- catch_block->exception_var(),
- catch_block->stacktrace_var(),
- catch_block->needs_stacktrace());
+ original_handler_index,
+ types,
+ catch_handler_index,
+ catch_block->exception_var(),
+ catch_block->stacktrace_var(),
+ catch_block->needs_stacktrace());
owner()->AddCatchEntry(finally_entry);
AppendFragment(finally_entry, for_finally);
}
diff --git a/runtime/vm/flow_graph_optimizer.cc b/runtime/vm/flow_graph_optimizer.cc
index 2a4a5db..17e5c08 100644
--- a/runtime/vm/flow_graph_optimizer.cc
+++ b/runtime/vm/flow_graph_optimizer.cc
@@ -33,6 +33,7 @@
DEFINE_FLAG(int, max_equality_polymorphic_checks, 32,
"Maximum number of polymorphic checks in equality operator,"
" otherwise use megamorphic dispatch.");
+DEFINE_FLAG(bool, merge_sin_cos, false, "Merge sin/cos into sincos");
DEFINE_FLAG(bool, trace_load_optimization, false,
"Print live sets for load optimization pass.");
DEFINE_FLAG(bool, trace_optimization, false, "Print optimization details.");
@@ -436,7 +437,8 @@
// Tries to merge MathUnary operations, in this case sinus and cosinus.
void FlowGraphOptimizer::TryMergeMathUnary(
GrowableArray<MathUnaryInstr*>* merge_candidates) {
- if (!FlowGraphCompiler::SupportsSinCos() || !CanUnboxDouble()) {
+ if (!FlowGraphCompiler::SupportsSinCos() || !CanUnboxDouble() ||
+ !FLAG_merge_sin_cos) {
return;
}
if (merge_candidates->length() < 2) {
@@ -453,8 +455,8 @@
ASSERT((kind == MathUnaryInstr::kSin) ||
(kind == MathUnaryInstr::kCos));
// Check if there is sin/cos binop with same inputs.
- const intptr_t other_kind = (kind == MethodRecognizer::kMathSin) ?
- MethodRecognizer::kMathCos : MethodRecognizer::kMathSin;
+ const intptr_t other_kind = (kind == MathUnaryInstr::kSin) ?
+ MathUnaryInstr::kCos : MathUnaryInstr::kSin;
Definition* def = curr_instr->value()->definition();
for (intptr_t k = i + 1; k < merge_candidates->length(); k++) {
MathUnaryInstr* other_op = (*merge_candidates)[k];
diff --git a/runtime/vm/heap.cc b/runtime/vm/heap.cc
index aec0a7dc..4b31be8 100644
--- a/runtime/vm/heap.cc
+++ b/runtime/vm/heap.cc
@@ -253,6 +253,11 @@
RawObject* Heap::FindOldObject(FindObjectVisitor* visitor) const {
+ // Wait for any concurrent GC tasks to finish before walking.
+ MonitorLocker ml(old_space_->tasks_lock());
+ while (old_space_->tasks() > 0) {
+ ml.Wait();
+ }
return old_space_->FindObject(visitor, HeapPage::kData);
}
diff --git a/runtime/vm/intermediate_language.cc b/runtime/vm/intermediate_language.cc
index 4d1eb87..d024f38 100644
--- a/runtime/vm/intermediate_language.cc
+++ b/runtime/vm/intermediate_language.cc
@@ -1566,6 +1566,65 @@
}
+<<<<<<< .working
+static bool IsRepresentable(const Integer& value, Representation rep) {
+ switch (rep) {
+ case kTagged: // Smi case.
+ return value.IsSmi();
+
+ case kUnboxedInt32:
+ if (value.IsSmi() || value.IsMint()) {
+ return Utils::IsInt(32, value.AsInt64Value());
+ }
+ return false;
+
+ case kUnboxedMint:
+ return value.IsSmi() || value.IsMint();
+
+ case kUnboxedUint32: // Only truncating Uint32 arithmetic is supported.
+ default:
+ UNREACHABLE();
+ }
+
+ return false;
+}
+
+
+RawInteger* UnaryIntegerOpInstr::Evaluate(const Integer& value) const {
+ Integer& result = Integer::Handle();
+
+ switch (op_kind()) {
+ case Token::kNEGATE:
+ result = value.ArithmeticOp(Token::kMUL, Smi::Handle(Smi::New(-1)));
+ break;
+
+ case Token::kBIT_NOT:
+ if (value.IsSmi()) {
+ result = Integer::New(~Smi::Cast(value).Value());
+ } else if (value.IsMint()) {
+ result = Integer::New(~Mint::Cast(value).value());
+ }
+ break;
+
+ default:
+ UNREACHABLE();
+ }
+
+ if (!result.IsNull()) {
+ if (!IsRepresentable(result, representation())) {
+ // If this operation is not truncating it would deoptimize on overflow.
+ // Check that we match this behavior and don't produce a value that is
+ // larger than something this operation can produce. We could have
+ // specialized instructions that use this value under this assumption.
+ return Integer::null();
+ }
+ result ^= result.CheckAndCanonicalize(NULL);
+ }
+
+ return result.raw();
+}
+
+
RawInteger* BinaryIntegerOpInstr::Evaluate(const Integer& left,
const Integer& right) const {
Integer& result = Integer::Handle();
@@ -1607,6 +1666,13 @@
int64_t truncated = result.AsTruncatedInt64Value();
truncated &= RepresentationMask(representation());
result = Integer::New(truncated);
+ ASSERT(IsRepresentable(result, representation()));
+ } else if (!IsRepresentable(result, representation())) {
+ // If this operation is not truncating it would deoptimize on overflow.
+ // Check that we match this behavior and don't produce a value that is
+ // larger than something this operation can produce. We could have
+ // specialized instructions that use this value under this assumption.
+ return Integer::null();
}
result ^= result.CheckAndCanonicalize(NULL);
}
@@ -2279,22 +2345,48 @@
}
-// Recognize the pattern (a & b) == 0 where left is a bitwise and operation
-// and right is a constant 0.
-static bool RecognizeTestPattern(Value* left, Value* right) {
- if (!right->BindsToConstant()) {
+static bool BindsToGivenConstant(Value* v, intptr_t expected) {
+ return v->BindsToConstant() &&
+ v->BoundConstant().IsSmi() &&
+ (Smi::Cast(v->BoundConstant()).Value() == expected);
+}
+
+
+// Recognize patterns (a & b) == 0 and (a & 2^n) != 2^n.
+static bool RecognizeTestPattern(Value* left, Value* right, bool* negate) {
+ if (!right->BindsToConstant() || !right->BoundConstant().IsSmi()) {
return false;
}
- const Object& value = right->BoundConstant();
- if (!value.IsSmi() || (Smi::Cast(value).Value() != 0)) {
+ const intptr_t value = Smi::Cast(right->BoundConstant()).Value();
+ if ((value != 0) && !Utils::IsPowerOfTwo(value)) {
return false;
}
- Definition* left_defn = left->definition();
- return left_defn->IsBinarySmiOp() &&
- (left_defn->AsBinarySmiOp()->op_kind() == Token::kBIT_AND) &&
- left_defn->HasOnlyUse(left);
+
+ BinarySmiOpInstr* mask_op = left->definition()->AsBinarySmiOp();
+ if ((mask_op == NULL) ||
+ (mask_op->op_kind() != Token::kBIT_AND) ||
+ !mask_op->HasOnlyUse(left)) {
+ return false;
+ }
+
+ if (value == 0) {
+ // Recognized (a & b) == 0 pattern.
+ *negate = false;
+ return true;
+ }
+
+ // Recognize
+ if (BindsToGivenConstant(mask_op->left(), value) ||
+ BindsToGivenConstant(mask_op->right(), value)) {
+ // Recognized (a & 2^n) == 2^n pattern. It's equivalent to (a & 2^n) != 0
+ // so we need to negate original comparison.
+ *negate = true;
+ return true;
+ }
+
+ return false;
}
@@ -2342,10 +2434,14 @@
} else if (comparison()->IsEqualityCompare() &&
comparison()->operation_cid() == kSmiCid) {
BinarySmiOpInstr* bit_and = NULL;
- if (RecognizeTestPattern(comparison()->left(), comparison()->right())) {
+ bool negate = false;
+ if (RecognizeTestPattern(comparison()->left(),
+ comparison()->right(),
+ &negate)) {
bit_and = comparison()->left()->definition()->AsBinarySmiOp();
} else if (RecognizeTestPattern(comparison()->right(),
- comparison()->left())) {
+ comparison()->left(),
+ &negate)) {
bit_and = comparison()->right()->definition()->AsBinarySmiOp();
}
if (bit_and != NULL) {
@@ -2354,7 +2450,8 @@
}
TestSmiInstr* test = new TestSmiInstr(
comparison()->token_pos(),
- comparison()->kind(),
+ negate ? Token::NegateComparison(comparison()->kind())
+ : comparison()->kind(),
bit_and->left()->Copy(isolate),
bit_and->right()->Copy(isolate));
ASSERT(!CanDeoptimize());
@@ -3478,8 +3575,8 @@
intptr_t MergedMathInstr::OutputIndexOf(intptr_t kind) {
switch (kind) {
- case MethodRecognizer::kMathSin: return 1;
- case MethodRecognizer::kMathCos: return 0;
+ case MathUnaryInstr::kSin: return 1;
+ case MathUnaryInstr::kCos: return 0;
default: UNIMPLEMENTED(); return -1;
}
}
diff --git a/runtime/vm/intermediate_language.h b/runtime/vm/intermediate_language.h
index 4fad850..1e31675 100644
--- a/runtime/vm/intermediate_language.h
+++ b/runtime/vm/intermediate_language.h
@@ -6633,6 +6633,8 @@
virtual void PrintOperandsTo(BufferFormatter* f) const;
+ RawInteger* Evaluate(const Integer& value) const;
+
DEFINE_INSTRUCTION_TYPE_CHECK(UnaryIntegerOp)
private:
diff --git a/runtime/vm/intermediate_language_ia32.cc b/runtime/vm/intermediate_language_ia32.cc
index 615148a..d9e565a 100644
--- a/runtime/vm/intermediate_language_ia32.cc
+++ b/runtime/vm/intermediate_language_ia32.cc
@@ -5541,12 +5541,18 @@
}
if (kind() == MergedMathInstr::kSinCos) {
const intptr_t kNumInputs = 1;
- const intptr_t kNumTemps = 0;
+ const intptr_t kNumTemps = 2;
LocationSummary* summary = new(zone) LocationSummary(
- zone, kNumInputs, kNumTemps, LocationSummary::kNoCall);
- summary->set_in(0, Location::RequiresFpuRegister());
- summary->set_out(0, Location::Pair(Location::RequiresFpuRegister(),
- Location::RequiresFpuRegister()));
+ zone, kNumInputs, kNumTemps, LocationSummary::kCall);
+ // Because we always call into the runtime (LocationSummary::kCall) we
+ // must specify each input, temp, and output register explicitly.
+ summary->set_in(0, Location::FpuRegisterLocation(XMM1));
+ // EDI is chosen because it is callee saved so we do not need to back it
+ // up before calling into the runtime.
+ summary->set_temp(0, Location::RegisterLocation(EDI));
+ summary->set_temp(1, Location::RegisterLocation(EBX));
+ summary->set_out(0, Location::Pair(Location::FpuRegisterLocation(XMM2),
+ Location::FpuRegisterLocation(XMM3)));
return summary;
}
UNIMPLEMENTED();
@@ -5631,27 +5637,47 @@
}
if (kind() == MergedMathInstr::kSinCos) {
- XmmRegister in = locs()->in(0).fpu_reg();
ASSERT(locs()->out(0).IsPairLocation());
PairLocation* pair = locs()->out(0).AsPairLocation();
XmmRegister out1 = pair->At(0).fpu_reg();
XmmRegister out2 = pair->At(1).fpu_reg();
- // Do x87 sincos, since the ia32 compilers may not fuse sin/cos into
- // sincos.
- __ pushl(EAX);
- __ pushl(EAX);
- __ movsd(Address(ESP, 0), in);
- __ fldl(Address(ESP, 0));
- __ fsincos();
- __ fstpl(Address(ESP, 0));
- __ movsd(out1, Address(ESP, 0));
- __ fstpl(Address(ESP, 0));
- __ movsd(out2, Address(ESP, 0));
- __ addl(ESP, Immediate(2 * kWordSize));
+ // Save ESP.
+ __ movl(locs()->temp(0).reg(), ESP);
+ // +-------------------------------+
+ // | double-argument | <- TOS
+ // +-------------------------------+
+ // | address-cos-result | +8
+ // +-------------------------------+
+ // | address-sin-result | +12
+ // +-------------------------------+
+ // | double-storage-for-cos-result | +16
+ // +-------------------------------+
+ // | double-storage-for-sin-result | +24
+ // +-------------------------------+
+ // ....
+ __ ReserveAlignedFrameSpace(kDoubleSize * 3 + kWordSize * 2);
+ __ movsd(Address(ESP, 0), locs()->in(0).fpu_reg());
+
+ Address cos_result(ESP, 2 * kWordSize + kDoubleSize);
+ Address sin_result(ESP, 2 * kWordSize + 2 * kDoubleSize);
+
+ // 'cos' result storage address.
+ __ leal(locs()->temp(1).reg(), cos_result);
+ __ movl(Address(ESP, kDoubleSize), locs()->temp(1).reg());
+
+ // 'sin' result storage address.
+ __ leal(locs()->temp(1).reg(), sin_result);
+ __ movl(Address(ESP, kDoubleSize + kWordSize), locs()->temp(1).reg());
+
+ __ CallRuntime(kSinCosRuntimeEntry, InputCount());
+ __ movsd(out2, sin_result); // sin.
+ __ movsd(out1, cos_result); // cos.
+ // Restore RSP.
+ __ movl(ESP, locs()->temp(0).reg());
+
return;
}
-
UNIMPLEMENTED();
}
diff --git a/runtime/vm/isolate.cc b/runtime/vm/isolate.cc
index 88c3726..f908b26 100644
--- a/runtime/vm/isolate.cc
+++ b/runtime/vm/isolate.cc
@@ -25,6 +25,7 @@
#include "vm/profiler.h"
#include "vm/reusable_handles.h"
#include "vm/service.h"
+#include "vm/service_isolate.h"
#include "vm/simulator.h"
#include "vm/stack_frame.h"
#include "vm/stub_code.h"
@@ -623,7 +624,7 @@
}
-Isolate* Isolate::Init(const char* name_prefix) {
+Isolate* Isolate::Init(const char* name_prefix, bool is_vm_isolate) {
Isolate* result = new Isolate();
ASSERT(result != NULL);
@@ -653,11 +654,11 @@
ASSERT(state != NULL);
result->set_api_state(state);
- // Initialize stack top and limit in case we are running the isolate in the
- // main thread.
- // TODO(5411455): Need to figure out how to set the stack limit for the
- // main thread.
- result->SetStackLimitFromStackBase(reinterpret_cast<uword>(&result));
+ // Initialize stack limit (wait until later for the VM isolate, since the
+ // needed GetStackPointer stub has not yet been generated in that case).
+ if (!is_vm_isolate) {
+ result->InitializeStackLimit();
+ }
result->set_main_port(PortMap::CreatePort(result->message_handler()));
#if defined(DEBUG)
// Verify that we are never reusing a live origin id.
@@ -686,12 +687,39 @@
}
+void Isolate::InitializeStackLimit() {
+ SetStackLimitFromStackBase(Isolate::GetCurrentStackPointer());
+}
+
+
+/* static */
+uword Isolate::GetCurrentStackPointer() {
+ // Since AddressSanitizer's detect_stack_use_after_return instruments the
+ // C++ code to give out fake stack addresses, we call a stub in that case.
+ uword (*func)() =
+ reinterpret_cast<uword (*)()>(StubCode::GetStackPointerEntryPoint());
+ // But for performance (and to support simulators), we normally use a local.
+#if defined(__has_feature)
+#if __has_feature(address_sanitizer)
+ uword current_sp = func();
+ return current_sp;
+#else
+ uword stack_allocated_local_address = reinterpret_cast<uword>(&func);
+ return stack_allocated_local_address;
+#endif
+#else
+ uword stack_allocated_local_address = reinterpret_cast<uword>(&func);
+ return stack_allocated_local_address;
+#endif
+}
+
+
void Isolate::BuildName(const char* name_prefix) {
ASSERT(name_ == NULL);
if (name_prefix == NULL) {
name_prefix = "isolate";
}
- if (Service::IsServiceIsolateName(name_prefix)) {
+ if (ServiceIsolate::NameEquals(name_prefix)) {
name_ = strdup(name_prefix);
return;
}
@@ -810,7 +838,7 @@
// Set the isolate as runnable and if we are being spawned schedule
// isolate on thread pool for execution.
is_runnable_ = true;
- if (!Service::IsServiceIsolate(this)) {
+ if (!ServiceIsolate::IsServiceIsolate(this)) {
message_handler()->set_pause_on_start(FLAG_pause_isolates_on_start);
message_handler()->set_pause_on_exit(FLAG_pause_isolates_on_exit);
}
diff --git a/runtime/vm/isolate.h b/runtime/vm/isolate.h
index 1b92b93..c6bfef0 100644
--- a/runtime/vm/isolate.h
+++ b/runtime/vm/isolate.h
@@ -123,7 +123,7 @@
static void SetCurrent(Isolate* isolate);
static void InitOnce();
- static Isolate* Init(const char* name_prefix);
+ static Isolate* Init(const char* name_prefix, bool is_vm_isolate = false);
void Shutdown();
Isolate* ShallowCopy();
@@ -248,10 +248,15 @@
library_tag_handler_ = value;
}
+ void InitializeStackLimit();
void SetStackLimit(uword value);
void SetStackLimitFromStackBase(uword stack_base);
void ClearStackLimit();
+ // Returns the current C++ stack pointer. Equivalent taking the address of a
+ // stack allocated local, but plays well with AddressSanitizer.
+ static uword GetCurrentStackPointer();
+
uword stack_limit_address() const {
return reinterpret_cast<uword>(&stack_limit_);
}
@@ -775,7 +780,7 @@
REUSABLE_HANDLE_LIST(REUSABLE_FRIEND_DECLARATION)
#undef REUSABLE_FRIEND_DECLARATION
- friend class Service;
+ friend class ServiceIsolate;
DISALLOW_COPY_AND_ASSIGN(Isolate);
};
@@ -794,7 +799,8 @@
if (saved_isolate_ != new_isolate_) {
ASSERT(Isolate::Current() == NULL);
Isolate::SetCurrent(new_isolate_);
- new_isolate_->SetStackLimitFromStackBase(reinterpret_cast<uword>(this));
+ new_isolate_->SetStackLimitFromStackBase(
+ Isolate::GetCurrentStackPointer());
}
}
diff --git a/runtime/vm/longjump.cc b/runtime/vm/longjump.cc
index 791fab1..811cc61 100644
--- a/runtime/vm/longjump.cc
+++ b/runtime/vm/longjump.cc
@@ -26,7 +26,7 @@
// We do not want to jump past Dart frames. Note that this code
// assumes the stack grows from high to low.
Isolate* isolate = Isolate::Current();
- uword jumpbuf_addr = reinterpret_cast<uword>(this);
+ uword jumpbuf_addr = Isolate::GetCurrentStackPointer();
#if defined(USING_SIMULATOR)
uword top_exit_frame_info = isolate->simulator()->top_exit_frame_info();
#else
@@ -55,11 +55,8 @@
isolate->object_store()->set_sticky_error(error);
// Destruct all the active StackResource objects.
- StackResource* current_resource = isolate->top_resource();
- while (current_resource != top_) {
- current_resource->~StackResource();
- current_resource = isolate->top_resource();
- }
+ StackResource::UnwindAbove(isolate, top_);
+>>>>>>> .merge-right.r43886
longjmp(environment_, value);
UNREACHABLE();
}
diff --git a/runtime/vm/message_handler.cc b/runtime/vm/message_handler.cc
index 4a5ad31..6ca2fb1 100644
--- a/runtime/vm/message_handler.cc
+++ b/runtime/vm/message_handler.cc
@@ -157,13 +157,15 @@
// The monitor was acquired in MessageHandler::TaskCallback().
monitor_.Exit();
Message::Priority saved_priority = message->priority();
+ Dart_Port saved_dest_port = message->dest_port();
result = HandleMessage(message);
+ message = NULL; // May be deleted by now.
monitor_.Enter();
if (FLAG_trace_isolates) {
OS::Print("[.] Message handled:\n"
"\thandler: %s\n"
"\tport: %" Pd64 "\n",
- name(), message->dest_port());
+ name(), saved_dest_port);
}
if (!result) {
// If we hit an error, we're done processing messages.
diff --git a/runtime/vm/object.cc b/runtime/vm/object.cc
index f51342d..b706fdd 100644
--- a/runtime/vm/object.cc
+++ b/runtime/vm/object.cc
@@ -1084,7 +1084,7 @@
const Class& stacktrace_cls = Class::Handle(isolate,
Class::New<Stacktrace>());
- RegisterClass(stacktrace_cls, Symbols::StackTrace(), core_lib);
+ RegisterPrivateClass(stacktrace_cls, Symbols::_StackTrace(), core_lib);
pending_classes.Add(stacktrace_cls);
// Super type set below, after Object is allocated.
@@ -1421,7 +1421,7 @@
#define ADD_SET_FIELD(clazz) \
field_name = Symbols::New("cid"#clazz); \
- field = Field::New(field_name, true, false, true, false, cls, 0); \
+ field = Field::New(field_name, true, false, true, true, cls, 0); \
value = Smi::New(k##clazz##Cid); \
field.set_value(value); \
field.set_type(Type::Handle(Type::IntType())); \
@@ -3058,6 +3058,7 @@
cls.set_num_native_fields(field_count);
cls.set_is_finalized();
cls.set_is_type_finalized();
+ cls.set_is_synthesized_class();
library.AddClass(cls);
return cls.raw();
} else {
@@ -6818,6 +6819,46 @@
}
+RawGrowableObjectArray* Function::CollectICsWithSourcePositions() const {
+ ZoneGrowableArray<const ICData*>* ic_data_array =
+ new ZoneGrowableArray<const ICData*>();
+ RestoreICDataMap(ic_data_array);
+ const Code& code = Code::Handle(unoptimized_code());
+ const PcDescriptors& descriptors = PcDescriptors::Handle(
+ code.pc_descriptors());
+
+ const intptr_t begin_pos = token_pos();
+ const intptr_t end_pos = end_token_pos();
+
+ const Script& script = Script::Handle(this->script());
+ const GrowableObjectArray& result =
+ GrowableObjectArray::Handle(GrowableObjectArray::New());
+
+ PcDescriptors::Iterator iter(descriptors,
+ RawPcDescriptors::kIcCall | RawPcDescriptors::kUnoptStaticCall);
+ while (iter.MoveNext()) {
+ const ICData* ic_data = (*ic_data_array)[iter.DeoptId()];
+ if (!ic_data->IsNull()) {
+ const intptr_t token_pos = iter.TokenPos();
+ // Filter out descriptors that do not map to tokens in the source code.
+ if ((token_pos < begin_pos) || (token_pos > end_pos)) {
+ continue;
+ }
+
+ intptr_t line = -1;
+ intptr_t column = -1;
+ script.GetTokenLocation(token_pos, &line, &column);
+
+ result.Add(*ic_data);
+ result.Add(Smi::Handle(Smi::New(line)));
+ result.Add(Smi::Handle(Smi::New(column)));
+ }
+ }
+
+ return result.raw();
+}
+
+
void ClosureData::set_context_scope(const ContextScope& value) const {
StorePointer(&raw_ptr()->context_scope_, value.raw());
}
@@ -11833,6 +11874,31 @@
}
+void ICData::PrintToJSONArray(JSONArray* jsarray,
+ intptr_t line,
+ intptr_t column) const {
+ Isolate* isolate = Isolate::Current();
+ Class& cls = Class::Handle();
+
+ JSONObject jsobj(jsarray);
+ jsobj.AddProperty("name", String::Handle(target_name()).ToCString());
+ jsobj.AddProperty("line", line);
+ jsobj.AddProperty("column", column);
+ // TODO(rmacnak): Figure out how to stringify DeoptReasons().
+ // jsobj.AddProperty("deoptReasons", ...);
+
+ JSONArray cache_entries(&jsobj, "cacheEntries");
+ for (intptr_t i = 0; i < NumberOfChecks(); i++) {
+ intptr_t cid = GetReceiverClassIdAt(i);
+ cls ^= isolate->class_table()->At(cid);
+ intptr_t count = GetCountAt(i);
+ JSONObject cache_entry(&cache_entries);
+ cache_entry.AddProperty("receiverClass", cls);
+ cache_entry.AddProperty("count", count);
+ }
+}
+
+
static Token::Kind RecognizeArithmeticOp(const String& name) {
ASSERT(name.IsSymbol());
if (name.raw() == Symbols::Plus().raw()) {
@@ -13260,7 +13326,7 @@
RawUnhandledException* UnhandledException::New(const Instance& exception,
- const Stacktrace& stacktrace,
+ const Instance& stacktrace,
Heap::Space space) {
ASSERT(Object::unhandled_exception_class() != Class::null());
UnhandledException& result = UnhandledException::Handle();
@@ -13298,7 +13364,7 @@
}
-void UnhandledException::set_stacktrace(const Stacktrace& stacktrace) const {
+void UnhandledException::set_stacktrace(const Instance& stacktrace) const {
StorePointer(&raw_ptr()->stacktrace_, stacktrace.raw());
}
@@ -19113,9 +19179,18 @@
uword new_tags = RawObject::SizeTag::update(used_size, old_tags);
tags = array.CompareAndSwapTags(old_tags, new_tags);
} while (tags != old_tags);
+ // TODO(22501): For the heap to remain walkable by the sweeper, it must
+ // observe the creation of the filler object no later than the new length
+ // of the array. This assumption holds on ia32/x64 or if the CAS above is a
+ // full memory barrier.
+ //
+ // Also, between the CAS of the header above and the SetLength below,
+ // the array is temporarily in an inconsistent state. The header is considered
+ // the overriding source of object size by RawObject::Size, but the ASSERTs
+ // in RawObject::SizeFromClass must handle this special case.
array.SetLength(used_len);
- // Null the GrowableObjectArray, we are removing it's backing array.
+ // Null the GrowableObjectArray, we are removing its backing array.
growable_array.SetLength(0);
growable_array.SetData(Object::empty_array());
@@ -20045,16 +20120,6 @@
}
-void Stacktrace::set_catch_code_array(const Array& code_array) const {
- StorePointer(&raw_ptr()->catch_code_array_, code_array.raw());
-}
-
-
-void Stacktrace::set_catch_pc_offset_array(const Array& pc_offset_array) const {
- StorePointer(&raw_ptr()->catch_pc_offset_array_, pc_offset_array.raw());
-}
-
-
void Stacktrace::set_expand_inlined(bool value) const {
StoreNonPointer(&raw_ptr()->expand_inlined_, value);
}
@@ -20078,68 +20143,13 @@
}
result.set_code_array(code_array);
result.set_pc_offset_array(pc_offset_array);
- result.SetCatchStacktrace(Object::empty_array(),
- Object::empty_array());
result.set_expand_inlined(true); // default.
return result.raw();
}
-void Stacktrace::Append(const Array& code_list,
- const Array& pc_offset_list,
- const intptr_t start_index) const {
- ASSERT(start_index <= code_list.Length());
- ASSERT(pc_offset_list.Length() == code_list.Length());
- intptr_t old_length = Length();
- intptr_t new_length = old_length + pc_offset_list.Length() - start_index;
- if (new_length == old_length) {
- // Nothing to append. Avoid work and an assert that growing arrays always
- // increases their size.
- return;
- }
-
- // Grow the arrays for code, pc_offset pairs to accommodate the new stack
- // frames.
- Isolate* isolate = Isolate::Current();
- Array& code_array = Array::Handle(isolate, raw_ptr()->code_array_);
- Array& pc_offset_array = Array::Handle(isolate, raw_ptr()->pc_offset_array_);
- code_array = Array::Grow(code_array, new_length);
- pc_offset_array = Array::Grow(pc_offset_array, new_length);
- set_code_array(code_array);
- set_pc_offset_array(pc_offset_array);
- // Now append the new function and code list to the existing arrays.
- intptr_t j = start_index;
- PassiveObject& obj = PassiveObject::Handle(isolate);
- for (intptr_t i = old_length; i < new_length; i++, j++) {
- obj = code_list.At(j);
- code_array.SetAt(i, obj);
- obj = pc_offset_list.At(j);
- pc_offset_array.SetAt(i, obj);
- }
-}
-
-
-void Stacktrace::SetCatchStacktrace(const Array& code_array,
- const Array& pc_offset_array) const {
- StorePointer(&raw_ptr()->catch_code_array_, code_array.raw());
- StorePointer(&raw_ptr()->catch_pc_offset_array_, pc_offset_array.raw());
-}
-
-
RawString* Stacktrace::FullStacktrace() const {
- const Array& code_array = Array::Handle(raw_ptr()->catch_code_array_);
intptr_t idx = 0;
- if (!code_array.IsNull() && (code_array.Length() > 0)) {
- const Array& pc_offset_array =
- Array::Handle(raw_ptr()->catch_pc_offset_array_);
- const Stacktrace& catch_trace = Stacktrace::Handle(
- Stacktrace::New(code_array, pc_offset_array));
- const String& throw_string =
- String::Handle(String::New(ToCStringInternal(&idx)));
- const String& catch_string =
- String::Handle(String::New(catch_trace.ToCStringInternal(&idx)));
- return String::Concat(throw_string, catch_string);
- }
return String::New(ToCStringInternal(&idx));
}
diff --git a/runtime/vm/object.h b/runtime/vm/object.h
index 254ec19..f4d67360 100644
--- a/runtime/vm/object.h
+++ b/runtime/vm/object.h
@@ -1807,6 +1807,8 @@
}
bool HasCode() const;
+ RawGrowableObjectArray* CollectICsWithSourcePositions() const;
+
static intptr_t instructions_offset() {
return OFFSET_OF(RawFunction, instructions_);
}
@@ -3872,6 +3874,10 @@
bool HasRangeFeedback() const;
RangeFeedback DecodeRangeFeedbackAt(intptr_t idx) const;
+ void PrintToJSONArray(JSONArray* jsarray,
+ intptr_t line,
+ intptr_t column) const;
+
private:
RawArray* ic_data() const {
return raw_ptr()->ic_data_;
@@ -4584,7 +4590,7 @@
return OFFSET_OF(RawUnhandledException, exception_);
}
- RawStacktrace* stacktrace() const { return raw_ptr()->stacktrace_; }
+ RawInstance* stacktrace() const { return raw_ptr()->stacktrace_; }
static intptr_t stacktrace_offset() {
return OFFSET_OF(RawUnhandledException, stacktrace_);
}
@@ -4594,7 +4600,7 @@
}
static RawUnhandledException* New(const Instance& exception,
- const Stacktrace& stacktrace,
+ const Instance& stacktrace,
Heap::Space space = Heap::kNew);
virtual const char* ToErrorCString() const;
@@ -4603,7 +4609,7 @@
static RawUnhandledException* New(Heap::Space space = Heap::kNew);
void set_exception(const Instance& exception) const;
- void set_stacktrace(const Stacktrace& stacktrace) const;
+ void set_stacktrace(const Instance& stacktrace) const;
FINAL_HEAP_OBJECT_IMPLEMENTATION(UnhandledException, Error);
friend class Class;
@@ -7371,7 +7377,7 @@
// Internal stacktrace object used in exceptions for printing stack traces.
class Stacktrace : public Instance {
public:
- static const int kPreallocatedStackdepth = 10;
+ static const int kPreallocatedStackdepth = 30;
intptr_t Length() const;
@@ -7382,14 +7388,8 @@
RawSmi* PcOffsetAtFrame(intptr_t frame_index) const;
void SetPcOffsetAtFrame(intptr_t frame_index, const Smi& pc_offset) const;
- void SetCatchStacktrace(const Array& code_array,
- const Array& pc_offset_array) const;
void set_expand_inlined(bool value) const;
- void Append(const Array& code_list,
- const Array& pc_offset_list,
- const intptr_t start_index) const;
-
static intptr_t InstanceSize() {
return RoundedAllocationSize(sizeof(RawStacktrace));
}
@@ -7406,8 +7406,6 @@
private:
void set_code_array(const Array& code_array) const;
void set_pc_offset_array(const Array& pc_offset_array) const;
- void set_catch_code_array(const Array& code_array) const;
- void set_catch_pc_offset_array(const Array& pc_offset_array) const;
bool expand_inlined() const;
FINAL_HEAP_OBJECT_IMPLEMENTATION(Stacktrace, Instance);
diff --git a/runtime/vm/object_store.cc b/runtime/vm/object_store.cc
index 45759d9..985f0b5 100644
--- a/runtime/vm/object_store.cc
+++ b/runtime/vm/object_store.cc
@@ -154,14 +154,12 @@
Stacktrace::Handle(isolate)));
set_preallocated_unhandled_exception(unhandled_exception);
- const Array& code_array = Array::Handle(
- isolate,
+ const Array& code_array = Array::Handle(isolate,
Array::New(Stacktrace::kPreallocatedStackdepth, Heap::kOld));
- const Array& pc_offset_array = Array::Handle(
- isolate,
+ const Array& pc_offset_array = Array::Handle(isolate,
Array::New(Stacktrace::kPreallocatedStackdepth, Heap::kOld));
- const Stacktrace& stack_trace =
- Stacktrace::Handle(Stacktrace::New(code_array, pc_offset_array));
+ const Stacktrace& stack_trace = Stacktrace::Handle(isolate,
+ Stacktrace::New(code_array, pc_offset_array));
// Expansion of inlined functions requires additional memory at run time,
// avoid it.
stack_trace.set_expand_inlined(false);
diff --git a/runtime/vm/pages.cc b/runtime/vm/pages.cc
index a352273..25039a2 100644
--- a/runtime/vm/pages.cc
+++ b/runtime/vm/pages.cc
@@ -499,7 +499,9 @@
void PageSpace::MakeIterable() const {
- // TODO(koda): Assert not called from concurrent sweeper task.
+ // Assert not called from concurrent sweeper task.
+ // TODO(koda): Use thread/task identity when implemented.
+ ASSERT(Isolate::Current()->heap() != NULL);
if (bump_top_ < bump_end_) {
FreeListElement::AsElement(bump_top_, bump_end_ - bump_top_);
}
diff --git a/runtime/vm/parser.cc b/runtime/vm/parser.cc
index a1c8aa7..2de53d4 100644
--- a/runtime/vm/parser.cc
+++ b/runtime/vm/parser.cc
@@ -69,7 +69,11 @@
#if defined(DEBUG)
class TraceParser : public ValueObject {
public:
- TraceParser(intptr_t token_pos, const Script& script, const char* msg) {
+ TraceParser(intptr_t token_pos,
+ const Script& script,
+ intptr_t* trace_indent,
+ const char* msg) {
+ indent_ = trace_indent;
if (FLAG_trace_parser) {
// Skips tracing of bootstrap libraries.
if (script.HasSource()) {
@@ -79,21 +83,26 @@
OS::Print("%s (line %" Pd ", col %" Pd ", token %" Pd ")\n",
msg, line, column, token_pos);
}
- indent_++;
+ (*indent_)++;
}
}
- ~TraceParser() { indent_--; }
+ ~TraceParser() {
+ if (FLAG_trace_parser) {
+ (*indent_)--;
+ ASSERT(*indent_ >= 0);
+ }
+ }
+
private:
void PrintIndent() {
- for (int i = 0; i < indent_; i++) { OS::Print(". "); }
+ for (intptr_t i = 0; i < *indent_; i++) { OS::Print(". "); }
}
- static int indent_;
+ intptr_t* indent_;
};
-int TraceParser::indent_ = 0;
#define TRACE_PARSER(s) \
- TraceParser __p__(this->TokenPos(), this->script_, s)
+ TraceParser __p__(this->TokenPos(), this->script_, &this->trace_indent_, s)
#else // not DEBUG
#define TRACE_PARSER(s)
@@ -326,7 +335,8 @@
try_blocks_list_(NULL),
last_used_try_index_(0),
unregister_pending_function_(false),
- async_temp_scope_(NULL) {
+ async_temp_scope_(NULL),
+ trace_indent_(0) {
ASSERT(tokens_iterator_.IsValid());
ASSERT(!library.IsNull());
}
@@ -358,7 +368,8 @@
try_blocks_list_(NULL),
last_used_try_index_(0),
unregister_pending_function_(false),
- async_temp_scope_(NULL) {
+ async_temp_scope_(NULL),
+ trace_indent_(0) {
ASSERT(tokens_iterator_.IsValid());
ASSERT(!current_function().IsNull());
EnsureExpressionTemp();
@@ -4158,8 +4169,10 @@
const Class& toplevel_class,
intptr_t metadata_pos) {
TRACE_PARSER("ParseEnumDeclaration");
+ const intptr_t declaration_pos = (metadata_pos > 0) ? metadata_pos
+ : TokenPos();
ConsumeToken();
- const intptr_t enum_pos = TokenPos();
+ const intptr_t name_pos = TokenPos();
String* enum_name =
ExpectUserDefinedTypeIdentifier("enum type name expected");
if (FLAG_trace_parser) {
@@ -4186,10 +4199,10 @@
Object& obj = Object::Handle(Z, library_.LookupLocalObject(*enum_name));
if (!obj.IsNull()) {
- ReportError(enum_pos, "'%s' is already defined", enum_name->ToCString());
+ ReportError(name_pos, "'%s' is already defined", enum_name->ToCString());
}
Class& cls = Class::Handle(Z);
- cls = Class::New(*enum_name, script_, enum_pos);
+ cls = Class::New(*enum_name, script_, declaration_pos);
cls.set_library(library_);
library_.AddClass(cls);
cls.set_is_synthesized_class();
@@ -4208,6 +4221,7 @@
TRACE_PARSER("ParseClassDeclaration");
bool is_patch = false;
bool is_abstract = false;
+ intptr_t declaration_pos = (metadata_pos > 0) ? metadata_pos : TokenPos();
if (is_patch_source() &&
(CurrentToken() == Token::kIDENT) &&
CurrentLiteral()->Equals("patch")) {
@@ -4231,7 +4245,7 @@
ReportError(classname_pos, "missing class '%s' cannot be patched",
class_name.ToCString());
}
- cls = Class::New(class_name, script_, classname_pos);
+ cls = Class::New(class_name, script_, declaration_pos);
library_.AddClass(cls);
} else {
if (!obj.IsClass()) {
@@ -4247,7 +4261,7 @@
// otherwise the generic signature classes it defines will not match the
// patched generic signature classes. Therefore, new signature classes
// will be introduced and the original ones will not get finalized.
- cls = Class::New(class_name, script_, classname_pos);
+ cls = Class::New(class_name, script_, declaration_pos);
cls.set_library(library_);
} else {
// Not patching a class, but it has been found. This must be one of the
@@ -4259,7 +4273,7 @@
}
// Pre-registered classes need their scripts connected at this time.
cls.set_script(script_);
- cls.set_token_pos(classname_pos);
+ cls.set_token_pos(declaration_pos);
}
}
ASSERT(!cls.IsNull());
@@ -4399,6 +4413,15 @@
set_current_class(cls);
is_top_level_ = true;
String& class_name = String::Handle(Z, cls.Name());
+ SkipMetadata();
+ if (is_patch_source() &&
+ (CurrentToken() == Token::kIDENT) &&
+ CurrentLiteral()->Equals("patch")) {
+ ConsumeToken();
+ } else if (CurrentToken() == Token::kABSTRACT) {
+ ConsumeToken();
+ }
+ ExpectToken(Token::kCLASS);
const intptr_t class_pos = TokenPos();
ClassDesc members(cls, class_name, false, class_pos);
while (CurrentToken() != Token::kLBRACE) {
@@ -4448,6 +4471,9 @@
TRACE_PARSER("ParseEnumDefinition");
CompilerStats::num_classes_compiled++;
+ SkipMetadata();
+ ExpectToken(Token::kENUM);
+
const String& enum_name = String::Handle(Z, cls.Name());
ClassDesc enum_members(cls, enum_name, false, cls.token_pos());
@@ -4784,6 +4810,7 @@
const Class& toplevel_class,
intptr_t metadata_pos) {
TRACE_PARSER("ParseTypedef");
+ intptr_t declaration_pos = (metadata_pos > 0) ? metadata_pos : TokenPos();
ExpectToken(Token::kTYPEDEF);
if (IsMixinAppAlias()) {
@@ -4826,7 +4853,7 @@
Class::NewSignatureClass(*alias_name,
Function::Handle(Z),
script_,
- alias_name_pos));
+ declaration_pos));
library_.AddClass(function_type_alias);
set_current_class(function_type_alias);
// Parse the type parameters of the function type.
@@ -4993,6 +5020,8 @@
ConsumeToken();
const intptr_t metadata_pos = SkipMetadata();
const intptr_t type_parameter_pos = TokenPos();
+ const intptr_t declaration_pos = (metadata_pos > 0) ? metadata_pos
+ : type_parameter_pos;
String& type_parameter_name =
*ExpectUserDefinedTypeIdentifier("type parameter expected");
// Check for duplicate type parameters.
@@ -5018,7 +5047,7 @@
index,
type_parameter_name,
type_parameter_bound,
- type_parameter_pos);
+ declaration_pos);
type_parameters_array.Add(type_parameter);
if (metadata_pos >= 0) {
library_.AddTypeParameterMetadata(type_parameter, metadata_pos);
@@ -5944,36 +5973,37 @@
LocalVariable* context_var = current_block_->scope->LookupVariable(
Symbols::SavedTryContextVar(), false);
ASSERT(context_var != NULL);
+
LocalVariable* exception_var = current_block_->scope->LookupVariable(
Symbols::ExceptionVar(), false);
+ ASSERT(exception_var != NULL);
if (exception_param.var != NULL) {
// Generate code to load the exception object (:exception_var) into
// the exception variable specified in this block.
- ASSERT(exception_var != NULL);
current_block_->statements->Add(new(Z) StoreLocalNode(
Scanner::kNoSourcePos,
exception_param.var,
new(Z) LoadLocalNode(Scanner::kNoSourcePos, exception_var)));
}
+
LocalVariable* stack_trace_var =
current_block_->scope->LookupVariable(Symbols::StackTraceVar(), false);
+ ASSERT(stack_trace_var != NULL);
if (stack_trace_param.var != NULL) {
// A stack trace variable is specified in this block, so generate code
// to load the stack trace object (:stack_trace_var) into the stack
// trace variable specified in this block.
- ArgumentListNode* no_args = new(Z) ArgumentListNode(Scanner::kNoSourcePos);
- ASSERT(stack_trace_var != NULL);
+ current_block_->statements->Add(new(Z) StoreLocalNode(
+>>>>>>> .merge-right.r43886
current_block_->statements->Add(new(Z) StoreLocalNode(
Scanner::kNoSourcePos,
stack_trace_param.var,
new(Z) LoadLocalNode(Scanner::kNoSourcePos, stack_trace_var)));
- current_block_->statements->Add(new(Z) InstanceCallNode(
- Scanner::kNoSourcePos,
- new(Z) LoadLocalNode(Scanner::kNoSourcePos, stack_trace_param.var),
- Library::PrivateCoreLibName(Symbols::_setupFullStackTrace()),
- no_args));
}
+ AddSavedExceptionAndStacktraceToScope(
+ exception_var, stack_trace_var, current_block_->scope);
+
ASSERT(try_blocks_list_ != NULL);
ASSERT(innermost_function().IsAsyncClosure() ||
innermost_function().IsAsyncFunction());
@@ -6659,16 +6689,18 @@
ASSERT(IsIdentifier());
const intptr_t ident_pos = TokenPos();
const String& ident = *CurrentLiteral();
- LocalVariable* variable = new(Z) LocalVariable(
- ident_pos, ident, type);
ConsumeToken(); // Variable identifier.
+ const intptr_t assign_pos = TokenPos();
AstNode* initialization = NULL;
+ LocalVariable* variable = NULL;
if (CurrentToken() == Token::kASSIGN) {
// Variable initialization.
- const intptr_t assign_pos = TokenPos();
ConsumeToken();
AstNode* expr = ParseAwaitableExpr(
is_const, kConsumeCascades, await_preamble);
+ const intptr_t expr_end_pos = TokenPos();
+ variable = new(Z) LocalVariable(
+ expr_end_pos, ident, type);
initialization = new(Z) StoreLocalNode(
assign_pos, variable, expr);
if (is_const) {
@@ -6680,6 +6712,8 @@
"missing initialization of 'final' or 'const' variable");
} else {
// Initialize variable with null.
+ variable = new(Z) LocalVariable(
+ assign_pos, ident, type);
AstNode* null_expr = new(Z) LiteralNode(ident_pos, Instance::ZoneHandle(Z));
initialization = new(Z) StoreLocalNode(
ident_pos, variable, null_expr);
@@ -6687,7 +6721,7 @@
ASSERT(current_block_ != NULL);
const intptr_t previous_pos =
- current_block_->scope->PreviousReferencePos(ident);
+ current_block_->scope->PreviousReferencePos(ident);
if (previous_pos >= 0) {
ASSERT(!script_.IsNull());
if (previous_pos > ident_pos) {
@@ -8176,15 +8210,65 @@
var->set_is_final();
bool added_to_scope = scope->AddVariable(var);
if (!added_to_scope) {
+ // The name of the exception param is reused for the stack trace param.
ReportError(stack_trace_param->token_pos,
"name '%s' already exists in scope",
stack_trace_param->name->ToCString());
- }
+ }
stack_trace_param->var = var;
}
}
+// Populate local scope of the catch block with the saved exception and saved
+// stack trace.
+void Parser::AddSavedExceptionAndStacktraceToScope(
+ LocalVariable* exception_var,
+ LocalVariable* stack_trace_var,
+ LocalScope* scope) {
+ ASSERT(innermost_function().IsAsyncClosure() ||
+ innermost_function().IsAsyncFunction() ||
+ innermost_function().IsSyncGenClosure() ||
+ innermost_function().IsSyncGenerator());
+ // Add :saved_exception_var and :saved_stack_trace_var to scope.
+ // They will automatically get captured.
+ LocalVariable* saved_exception_var = new (Z) LocalVariable(
+ Scanner::kNoSourcePos,
+ Symbols::SavedExceptionVar(),
+ Type::ZoneHandle(Z, Type::DynamicType()));
+ saved_exception_var->set_is_final();
+ scope->AddVariable(saved_exception_var);
+ LocalVariable* saved_stack_trace_var = new (Z) LocalVariable(
+ Scanner::kNoSourcePos,
+ Symbols::SavedStackTraceVar(),
+ Type::ZoneHandle(Z, Type::DynamicType()));
+ saved_exception_var->set_is_final();
+ scope->AddVariable(saved_stack_trace_var);
+
+ // Generate code to load the exception object (:exception_var) into
+ // the saved exception variable (:saved_exception_var) used to rethrow.
+ saved_exception_var = current_block_->scope->LookupVariable(
+ Symbols::SavedExceptionVar(), false);
+ ASSERT(saved_exception_var != NULL);
+ ASSERT(exception_var != NULL);
+ current_block_->statements->Add(new(Z) StoreLocalNode(
+ Scanner::kNoSourcePos,
+ saved_exception_var,
+ new(Z) LoadLocalNode(Scanner::kNoSourcePos, exception_var)));
+
+ // Generate code to load the stack trace object (:stack_trace_var) into
+ // the saved stacktrace variable (:saved_stack_trace_var) used to rethrow.
+ saved_stack_trace_var = current_block_->scope->LookupVariable(
+ Symbols::SavedStackTraceVar(), false);
+ ASSERT(saved_stack_trace_var != NULL);
+ ASSERT(stack_trace_var != NULL);
+ current_block_->statements->Add(new(Z) StoreLocalNode(
+ Scanner::kNoSourcePos,
+ saved_stack_trace_var,
+ new(Z) LoadLocalNode(Scanner::kNoSourcePos, stack_trace_var)));
+}
+
+
SequenceNode* Parser::ParseFinallyBlock() {
TRACE_PARSER("ParseFinallyBlock");
OpenBlock();
@@ -8318,7 +8402,9 @@
// following code:
// 1) Store exception object and stack trace object into user-defined
// variables (as needed).
- // 2) Nested block with source code from catch clause block.
+ // 2) In async code, save exception object and stack trace object into
+ // captured :saved_exception_var and :saved_stack_trace_var.
+ // 3) Nested block with source code from catch clause block.
OpenBlock();
AddCatchParamsToScope(&exception_param, &stack_trace_param,
current_block_->scope);
@@ -8336,16 +8422,10 @@
// to load the stack trace object (:stack_trace_var) into the stack
// trace variable specified in this block.
*needs_stack_trace = true;
- ArgumentListNode* no_args = new(Z) ArgumentListNode(catch_pos);
ASSERT(stack_trace_var != NULL);
current_block_->statements->Add(new(Z) StoreLocalNode(
catch_pos, stack_trace_param.var, new(Z) LoadLocalNode(
catch_pos, stack_trace_var)));
- current_block_->statements->Add(new(Z) InstanceCallNode(
- catch_pos,
- new(Z) LoadLocalNode(catch_pos, stack_trace_param.var),
- Library::PrivateCoreLibName(Symbols::_setupFullStackTrace()),
- no_args));
}
// Add nested block with user-defined code. This blocks allows
@@ -8372,6 +8452,8 @@
} else {
parsed_function()->reset_saved_try_ctx_vars();
}
+ AddSavedExceptionAndStacktraceToScope(
+ exception_var, stack_trace_var, current_block_->scope);
}
current_block_->statements->Add(ParseNestedStatement(false, NULL));
@@ -8516,7 +8598,7 @@
// Restore the currently relevant :saved_try_context_var on the stack
-// from the captured :async_saved_try_cts_var.
+// from the captured :async_saved_try_ctx_var_.
// * Try blocks: Set the context variable for this try block.
// * Catch/finally blocks: Set the context variable for any outer try block (if
// existent).
@@ -8910,16 +8992,31 @@
if ((try_blocks_list_ == NULL) || !try_blocks_list_->inside_catch()) {
ReportError(statement_pos, "rethrow of an exception is not valid here");
}
- // The exception and stack trace variables are bound in the block
- // containing the try.
- LocalScope* scope = try_blocks_list_->try_block()->scope->parent();
- ASSERT(scope != NULL);
- LocalVariable* excp_var =
- scope->LocalLookupVariable(Symbols::ExceptionVar());
+
+ // If in async code, use :saved_exception_var and :saved_stack_trace_var
+ // instead of :exception_var and :stack_trace_var.
+ LocalVariable* excp_var;
+ LocalVariable* trace_var;
+ if (innermost_function().IsAsyncClosure() ||
+ innermost_function().IsAsyncFunction() ||
+ innermost_function().IsSyncGenClosure() ||
+ innermost_function().IsSyncGenerator()) {
+ // The saved exception and stack trace variables are bound in the block
+ // containing the catch. So start looking in the current scope.
+ LocalScope* scope = current_block_->scope;
+ excp_var = scope->LookupVariable(Symbols::SavedExceptionVar(), false);
+ trace_var = scope->LookupVariable(Symbols::SavedStackTraceVar(), false);
+ } else {
+ // The exception and stack trace variables are bound in the block
+ // containing the try. Look in the try scope directly.
+ LocalScope* scope = try_blocks_list_->try_block()->scope->parent();
+ ASSERT(scope != NULL);
+ excp_var = scope->LocalLookupVariable(Symbols::ExceptionVar());
+ trace_var = scope->LocalLookupVariable(Symbols::StackTraceVar());
+ }
ASSERT(excp_var != NULL);
- LocalVariable* trace_var =
- scope->LocalLookupVariable(Symbols::StackTraceVar());
ASSERT(trace_var != NULL);
+
statement = new(Z) ThrowNode(
statement_pos,
new(Z) LoadLocalNode(statement_pos, excp_var),
diff --git a/runtime/vm/parser.h b/runtime/vm/parser.h
index 326906d..bded365 100644
--- a/runtime/vm/parser.h
+++ b/runtime/vm/parser.h
@@ -602,6 +602,9 @@
void AddCatchParamsToScope(CatchParamDesc* exception_param,
CatchParamDesc* stack_trace_param,
LocalScope* scope);
+ void AddSavedExceptionAndStacktraceToScope(LocalVariable* exception_var,
+ LocalVariable* stack_trace_var,
+ LocalScope* scope);
// Parse all the catch clause of a try.
SequenceNode* ParseCatchClauses(intptr_t handler_pos,
LocalVariable* exception_var,
@@ -839,6 +842,9 @@
LocalScope* async_temp_scope_;
+ // Indentation of parser trace.
+ intptr_t trace_indent_;
+
DISALLOW_COPY_AND_ASSIGN(Parser);
};
diff --git a/runtime/vm/parser_test.cc b/runtime/vm/parser_test.cc
index 71fc503..ca7a261 100644
--- a/runtime/vm/parser_test.cc
+++ b/runtime/vm/parser_test.cc
@@ -280,7 +280,7 @@
" 0 ContextLevel level=1 scope=1 begin=2 end=37\n"
" 1 CurrentCtx scope=0 begin=0 end=0"
" name=:current_context_var\n"
- " 2 ContextVar level=1 begin=7 end=37 name=value\n"
+ " 2 ContextVar level=1 begin=10 end=37 name=value\n"
" 3 StackVar scope=2 begin=12 end=37 name=f\n",
CaptureVarsAtLine(lib, "main", 4));
}
@@ -321,7 +321,7 @@
" 0 ContextLevel level=1 scope=1 begin=8 end=38\n"
" 1 CurrentCtx scope=0 begin=0 end=0"
" name=:current_context_var\n"
- " 2 ContextVar level=1 begin=13 end=38 name=value\n"
+ " 2 ContextVar level=1 begin=16 end=38 name=value\n"
" 3 StackVar scope=2 begin=18 end=38 name=c\n"
// Closure call saves current context.
@@ -380,7 +380,7 @@
" 0 ContextLevel level=1 scope=1 begin=20 end=50\n"
" 1 CurrentCtx scope=0 begin=0 end=0"
" name=:current_context_var\n"
- " 2 ContextVar level=1 begin=25 end=50 name=value2\n"
+ " 2 ContextVar level=1 begin=28 end=50 name=value2\n"
" 3 StackVar scope=2 begin=30 end=50 name=bb\n"
// Closure call saves current context.
@@ -407,7 +407,7 @@
" 0 ContextLevel level=1 scope=1 begin=2 end=68\n"
" 1 CurrentCtx scope=0 begin=0 end=0"
" name=:current_context_var\n"
- " 2 ContextVar level=1 begin=7 end=68 name=value1\n"
+ " 2 ContextVar level=1 begin=10 end=68 name=value1\n"
" 3 StackVar scope=2 begin=12 end=68 name=b\n",
CaptureVarsAtLine(lib, "a", 7));
}
@@ -464,7 +464,7 @@
"doIt\n"
" 0 CurrentCtx scope=0 begin=0 end=0"
" name=:current_context_var\n"
- " 1 StackVar scope=2 begin=29 end=77 name=x\n",
+ " 1 StackVar scope=2 begin=35 end=77 name=x\n",
CaptureVarsAtLine(lib, "doIt", 12));
}
@@ -505,9 +505,9 @@
"outer\n"
" 0 CurrentCtx scope=0 begin=0 end=0"
" name=:current_context_var\n"
- " 1 StackVar scope=3 begin=9 end=50 name=i\n"
+ " 1 StackVar scope=3 begin=12 end=50 name=i\n"
" 2 ContextLevel level=1 scope=4 begin=20 end=50\n"
- " 3 ContextVar level=1 begin=23 end=50 name=value\n"
+ " 3 ContextVar level=1 begin=28 end=50 name=value\n"
" 4 StackVar scope=4 begin=30 end=50 name=inner\n",
CaptureVarsAtLine(lib, "outer", 5));
}
@@ -548,7 +548,7 @@
" name=:current_context_var\n"
" 2 StackVar scope=2 begin=46 end=68 name=c\n"
" 3 ContextLevel level=1 scope=3 begin=18 end=46\n"
- " 4 ContextVar level=1 begin=19 end=46 name=i\n"
+ " 4 ContextVar level=1 begin=22 end=46 name=i\n"
" 5 StackVar scope=4 begin=32 end=46 name=d\n"
"_FunctionImpl.call\n"
@@ -560,7 +560,7 @@
" 0 ContextLevel level=1 scope=1 begin=1 end=76\n"
" 1 CurrentCtx scope=0 begin=0 end=0"
" name=:current_context_var\n"
- " 2 ContextVar level=1 begin=6 end=76 name=x\n"
+ " 2 ContextVar level=1 begin=9 end=76 name=x\n"
" 3 StackVar scope=2 begin=11 end=76 name=b\n",
CaptureVarsAtLine(lib, "a", 10));
}
diff --git a/runtime/vm/raw_object.cc b/runtime/vm/raw_object.cc
index 9c95802..41d2f9c 100644
--- a/runtime/vm/raw_object.cc
+++ b/runtime/vm/raw_object.cc
@@ -72,7 +72,15 @@
ASSERT(IsHeapObject());
intptr_t class_id = GetClassId();
- RawClass* raw_class = isolate->class_table()->At(class_id);
+ ClassTable* class_table = isolate->class_table();
+#if defined(DEBUG)
+ if (!class_table->IsValidIndex(class_id) ||
+ !class_table->HasValidClassAt(class_id)) {
+ FATAL2("Invalid class id: %" Pd " from tags %" Px "\n",
+ class_id, ptr()->tags_);
+ }
+#endif // DEBUG
+ RawClass* raw_class = class_table->At(class_id);
ASSERT(raw_class->ptr()->id_ == class_id);
// Get the instance size out of the class.
@@ -205,9 +213,26 @@
}
}
ASSERT(instance_size != 0);
+#if defined(DEBUG)
uword tags = ptr()->tags_;
- ASSERT((instance_size == SizeTag::decode(tags)) ||
- (SizeTag::decode(tags) == 0));
+ intptr_t tags_size = SizeTag::decode(tags);
+ if ((class_id == kArrayCid) && (instance_size > tags_size && tags_size > 0)) {
+ // TODO(22501): Array::MakeArray could be in the process of shrinking
+ // the array (see comment therein), having already updated the tags but not
+ // yet set the new length. Wait a millisecond and try again.
+ int retries_remaining = 1000; // ... but not forever.
+ do {
+ OS::Sleep(1);
+ const RawArray* raw_array = reinterpret_cast<const RawArray*>(this);
+ intptr_t array_length = Smi::Value(raw_array->ptr()->length_);
+ instance_size = Array::InstanceSize(array_length);
+ } while ((instance_size > tags_size) && (--retries_remaining > 0));
+ }
+ if ((instance_size != tags_size) && (tags_size != 0)) {
+ FATAL3("Size mismatch: %" Pd " from class vs %" Pd " from tags %" Px "\n",
+ instance_size, tags_size, tags);
+ }
+#endif // DEBUG
return instance_size;
}
diff --git a/runtime/vm/raw_object.h b/runtime/vm/raw_object.h
index dd3e075..483bb24 100644
--- a/runtime/vm/raw_object.h
+++ b/runtime/vm/raw_object.h
@@ -1387,7 +1387,7 @@
return reinterpret_cast<RawObject**>(&ptr()->exception_);
}
RawInstance* exception_;
- RawStacktrace* stacktrace_;
+ RawInstance* stacktrace_;
RawObject** to() {
return reinterpret_cast<RawObject**>(&ptr()->stacktrace_);
}
@@ -1859,10 +1859,8 @@
}
RawArray* code_array_; // Code object for each frame in the stack trace.
RawArray* pc_offset_array_; // Offset of PC for each frame.
- RawArray* catch_code_array_; // Code for each frame in catch stack trace.
- RawArray* catch_pc_offset_array_; // Offset of PC for each catch stack frame.
RawObject** to() {
- return reinterpret_cast<RawObject**>(&ptr()->catch_pc_offset_array_);
+ return reinterpret_cast<RawObject**>(&ptr()->pc_offset_array_);
}
// False for pre-allocated stack trace (used in OOM and Stack overflow).
bool expand_inlined_;
diff --git a/runtime/vm/service.cc b/runtime/vm/service.cc
index cbb1699..404e8d3 100644
--- a/runtime/vm/service.cc
+++ b/runtime/vm/service.cc
@@ -27,6 +27,7 @@
#include "vm/port.h"
#include "vm/profiler_service.h"
#include "vm/reusable_handles.h"
+#include "vm/service_isolate.h"
#include "vm/stack_frame.h"
#include "vm/symbols.h"
#include "vm/unicode.h"
@@ -34,817 +35,23 @@
namespace dart {
-DEFINE_FLAG(bool, trace_service, false, "Trace VM service requests.");
-DEFINE_FLAG(bool, trace_service_pause_events, false,
- "Trace VM service isolate pause events.");
+DECLARE_FLAG(bool, trace_service);
+DECLARE_FLAG(bool, trace_service_pause_events);
DECLARE_FLAG(bool, enable_type_checks);
DECLARE_FLAG(bool, enable_asserts);
-struct ResourcesEntry {
- const char* path_;
- const char* resource_;
- int length_;
-};
-
-extern ResourcesEntry __service_resources_[];
-
-class Resources {
- public:
- static const int kNoSuchInstance = -1;
- static int ResourceLookup(const char* path, const char** resource) {
- ResourcesEntry* table = ResourceTable();
- for (int i = 0; table[i].path_ != NULL; i++) {
- const ResourcesEntry& entry = table[i];
- if (strcmp(path, entry.path_) == 0) {
- *resource = entry.resource_;
- ASSERT(entry.length_ > 0);
- return entry.length_;
- }
- }
- return kNoSuchInstance;
- }
-
- static const char* Path(int idx) {
- ASSERT(idx >= 0);
- ResourcesEntry* entry = At(idx);
- if (entry == NULL) {
- return NULL;
- }
- ASSERT(entry->path_ != NULL);
- return entry->path_;
- }
-
- static int Length(int idx) {
- ASSERT(idx >= 0);
- ResourcesEntry* entry = At(idx);
- if (entry == NULL) {
- return kNoSuchInstance;
- }
- ASSERT(entry->path_ != NULL);
- return entry->length_;
- }
-
- static const uint8_t* Resource(int idx) {
- ASSERT(idx >= 0);
- ResourcesEntry* entry = At(idx);
- if (entry == NULL) {
- return NULL;
- }
- return reinterpret_cast<const uint8_t*>(entry->resource_);
- }
-
- private:
- static ResourcesEntry* At(int idx) {
- ASSERT(idx >= 0);
- ResourcesEntry* table = ResourceTable();
- for (int i = 0; table[i].path_ != NULL; i++) {
- if (idx == i) {
- return &table[i];
- }
- }
- return NULL;
- }
-
- static ResourcesEntry* ResourceTable() {
- return &__service_resources_[0];
- }
-
- DISALLOW_ALLOCATION();
- DISALLOW_IMPLICIT_CONSTRUCTORS(Resources);
-};
-
-
-class EmbedderServiceHandler {
- public:
- explicit EmbedderServiceHandler(const char* name) : name_(NULL),
- callback_(NULL),
- user_data_(NULL),
- next_(NULL) {
- ASSERT(name != NULL);
- name_ = strdup(name);
- }
-
- ~EmbedderServiceHandler() {
- free(name_);
- }
-
- const char* name() const { return name_; }
-
- Dart_ServiceRequestCallback callback() const { return callback_; }
- void set_callback(Dart_ServiceRequestCallback callback) {
- callback_ = callback;
- }
-
- void* user_data() const { return user_data_; }
- void set_user_data(void* user_data) {
- user_data_ = user_data;
- }
-
- EmbedderServiceHandler* next() const { return next_; }
- void set_next(EmbedderServiceHandler* next) {
- next_ = next;
- }
-
- private:
- char* name_;
- Dart_ServiceRequestCallback callback_;
- void* user_data_;
- EmbedderServiceHandler* next_;
-};
-
-
-class LibraryCoverageFilter : public CoverageFilter {
- public:
- explicit LibraryCoverageFilter(const Library& lib) : lib_(lib) {}
- bool ShouldOutputCoverageFor(const Library& lib,
- const Script& script,
- const Class& cls,
- const Function& func) const {
- return lib.raw() == lib_.raw();
- }
- private:
- const Library& lib_;
-};
-
-
-class ScriptCoverageFilter : public CoverageFilter {
- public:
- explicit ScriptCoverageFilter(const Script& script)
- : script_(script) {}
- bool ShouldOutputCoverageFor(const Library& lib,
- const Script& script,
- const Class& cls,
- const Function& func) const {
- return script.raw() == script_.raw();
- }
- private:
- const Script& script_;
-};
-
-
-class ClassCoverageFilter : public CoverageFilter {
- public:
- explicit ClassCoverageFilter(const Class& cls) : cls_(cls) {}
- bool ShouldOutputCoverageFor(const Library& lib,
- const Script& script,
- const Class& cls,
- const Function& func) const {
- return cls.raw() == cls_.raw();
- }
- private:
- const Class& cls_;
-};
-
-
-class FunctionCoverageFilter : public CoverageFilter {
- public:
- explicit FunctionCoverageFilter(const Function& func) : func_(func) {}
- bool ShouldOutputCoverageFor(const Library& lib,
- const Script& script,
- const Class& cls,
- const Function& func) const {
- return func.raw() == func_.raw();
- }
- private:
- const Function& func_;
-};
-
+// TODO(johnmccutchan): Unify embedder service handler lists and their APIs.
+EmbedderServiceHandler* Service::isolate_service_handler_head_ = NULL;
+EmbedderServiceHandler* Service::root_service_handler_head_ = NULL;
+uint32_t Service::event_mask_ = 0;
+struct ServiceMethodDescriptor;
+ServiceMethodDescriptor* FindMethod(const char* method_name);
static uint8_t* allocator(uint8_t* ptr, intptr_t old_size, intptr_t new_size) {
void* new_ptr = realloc(reinterpret_cast<void*>(ptr), new_size);
return reinterpret_cast<uint8_t*>(new_ptr);
}
-
-static void SendIsolateServiceMessage(Dart_NativeArguments args) {
- NativeArguments* arguments = reinterpret_cast<NativeArguments*>(args);
- Isolate* isolate = arguments->isolate();
- StackZone zone(isolate);
- HANDLESCOPE(isolate);
- GET_NON_NULL_NATIVE_ARGUMENT(SendPort, sp, arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(Array, message, arguments->NativeArgAt(1));
-
- // Set the type of the OOB message.
- message.SetAt(0, Smi::Handle(isolate, Smi::New(Message::kServiceOOBMsg)));
-
- // Serialize message.
- uint8_t* data = NULL;
- MessageWriter writer(&data, &allocator, false);
- writer.WriteMessage(message);
-
- // TODO(turnidge): Throw an exception when the return value is false?
- PortMap::PostMessage(new Message(sp.Id(), data, writer.BytesWritten(),
- Message::kOOBPriority));
-}
-
-
-static void SendRootServiceMessage(Dart_NativeArguments args) {
- NativeArguments* arguments = reinterpret_cast<NativeArguments*>(args);
- Isolate* isolate = arguments->isolate();
- StackZone zone(isolate);
- HANDLESCOPE(isolate);
- GET_NON_NULL_NATIVE_ARGUMENT(Instance, message, arguments->NativeArgAt(0));
- Service::HandleRootMessage(message);
-}
-
-
-class ScopeStopwatch : public ValueObject {
- public:
- explicit ScopeStopwatch(const char* name) : name_(name) {
- start_ = OS::GetCurrentTimeMicros();
- }
-
- int64_t GetElapsed() const {
- int64_t end = OS::GetCurrentTimeMicros();
- ASSERT(end >= start_);
- return end - start_;
- }
-
- ~ScopeStopwatch() {
- int64_t elapsed = GetElapsed();
- OS::Print("[%" Pd "] %s took %" Pd64 " micros.\n",
- OS::ProcessId(), name_, elapsed);
- }
-
- private:
- const char* name_;
- int64_t start_;
-};
-
-
-bool Service::IsRunning() {
- MonitorLocker ml(monitor_);
- return (service_port_ != ILLEGAL_PORT) && (service_isolate_ != NULL);
-}
-
-
-void Service::SetServicePort(Dart_Port port) {
- MonitorLocker ml(monitor_);
- service_port_ = port;
-}
-
-
-void Service::SetServiceIsolate(Isolate* isolate) {
- MonitorLocker ml(monitor_);
- service_isolate_ = isolate;
- if (service_isolate_ != NULL) {
- service_isolate_->is_service_isolate_ = true;
- }
-}
-
-
-bool Service::HasServiceIsolate() {
- MonitorLocker ml(monitor_);
- return service_isolate_ != NULL;
-}
-
-
-bool Service::IsServiceIsolate(Isolate* isolate) {
- MonitorLocker ml(monitor_);
- return isolate == service_isolate_;
-}
-
-Dart_Port Service::WaitForLoadPort() {
- MonitorLocker ml(monitor_);
-
- while (initializing_ && (load_port_ == ILLEGAL_PORT)) {
- ml.Wait();
- }
-
- return load_port_;
-}
-
-
-Dart_Port Service::LoadPort() {
- MonitorLocker ml(monitor_);
- return load_port_;
-}
-
-
-void Service::SetLoadPort(Dart_Port port) {
- MonitorLocker ml(monitor_);
- load_port_ = port;
-}
-
-
-void Service::SetEventMask(uint32_t mask) {
- event_mask_ = mask;
-}
-
-
-static void SetEventMask(Dart_NativeArguments args) {
- NativeArguments* arguments = reinterpret_cast<NativeArguments*>(args);
- Isolate* isolate = arguments->isolate();
- StackZone zone(isolate);
- HANDLESCOPE(isolate);
- GET_NON_NULL_NATIVE_ARGUMENT(Integer, mask, arguments->NativeArgAt(0));
- Service::SetEventMask(mask.AsTruncatedUint32Value());
-}
-
-
-// These must be kept in sync with service/constants.dart
-#define VM_SERVICE_ISOLATE_STARTUP_MESSAGE_ID 1
-#define VM_SERVICE_ISOLATE_SHUTDOWN_MESSAGE_ID 2
-
-
-static RawArray* MakeServiceControlMessage(Dart_Port port_id, intptr_t code,
- const String& name) {
- const Array& list = Array::Handle(Array::New(4));
- ASSERT(!list.IsNull());
- const Integer& code_int = Integer::Handle(Integer::New(code));
- const Integer& port_int = Integer::Handle(Integer::New(port_id));
- const SendPort& send_port = SendPort::Handle(SendPort::New(port_id));
- list.SetAt(0, code_int);
- list.SetAt(1, port_int);
- list.SetAt(2, send_port);
- list.SetAt(3, name);
- return list.raw();
-}
-
-
-class RegisterRunningIsolatesVisitor : public IsolateVisitor {
- public:
- explicit RegisterRunningIsolatesVisitor(Isolate* service_isolate)
- : IsolateVisitor(),
- register_function_(Function::Handle(service_isolate)),
- service_isolate_(service_isolate) {
- ASSERT(Service::IsServiceIsolate(Isolate::Current()));
- // Get library.
- const String& library_url = Symbols::DartVMService();
- ASSERT(!library_url.IsNull());
- const Library& library =
- Library::Handle(Library::LookupLibrary(library_url));
- ASSERT(!library.IsNull());
- // Get function.
- const String& function_name =
- String::Handle(String::New("_registerIsolate"));
- ASSERT(!function_name.IsNull());
- register_function_ = library.LookupFunctionAllowPrivate(function_name);
- ASSERT(!register_function_.IsNull());
- }
-
- virtual void VisitIsolate(Isolate* isolate) {
- ASSERT(Service::IsServiceIsolate(Isolate::Current()));
- if (Service::IsServiceIsolate(isolate) ||
- (isolate == Dart::vm_isolate())) {
- // We do not register the service or vm isolate.
- return;
- }
- // Setup arguments for call.
- Dart_Port port_id = isolate->main_port();
- const Integer& port_int = Integer::Handle(Integer::New(port_id));
- ASSERT(!port_int.IsNull());
- const SendPort& send_port = SendPort::Handle(SendPort::New(port_id));
- const String& name = String::Handle(String::New(isolate->name()));
- ASSERT(!name.IsNull());
- const Array& args = Array::Handle(Array::New(3));
- ASSERT(!args.IsNull());
- args.SetAt(0, port_int);
- args.SetAt(1, send_port);
- args.SetAt(2, name);
- Object& r = Object::Handle(service_isolate_);
- r = DartEntry::InvokeFunction(register_function_, args);
- if (FLAG_trace_service) {
- OS::Print("vm-service: Isolate %s %" Pd64 " registered.\n",
- name.ToCString(),
- port_id);
- }
- ASSERT(!r.IsError());
- }
-
- private:
- Function& register_function_;
- Isolate* service_isolate_;
-};
-
-
-static Dart_Port ExtractPort(Isolate* isolate, Dart_Handle receivePort) {
- const ReceivePort& rp = Api::UnwrapReceivePortHandle(isolate, receivePort);
- if (rp.IsNull()) {
- return ILLEGAL_PORT;
- }
- return rp.Id();
-}
-
-
-static void OnStart(Dart_NativeArguments args) {
- NativeArguments* arguments = reinterpret_cast<NativeArguments*>(args);
- Isolate* isolate = arguments->isolate();
- StackZone zone(isolate);
- HANDLESCOPE(isolate);
- {
- if (FLAG_trace_service) {
- OS::Print("vm-service: Booting dart:vmservice library.\n");
- }
- // Boot the dart:vmservice library.
- Dart_EnterScope();
- Dart_Handle url_str =
- Dart_NewStringFromCString(Symbols::Name(Symbols::kDartVMServiceId));
- Dart_Handle library = Dart_LookupLibrary(url_str);
- ASSERT(Dart_IsLibrary(library));
- Dart_Handle result =
- Dart_Invoke(library, Dart_NewStringFromCString("boot"), 0, NULL);
- ASSERT(!Dart_IsError(result));
- Dart_Port port = ExtractPort(isolate, result);
- ASSERT(port != ILLEGAL_PORT);
- Service::SetServicePort(port);
- Dart_ExitScope();
- }
-
- {
- if (FLAG_trace_service) {
- OS::Print("vm-service: Registering running isolates.\n");
- }
- // Register running isolates with service.
- RegisterRunningIsolatesVisitor register_isolates(isolate);
- Isolate::VisitIsolates(®ister_isolates);
- }
-}
-
-
-struct VmServiceNativeEntry {
- const char* name;
- int num_arguments;
- Dart_NativeFunction function;
-};
-
-
-static VmServiceNativeEntry _VmServiceNativeEntries[] = {
- {"VMService_SendIsolateServiceMessage", 2, SendIsolateServiceMessage},
- {"VMService_SendRootServiceMessage", 1, SendRootServiceMessage},
- {"VMService_SetEventMask", 1, SetEventMask},
- {"VMService_OnStart", 0, OnStart },
-};
-
-
-static Dart_NativeFunction VmServiceNativeResolver(Dart_Handle name,
- int num_arguments,
- bool* auto_setup_scope) {
- const Object& obj = Object::Handle(Api::UnwrapHandle(name));
- if (!obj.IsString()) {
- return NULL;
- }
- const char* function_name = obj.ToCString();
- ASSERT(function_name != NULL);
- ASSERT(auto_setup_scope != NULL);
- *auto_setup_scope = true;
- intptr_t n =
- sizeof(_VmServiceNativeEntries) / sizeof(_VmServiceNativeEntries[0]);
- for (intptr_t i = 0; i < n; i++) {
- VmServiceNativeEntry entry = _VmServiceNativeEntries[i];
- if ((strcmp(function_name, entry.name) == 0) &&
- (num_arguments == entry.num_arguments)) {
- return entry.function;
- }
- }
- return NULL;
-}
-
-const char* Service::kIsolateName = "vm-service";
-EmbedderServiceHandler* Service::isolate_service_handler_head_ = NULL;
-EmbedderServiceHandler* Service::root_service_handler_head_ = NULL;
-Isolate* Service::service_isolate_ = NULL;
-Dart_Port Service::service_port_ = ILLEGAL_PORT;
-Dart_Port Service::load_port_ = ILLEGAL_PORT;
-Dart_IsolateCreateCallback Service::create_callback_ = NULL;
-Monitor* Service::monitor_ = NULL;
-bool Service::initializing_ = true;
-uint32_t Service::event_mask_ = 0;
-
-
-bool Service::IsServiceIsolateName(const char* name) {
- ASSERT(name != NULL);
- return strcmp(name, kIsolateName) == 0;
-}
-
-
-bool Service::SendIsolateStartupMessage() {
- if (!IsRunning()) {
- return false;
- }
- Isolate* isolate = Isolate::Current();
- if (IsServiceIsolate(isolate)) {
- return false;
- }
- ASSERT(isolate != NULL);
- HANDLESCOPE(isolate);
- const String& name = String::Handle(String::New(isolate->name()));
- ASSERT(!name.IsNull());
- const Array& list = Array::Handle(
- MakeServiceControlMessage(Dart_GetMainPortId(),
- VM_SERVICE_ISOLATE_STARTUP_MESSAGE_ID,
- name));
- ASSERT(!list.IsNull());
- uint8_t* data = NULL;
- MessageWriter writer(&data, &allocator, false);
- writer.WriteMessage(list);
- intptr_t len = writer.BytesWritten();
- if (FLAG_trace_service) {
- OS::Print("vm-service: Isolate %s %" Pd64 " registered.\n",
- name.ToCString(),
- Dart_GetMainPortId());
- }
- return PortMap::PostMessage(
- new Message(service_port_, data, len, Message::kNormalPriority));
-}
-
-
-bool Service::SendIsolateShutdownMessage() {
- if (!IsRunning()) {
- return false;
- }
- Isolate* isolate = Isolate::Current();
- if (IsServiceIsolate(isolate)) {
- return false;
- }
- ASSERT(isolate != NULL);
- HANDLESCOPE(isolate);
- const String& name = String::Handle(String::New(isolate->name()));
- ASSERT(!name.IsNull());
- const Array& list = Array::Handle(
- MakeServiceControlMessage(Dart_GetMainPortId(),
- VM_SERVICE_ISOLATE_SHUTDOWN_MESSAGE_ID,
- name));
- ASSERT(!list.IsNull());
- uint8_t* data = NULL;
- MessageWriter writer(&data, &allocator, false);
- writer.WriteMessage(list);
- intptr_t len = writer.BytesWritten();
- if (FLAG_trace_service) {
- OS::Print("vm-service: Isolate %s %" Pd64 " deregistered.\n",
- name.ToCString(),
- Dart_GetMainPortId());
- }
- return PortMap::PostMessage(
- new Message(service_port_, data, len, Message::kNormalPriority));
-}
-
-
-Dart_Handle Service::GetSource(const char* name) {
- ASSERT(name != NULL);
- int i = 0;
- while (true) {
- const char* path = Resources::Path(i);
- if (path == NULL) {
- break;
- }
- ASSERT(*path != '\0');
- // Skip the '/'.
- path++;
- if (strcmp(name, path) == 0) {
- const uint8_t* str = Resources::Resource(i);
- intptr_t length = Resources::Length(i);
- return Dart_NewStringFromUTF8(str, length);
- }
- i++;
- }
- return Dart_Null();
-}
-
-
-Dart_Handle Service::LibraryTagHandler(Dart_LibraryTag tag,
- Dart_Handle library,
- Dart_Handle url) {
- if (tag == Dart_kCanonicalizeUrl) {
- // url is already canonicalized.
- return url;
- }
- if (tag != Dart_kSourceTag) {
- FATAL("Service::LibraryTagHandler encountered an unexpected tag.");
- }
- ASSERT(tag == Dart_kSourceTag);
- const char* url_string = NULL;
- Dart_Handle result = Dart_StringToCString(url, &url_string);
- if (Dart_IsError(result)) {
- return result;
- }
- Dart_Handle source = GetSource(url_string);
- if (Dart_IsError(source)) {
- return source;
- }
- return Dart_LoadSource(library, url, source, 0, 0);
-}
-
-
-void Service::MaybeInjectVMServiceLibrary(Isolate* isolate) {
- ASSERT(isolate != NULL);
- ASSERT(isolate->name() != NULL);
- if (!Service::IsServiceIsolateName(isolate->name())) {
- // Not service isolate.
- return;
- }
- if (HasServiceIsolate()) {
- // Service isolate already exists.
- return;
- }
- SetServiceIsolate(isolate);
-
- StackZone zone(isolate);
- HANDLESCOPE(isolate);
-
- // Register dart:vmservice library.
- const String& url_str = String::Handle(Symbols::DartVMService().raw());
- const Library& library = Library::Handle(Library::New(url_str));
- library.Register();
- library.set_native_entry_resolver(VmServiceNativeResolver);
-
- // Temporarily install our library tag handler.
- isolate->set_library_tag_handler(LibraryTagHandler);
-
- // Get script source.
- const char* resource = NULL;
- const char* path = "/vmservice.dart";
- intptr_t r = Resources::ResourceLookup(path, &resource);
- ASSERT(r != Resources::kNoSuchInstance);
- ASSERT(resource != NULL);
- const String& source_str = String::Handle(
- String::FromUTF8(reinterpret_cast<const uint8_t*>(resource), r));
- ASSERT(!source_str.IsNull());
- const Script& script = Script::Handle(
- isolate, Script::New(url_str, source_str, RawScript::kLibraryTag));
-
- // Compile script.
- Dart_EnterScope(); // Need to enter scope for tag handler.
- library.SetLoadInProgress();
- const Error& error = Error::Handle(isolate,
- Compiler::Compile(library, script));
- ASSERT(error.IsNull());
- Dart_Handle result = Dart_FinalizeLoading(false);
- ASSERT(!Dart_IsError(result));
- Dart_ExitScope();
-
- // Uninstall our library tag handler.
- isolate->set_library_tag_handler(NULL);
-}
-
-
-void Service::FinishedInitializing() {
- MonitorLocker ml(monitor_);
- initializing_ = false;
- ml.NotifyAll();
-}
-
-
-static void ShutdownIsolate(uword parameter) {
- Isolate* isolate = reinterpret_cast<Isolate*>(parameter);
- ASSERT(Service::IsServiceIsolate(isolate));
- {
- // Print the error if there is one. This may execute dart code to
- // print the exception object, so we need to use a StartIsolateScope.
- StartIsolateScope start_scope(isolate);
- StackZone zone(isolate);
- HandleScope handle_scope(isolate);
- Error& error = Error::Handle();
- error = isolate->object_store()->sticky_error();
- if (!error.IsNull()) {
- OS::PrintErr("vm-service: Error: %s\n", error.ToErrorCString());
- }
- Dart::RunShutdownCallback();
- }
- {
- // Shut the isolate down.
- SwitchIsolateScope switch_scope(isolate);
- Dart::ShutdownIsolate();
- }
- Service::SetServiceIsolate(NULL);
- Service::SetServicePort(ILLEGAL_PORT);
- if (FLAG_trace_service) {
- OS::Print("vm-service: Shutdown.\n");
- }
-}
-
-
-class RunServiceTask : public ThreadPool::Task {
- public:
- virtual void Run() {
- ASSERT(Isolate::Current() == NULL);
- char* error = NULL;
- Isolate* isolate = NULL;
-
- Dart_IsolateCreateCallback create_callback = Service::create_callback();
- // TODO(johnmccutchan): Support starting up service isolate without embedder
- // provided isolate creation callback.
- if (create_callback == NULL) {
- Service::FinishedInitializing();
- return;
- }
-
- isolate =
- reinterpret_cast<Isolate*>(create_callback(Service::kIsolateName,
- NULL,
- NULL,
- NULL,
- &error));
- if (isolate == NULL) {
- OS::PrintErr("vm-service: Isolate creation error: %s\n", error);
- Service::FinishedInitializing();
- return;
- }
-
- Isolate::SetCurrent(NULL);
-
- RunMain(isolate);
-
- Service::FinishedInitializing();
-
- isolate->message_handler()->Run(Dart::thread_pool(),
- NULL,
- ShutdownIsolate,
- reinterpret_cast<uword>(isolate));
- }
-
- protected:
- void RunMain(Isolate* isolate) {
- StartIsolateScope iso_scope(isolate);
- StackZone zone(isolate);
- HANDLESCOPE(isolate);
- // Invoke main which will return the loadScriptPort.
- const Library& root_library =
- Library::Handle(isolate, isolate->object_store()->root_library());
- if (root_library.IsNull()) {
- if (FLAG_trace_service) {
- OS::Print("vm-service: Embedder did not install a script.");
- }
- // Service isolate is not supported by embedder.
- return;
- }
- ASSERT(!root_library.IsNull());
- const String& entry_name = String::Handle(isolate, String::New("main"));
- ASSERT(!entry_name.IsNull());
- const Function& entry =
- Function::Handle(isolate,
- root_library.LookupFunctionAllowPrivate(entry_name));
- if (entry.IsNull()) {
- // Service isolate is not supported by embedder.
- if (FLAG_trace_service) {
- OS::Print("vm-service: Embedder did not provide a main function.");
- }
- return;
- }
- ASSERT(!entry.IsNull());
- const Object& result =
- Object::Handle(isolate,
- DartEntry::InvokeFunction(entry,
- Object::empty_array()));
- ASSERT(!result.IsNull());
- if (result.IsError()) {
- // Service isolate did not initialize properly.
- if (FLAG_trace_service) {
- const Error& error = Error::Cast(result);
- OS::Print("vm-service: Calling main resulted in an error: %s",
- error.ToErrorCString());
- }
- return;
- }
- ASSERT(result.IsReceivePort());
- const ReceivePort& rp = ReceivePort::Cast(result);
- Service::SetLoadPort(rp.Id());
- }
-};
-
-
-void Service::RunService() {
- ASSERT(monitor_ == NULL);
- monitor_ = new Monitor();
- ASSERT(monitor_ != NULL);
- // Grab the isolate create callback here to avoid race conditions with tests
- // that change this after Dart_Initialize returns.
- create_callback_ = Isolate::CreateCallback();
- Dart::thread_pool()->Run(new RunServiceTask());
-}
-
-// A handler for a per-isolate request.
-//
-// If a handler returns true, the reply is complete and ready to be
-// posted. If a handler returns false, then it is responsible for
-// posting the reply (this can be used for asynchronous delegation of
-// the response handling).
-typedef bool (*IsolateMessageHandler)(Isolate* isolate, JSONStream* stream);
-
-struct IsolateMessageHandlerEntry {
- const char* method;
- IsolateMessageHandler handler;
-};
-
-static IsolateMessageHandler FindIsolateMessageHandler(const char* method);
-
-
-// A handler for a root (vm-global) request.
-//
-// If a handler returns true, the reply is complete and ready to be
-// posted. If a handler returns false, then it is responsible for
-// posting the reply (this can be used for asynchronous delegation of
-// the response handling).
-typedef bool (*RootMessageHandler)(JSONStream* stream);
-
-struct RootMessageHandlerEntry {
- const char* method;
- RootMessageHandler handler;
-};
-
-static RootMessageHandler FindRootMessageHandler(const char* method);
-
-
static void PrintRequest(const JSONObject& obj, JSONStream* js) {
JSONObject jsobj(&obj, "request");
jsobj.AddProperty("method", js->method());
@@ -899,6 +106,11 @@
}
+static void PrintUnrecognizedMethodError(JSONStream* js) {
+ PrintError(js, "unrecognized method: %s", js->method());
+}
+
+
static void PrintErrorWithKind(JSONStream* js,
const char* kind,
const char* format, ...) {
@@ -924,130 +136,6 @@
}
-void Service::HandleIsolateMessage(Isolate* isolate, const Array& msg) {
- ASSERT(isolate != NULL);
- ASSERT(!msg.IsNull());
- ASSERT(msg.Length() == 5);
-
- {
- StackZone zone(isolate);
- HANDLESCOPE(isolate);
-
- Instance& reply_port = Instance::Handle(isolate);
- String& method = String::Handle(isolate);
- Array& param_keys = Array::Handle(isolate);
- Array& param_values = Array::Handle(isolate);
- reply_port ^= msg.At(1);
- method ^= msg.At(2);
- param_keys ^= msg.At(3);
- param_values ^= msg.At(4);
-
- ASSERT(!method.IsNull());
- ASSERT(!param_keys.IsNull());
- ASSERT(!param_values.IsNull());
- ASSERT(param_keys.Length() == param_values.Length());
-
- if (!reply_port.IsSendPort()) {
- FATAL("SendPort expected.");
- }
-
- IsolateMessageHandler handler =
- FindIsolateMessageHandler(method.ToCString());
- {
- JSONStream js;
- js.Setup(zone.GetZone(), SendPort::Cast(reply_port).Id(),
- method, param_keys, param_values);
- if (handler == NULL) {
- // Check for an embedder handler.
- EmbedderServiceHandler* e_handler =
- FindIsolateEmbedderHandler(method.ToCString());
- if (e_handler != NULL) {
- EmbedderHandleMessage(e_handler, &js);
- } else {
- if (FindRootMessageHandler(method.ToCString()) != NULL) {
- PrintError(&js, "%s does not expect the 'isolateId' parameter",
- method.ToCString());
- } else {
- PrintError(&js, "Unrecognized method: %s", method.ToCString());
- }
- }
- js.PostReply();
- } else {
- if (handler(isolate, &js)) {
- // Handler returns true if the reply is ready to be posted.
- // TODO(johnmccutchan): Support asynchronous replies.
- js.PostReply();
- }
- }
- }
- }
-}
-
-
-static bool HandleIsolate(Isolate* isolate, JSONStream* js) {
- isolate->PrintJSON(js, false);
- return true;
-}
-
-
-static bool HandleIsolateGetStack(Isolate* isolate, JSONStream* js) {
- DebuggerStackTrace* stack = isolate->debugger()->StackTrace();
- JSONObject jsobj(js);
- jsobj.AddProperty("type", "Stack");
- JSONArray jsarr(&jsobj, "frames");
- intptr_t num_frames = stack->Length();
- for (intptr_t i = 0; i < num_frames; i++) {
- ActivationFrame* frame = stack->FrameAt(i);
- JSONObject jsobj(&jsarr);
- frame->PrintToJSONObject(&jsobj);
- // TODO(turnidge): Implement depth differently -- differentiate
- // inlined frames.
- jsobj.AddProperty("depth", i);
- }
- return true;
-}
-
-
-static bool HandleCommonEcho(JSONObject* jsobj, JSONStream* js) {
- jsobj->AddProperty("type", "_EchoResponse");
- if (js->HasParam("text")) {
- jsobj->AddProperty("text", js->LookupParam("text"));
- }
- return true;
-}
-
-
-void Service::SendEchoEvent(Isolate* isolate, const char* text) {
- JSONStream js;
- {
- JSONObject jsobj(&js);
- jsobj.AddProperty("type", "ServiceEvent");
- jsobj.AddProperty("eventType", "_Echo");
- jsobj.AddProperty("isolate", isolate);
- if (text != NULL) {
- jsobj.AddProperty("text", text);
- }
- }
- const String& message = String::Handle(String::New(js.ToCString()));
- uint8_t data[] = {0, 128, 255};
- // TODO(koda): Add 'testing' event family.
- SendEvent(kEventFamilyDebug, message, data, sizeof(data));
-}
-
-
-static bool HandleIsolateTriggerEchoEvent(Isolate* isolate, JSONStream* js) {
- Service::SendEchoEvent(isolate, js->LookupParam("text"));
- JSONObject jsobj(js);
- return HandleCommonEcho(&jsobj, js);
-}
-
-
-static bool HandleIsolateEcho(Isolate* isolate, JSONStream* js) {
- JSONObject jsobj(js);
- return HandleCommonEcho(&jsobj, js);
-}
-
-
static bool GetIntegerId(const char* s, intptr_t* id, int base = 10) {
if ((s == NULL) || (*s == '\0')) {
// Empty string.
@@ -1110,6 +198,7 @@
return true;
}
+
// Scans the string until the '-' character. Returns pointer to string
// at '-' character. Returns NULL if not found.
static const char* ScanUntilDash(const char* s) {
@@ -1154,6 +243,563 @@
}
+// TODO(johnmccutchan): Split into separate file and write unit tests.
+class MethodParameter {
+ public:
+ MethodParameter(const char* name, bool required)
+ : name_(name), required_(required) {
+ }
+
+ virtual ~MethodParameter() { }
+
+ virtual bool Validate(const char* value) const {
+ return true;
+ }
+
+ const char* name() const {
+ return name_;
+ }
+
+ bool required() const {
+ return required_;
+ }
+
+ private:
+ const char* name_;
+ bool required_;
+};
+
+
+class NoSuchParameter : public MethodParameter {
+ public:
+ explicit NoSuchParameter(const char* name)
+ : MethodParameter(name, false) {
+ }
+
+ virtual bool Validate(const char* value) const {
+ return (value == NULL);
+ }
+};
+
+
+#define NO_ISOLATE_PARAMETER new NoSuchParameter("isolateId")
+
+
+class BoolParameter : public MethodParameter {
+ public:
+ BoolParameter(const char* name, bool required)
+ : MethodParameter(name, required) {
+ }
+
+ virtual bool Validate(const char* value) const {
+ if (value == NULL) {
+ return false;
+ }
+ return (strcmp("true", value) == 0) || (strcmp("false", value) == 0);
+ }
+
+ static bool Parse(const char* value) {
+ return strcmp("true", value) == 0;
+ }
+};
+
+
+class UIntParameter : public MethodParameter {
+ public:
+ UIntParameter(const char* name, bool required)
+ : MethodParameter(name, required) {
+ }
+
+ virtual bool Validate(const char* value) const {
+ if (value == NULL) {
+ return false;
+ }
+ for (const char* cp = value; *cp != '\0'; cp++) {
+ if (*cp < '0' || *cp > '9') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static intptr_t Parse(const char* value) {
+ char* end_ptr = NULL;
+ uintptr_t result = strtoul(value, &end_ptr, 10);
+ ASSERT(*end_ptr == '\0'); // Parsed full string
+ return result;
+ }
+};
+
+
+class IdParameter : public MethodParameter {
+ public:
+ IdParameter(const char* name, bool required)
+ : MethodParameter(name, required) {
+ }
+
+ virtual bool Validate(const char* value) const {
+ return (value != NULL);
+ }
+};
+
+
+#define ISOLATE_PARAMETER new IdParameter("isolateId", true)
+
+
+class EnumParameter : public MethodParameter {
+ public:
+ EnumParameter(const char* name, bool required, const char** enums)
+ : MethodParameter(name, required),
+ enums_(enums) {
+ }
+
+ virtual bool Validate(const char* value) const {
+ if (value == NULL) {
+ return true;
+ }
+ for (intptr_t i = 0; enums_[i] != NULL; i++) {
+ if (strcmp(value, enums_[i]) == 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private:
+ const char** enums_;
+};
+
+
+// If the key is not found, this function returns the last element in the
+// values array. This can be used to encode the default value.
+template<typename T>
+T EnumMapper(const char* value, const char** enums, T* values) {
+ ASSERT(value != NULL);
+ intptr_t i = 0;
+ for (i = 0; enums[i] != NULL; i++) {
+ if (strcmp(value, enums[i]) == 0) {
+ return values[i];
+ }
+ }
+ // Default value.
+ return values[i];
+}
+
+
+typedef bool (*ServiceMethodEntry)(Isolate* isolate, JSONStream* js);
+
+
+struct ServiceMethodDescriptor {
+ const char* name;
+ const ServiceMethodEntry entry;
+ const MethodParameter* const * parameters;
+};
+
+
+// TODO(johnmccutchan): Do we reject unexpected parameters?
+static bool ValidateParameters(const MethodParameter* const* parameters,
+ JSONStream* js) {
+ if (parameters == NULL) {
+ return true;
+ }
+ for (intptr_t i = 0; parameters[i] != NULL; i++) {
+ const MethodParameter* parameter = parameters[i];
+ const char* name = parameter->name();
+ const bool required = parameter->required();
+ const char* value = js->LookupParam(name);
+ const bool has_parameter = (value != NULL);
+ if (required && !has_parameter) {
+ PrintMissingParamError(js, name);
+ return false;
+ }
+ if (!parameter->Validate(value)) {
+ PrintInvalidParamError(js, name);
+ return false;
+ }
+ }
+ return true;
+}
+
+
+void Service::InvokeMethod(Isolate* isolate, const Array& msg) {
+ ASSERT(isolate != NULL);
+ ASSERT(!msg.IsNull());
+ ASSERT(msg.Length() == 5);
+
+ {
+ StackZone zone(isolate);
+ HANDLESCOPE(isolate);
+
+ Instance& reply_port = Instance::Handle(isolate);
+ String& method_name = String::Handle(isolate);
+ Array& param_keys = Array::Handle(isolate);
+ Array& param_values = Array::Handle(isolate);
+ reply_port ^= msg.At(1);
+ method_name ^= msg.At(2);
+ param_keys ^= msg.At(3);
+ param_values ^= msg.At(4);
+
+ ASSERT(!method_name.IsNull());
+ ASSERT(!param_keys.IsNull());
+ ASSERT(!param_values.IsNull());
+ ASSERT(param_keys.Length() == param_values.Length());
+
+ if (!reply_port.IsSendPort()) {
+ FATAL("SendPort expected.");
+ }
+
+ JSONStream js;
+ js.Setup(zone.GetZone(), SendPort::Cast(reply_port).Id(),
+ method_name, param_keys, param_values);
+
+ const char* c_method_name = method_name.ToCString();
+
+ ServiceMethodDescriptor* method = FindMethod(c_method_name);
+ if (method != NULL) {
+ if (!ValidateParameters(method->parameters, &js)) {
+ js.PostReply();
+ return;
+ }
+ if (method->entry(isolate, &js)) {
+ js.PostReply();
+ }
+ return;
+ }
+
+ EmbedderServiceHandler* handler = FindIsolateEmbedderHandler(c_method_name);
+ if (handler == NULL) {
+ handler = FindRootEmbedderHandler(c_method_name);
+ }
+
+ if (handler != NULL) {
+ EmbedderHandleMessage(handler, &js);
+ js.PostReply();
+ return;
+ }
+
+ PrintUnrecognizedMethodError(&js);
+ js.PostReply();
+ return;
+ }
+}
+
+
+void Service::HandleRootMessage(const Array& msg_instance) {
+ Isolate* isolate = Isolate::Current();
+ InvokeMethod(isolate, msg_instance);
+}
+
+
+void Service::HandleIsolateMessage(Isolate* isolate, const Array& msg) {
+ ASSERT(isolate != NULL);
+ InvokeMethod(isolate, msg);
+}
+
+
+bool Service::EventMaskHas(uint32_t mask) {
+ return (event_mask_ & mask) != 0;
+}
+
+
+bool Service::NeedsDebuggerEvents() {
+ return ServiceIsolate::IsRunning() && EventMaskHas(kEventFamilyDebugMask);
+}
+
+
+bool Service::NeedsGCEvents() {
+ return ServiceIsolate::IsRunning() && EventMaskHas(kEventFamilyGCMask);
+}
+
+
+void Service::SetEventMask(uint32_t mask) {
+ event_mask_ = mask;
+}
+
+
+void Service::SendEvent(intptr_t eventId, const Object& eventMessage) {
+ if (!ServiceIsolate::IsRunning()) {
+ return;
+ }
+ Isolate* isolate = Isolate::Current();
+ ASSERT(isolate != NULL);
+ HANDLESCOPE(isolate);
+
+ // Construct a list of the form [eventId, eventMessage].
+ const Array& list = Array::Handle(Array::New(2));
+ ASSERT(!list.IsNull());
+ list.SetAt(0, Integer::Handle(Integer::New(eventId)));
+ list.SetAt(1, eventMessage);
+
+ // Push the event to port_.
+ uint8_t* data = NULL;
+ MessageWriter writer(&data, &allocator, false);
+ writer.WriteMessage(list);
+ intptr_t len = writer.BytesWritten();
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Pushing event of type %" Pd ", len %" Pd "\n",
+ eventId, len);
+ }
+ // TODO(turnidge): For now we ignore failure to send an event. Revisit?
+ PortMap::PostMessage(
+ new Message(ServiceIsolate::Port(), data, len, Message::kNormalPriority));
+}
+
+
+void Service::SendEvent(intptr_t eventId,
+ const String& meta,
+ const uint8_t* data,
+ intptr_t size) {
+ // Bitstream: [meta data size (big-endian 64 bit)] [meta data (UTF-8)] [data]
+ const intptr_t meta_bytes = Utf8::Length(meta);
+ const intptr_t total_bytes = sizeof(uint64_t) + meta_bytes + size;
+ const TypedData& message = TypedData::Handle(
+ TypedData::New(kTypedDataUint8ArrayCid, total_bytes));
+ intptr_t offset = 0;
+ // TODO(koda): Rename these methods SetHostUint64, etc.
+ message.SetUint64(0, Utils::HostToBigEndian64(meta_bytes));
+ offset += sizeof(uint64_t);
+ {
+ NoGCScope no_gc;
+ meta.ToUTF8(static_cast<uint8_t*>(message.DataAddr(offset)), meta_bytes);
+ offset += meta_bytes;
+ }
+ // TODO(koda): It would be nice to avoid this copy (requires changes to
+ // MessageWriter code).
+ {
+ NoGCScope no_gc;
+ memmove(message.DataAddr(offset), data, size);
+ offset += size;
+ }
+ ASSERT(offset == total_bytes);
+ SendEvent(eventId, message);
+}
+
+
+void Service::HandleGCEvent(GCEvent* event) {
+ JSONStream js;
+ event->PrintJSON(&js);
+ const String& message = String::Handle(String::New(js.ToCString()));
+ SendEvent(kEventFamilyGC, message);
+}
+
+
+void Service::HandleDebuggerEvent(DebuggerEvent* event) {
+ JSONStream js;
+ event->PrintJSON(&js);
+ const String& message = String::Handle(String::New(js.ToCString()));
+ SendEvent(kEventFamilyDebug, message);
+}
+
+
+class EmbedderServiceHandler {
+ public:
+ explicit EmbedderServiceHandler(const char* name) : name_(NULL),
+ callback_(NULL),
+ user_data_(NULL),
+ next_(NULL) {
+ ASSERT(name != NULL);
+ name_ = strdup(name);
+ }
+
+ ~EmbedderServiceHandler() {
+ free(name_);
+ }
+
+ const char* name() const { return name_; }
+
+ Dart_ServiceRequestCallback callback() const { return callback_; }
+ void set_callback(Dart_ServiceRequestCallback callback) {
+ callback_ = callback;
+ }
+
+ void* user_data() const { return user_data_; }
+ void set_user_data(void* user_data) {
+ user_data_ = user_data;
+ }
+
+ EmbedderServiceHandler* next() const { return next_; }
+ void set_next(EmbedderServiceHandler* next) {
+ next_ = next;
+ }
+
+ private:
+ char* name_;
+ Dart_ServiceRequestCallback callback_;
+ void* user_data_;
+ EmbedderServiceHandler* next_;
+};
+
+
+void Service::EmbedderHandleMessage(EmbedderServiceHandler* handler,
+ JSONStream* js) {
+ ASSERT(handler != NULL);
+ Dart_ServiceRequestCallback callback = handler->callback();
+ ASSERT(callback != NULL);
+ const char* r = NULL;
+ const char* name = js->method();
+ const char** keys = js->param_keys();
+ const char** values = js->param_values();
+ r = callback(name, keys, values, js->num_params(), handler->user_data());
+ ASSERT(r != NULL);
+ // TODO(johnmccutchan): Allow for NULL returns?
+ TextBuffer* buffer = js->buffer();
+ buffer->AddString(r);
+ free(const_cast<char*>(r));
+}
+
+
+void Service::RegisterIsolateEmbedderCallback(
+ const char* name,
+ Dart_ServiceRequestCallback callback,
+ void* user_data) {
+ if (name == NULL) {
+ return;
+ }
+ EmbedderServiceHandler* handler = FindIsolateEmbedderHandler(name);
+ if (handler != NULL) {
+ // Update existing handler entry.
+ handler->set_callback(callback);
+ handler->set_user_data(user_data);
+ return;
+ }
+ // Create a new handler.
+ handler = new EmbedderServiceHandler(name);
+ handler->set_callback(callback);
+ handler->set_user_data(user_data);
+
+ // Insert into isolate_service_handler_head_ list.
+ handler->set_next(isolate_service_handler_head_);
+ isolate_service_handler_head_ = handler;
+}
+
+
+EmbedderServiceHandler* Service::FindIsolateEmbedderHandler(
+ const char* name) {
+ EmbedderServiceHandler* current = isolate_service_handler_head_;
+ while (current != NULL) {
+ if (strcmp(name, current->name()) == 0) {
+ return current;
+ }
+ current = current->next();
+ }
+ return NULL;
+}
+
+
+void Service::RegisterRootEmbedderCallback(
+ const char* name,
+ Dart_ServiceRequestCallback callback,
+ void* user_data) {
+ if (name == NULL) {
+ return;
+ }
+ EmbedderServiceHandler* handler = FindRootEmbedderHandler(name);
+ if (handler != NULL) {
+ // Update existing handler entry.
+ handler->set_callback(callback);
+ handler->set_user_data(user_data);
+ return;
+ }
+ // Create a new handler.
+ handler = new EmbedderServiceHandler(name);
+ handler->set_callback(callback);
+ handler->set_user_data(user_data);
+
+ // Insert into root_service_handler_head_ list.
+ handler->set_next(root_service_handler_head_);
+ root_service_handler_head_ = handler;
+}
+
+
+EmbedderServiceHandler* Service::FindRootEmbedderHandler(
+ const char* name) {
+ EmbedderServiceHandler* current = root_service_handler_head_;
+ while (current != NULL) {
+ if (strcmp(name, current->name()) == 0) {
+ return current;
+ }
+ current = current->next();
+ }
+ return NULL;
+}
+
+
+static const MethodParameter* get_isolate_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetIsolate(Isolate* isolate, JSONStream* js) {
+ isolate->PrintJSON(js, false);
+ return true;
+}
+
+
+static const MethodParameter* get_stack_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetStack(Isolate* isolate, JSONStream* js) {
+ DebuggerStackTrace* stack = isolate->debugger()->StackTrace();
+ JSONObject jsobj(js);
+ jsobj.AddProperty("type", "Stack");
+ JSONArray jsarr(&jsobj, "frames");
+ intptr_t num_frames = stack->Length();
+ for (intptr_t i = 0; i < num_frames; i++) {
+ ActivationFrame* frame = stack->FrameAt(i);
+ JSONObject jsobj(&jsarr);
+ frame->PrintToJSONObject(&jsobj);
+ // TODO(turnidge): Implement depth differently -- differentiate
+ // inlined frames.
+ jsobj.AddProperty("depth", i);
+ }
+ return true;
+}
+
+
+static bool HandleCommonEcho(JSONObject* jsobj, JSONStream* js) {
+ jsobj->AddProperty("type", "_EchoResponse");
+ if (js->HasParam("text")) {
+ jsobj->AddProperty("text", js->LookupParam("text"));
+ }
+ return true;
+}
+
+
+void Service::SendEchoEvent(Isolate* isolate, const char* text) {
+ JSONStream js;
+ {
+ JSONObject jsobj(&js);
+ jsobj.AddProperty("type", "ServiceEvent");
+ jsobj.AddProperty("eventType", "_Echo");
+ jsobj.AddProperty("isolate", isolate);
+ if (text != NULL) {
+ jsobj.AddProperty("text", text);
+ }
+ }
+ const String& message = String::Handle(String::New(js.ToCString()));
+ uint8_t data[] = {0, 128, 255};
+ // TODO(koda): Add 'testing' event family.
+ SendEvent(kEventFamilyDebug, message, data, sizeof(data));
+}
+
+
+static bool _TriggerEchoEvent(Isolate* isolate, JSONStream* js) {
+ Service::SendEchoEvent(isolate, js->LookupParam("text"));
+ JSONObject jsobj(js);
+ return HandleCommonEcho(&jsobj, js);
+}
+
+
+static bool _Echo(Isolate* isolate, JSONStream* js) {
+ JSONObject jsobj(js);
+ return HandleCommonEcho(&jsobj, js);
+}
+
+
static bool ContainsNonInstance(const Object& obj) {
if (obj.IsArray()) {
const Array& array = Array::Cast(obj);
@@ -1596,8 +1242,13 @@
}
-static bool HandleIsolateGetInboundReferences(Isolate* isolate,
- JSONStream* js) {
+static const MethodParameter* get_inbound_references_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetInboundReferences(Isolate* isolate, JSONStream* js) {
const char* target_id = js->LookupParam("targetId");
if (target_id == NULL) {
PrintMissingParamError(js, "targetId");
@@ -1694,8 +1345,14 @@
return true;
}
-static bool HandleIsolateGetRetainingPath(Isolate* isolate,
- JSONStream* js) {
+
+static const MethodParameter* get_retaining_path_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetRetainingPath(Isolate* isolate, JSONStream* js) {
const char* target_id = js->LookupParam("targetId");
if (target_id == NULL) {
PrintMissingParamError(js, "targetId");
@@ -1737,7 +1394,13 @@
}
-static bool HandleIsolateGetRetainedSize(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_retained_size_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetRetainedSize(Isolate* isolate, JSONStream* js) {
const char* target_id = js->LookupParam("targetId");
if (target_id == NULL) {
PrintMissingParamError(js, "targetId");
@@ -1784,7 +1447,13 @@
}
-static bool HandleIsolateEval(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* eval_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool Eval(Isolate* isolate, JSONStream* js) {
const char* target_id = js->LookupParam("targetId");
if (target_id == NULL) {
PrintMissingParamError(js, "targetId");
@@ -1844,6 +1513,43 @@
}
+static const MethodParameter* get_call_site_data_params[] = {
+ ISOLATE_PARAMETER,
+ new IdParameter("targetId", true),
+ NULL,
+};
+
+
+static bool GetCallSiteData(Isolate* isolate, JSONStream* js) {
+ const char* target_id = js->LookupParam("targetId");
+ Object& obj = Object::Handle(LookupHeapObject(isolate, target_id, NULL));
+ if (obj.raw() == Object::sentinel().raw()) {
+ PrintInvalidParamError(js, "targetId");
+ return true;
+ }
+ if (obj.IsFunction()) {
+ const Function& func = Function::Cast(obj);
+ const GrowableObjectArray& ics =
+ GrowableObjectArray::Handle(func.CollectICsWithSourcePositions());
+ JSONObject jsobj(js);
+ jsobj.AddProperty("type", "_CallSiteData");
+ jsobj.AddProperty("function", func);
+ JSONArray elements(&jsobj, "callSites");
+ Smi& line = Smi::Handle();
+ Smi& column = Smi::Handle();
+ ICData& ic_data = ICData::Handle();
+ for (intptr_t i = 0; i < ics.Length();) {
+ ic_data ^= ics.At(i++);
+ line ^= ics.At(i++);
+ column ^= ics.At(i++);
+ ic_data.PrintToJSONArray(&elements, line.Value(), column.Value());
+ }
+ return true;
+ }
+ return false;
+}
+
+
class GetInstancesVisitor : public ObjectGraph::Visitor {
public:
GetInstancesVisitor(const Class& cls, const Array& storage)
@@ -1876,7 +1582,13 @@
};
-static bool HandleIsolateGetInstances(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_instances_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetInstances(Isolate* isolate, JSONStream* js) {
const char* target_id = js->LookupParam("classId");
if (target_id == NULL) {
PrintMissingParamError(js, "classId");
@@ -1922,7 +1634,70 @@
}
-static bool HandleIsolateGetCoverage(Isolate* isolate, JSONStream* js) {
+class LibraryCoverageFilter : public CoverageFilter {
+ public:
+ explicit LibraryCoverageFilter(const Library& lib) : lib_(lib) {}
+ bool ShouldOutputCoverageFor(const Library& lib,
+ const Script& script,
+ const Class& cls,
+ const Function& func) const {
+ return lib.raw() == lib_.raw();
+ }
+ private:
+ const Library& lib_;
+};
+
+
+class ScriptCoverageFilter : public CoverageFilter {
+ public:
+ explicit ScriptCoverageFilter(const Script& script)
+ : script_(script) {}
+ bool ShouldOutputCoverageFor(const Library& lib,
+ const Script& script,
+ const Class& cls,
+ const Function& func) const {
+ return script.raw() == script_.raw();
+ }
+ private:
+ const Script& script_;
+};
+
+
+class ClassCoverageFilter : public CoverageFilter {
+ public:
+ explicit ClassCoverageFilter(const Class& cls) : cls_(cls) {}
+ bool ShouldOutputCoverageFor(const Library& lib,
+ const Script& script,
+ const Class& cls,
+ const Function& func) const {
+ return cls.raw() == cls_.raw();
+ }
+ private:
+ const Class& cls_;
+};
+
+
+class FunctionCoverageFilter : public CoverageFilter {
+ public:
+ explicit FunctionCoverageFilter(const Function& func) : func_(func) {}
+ bool ShouldOutputCoverageFor(const Library& lib,
+ const Script& script,
+ const Class& cls,
+ const Function& func) const {
+ return func.raw() == func_.raw();
+ }
+ private:
+ const Function& func_;
+};
+
+
+static const MethodParameter* get_coverage_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetCoverage(Isolate* isolate, JSONStream* js) {
if (!js->HasParam("targetId")) {
CodeCoverage::PrintJSON(isolate, js, NULL);
return true;
@@ -1960,21 +1735,21 @@
}
-static bool HandleIsolateAddBreakpoint(Isolate* isolate, JSONStream* js) {
- if (!js->HasParam("line")) {
- PrintMissingParamError(js, "line");
- return true;
- }
+static const MethodParameter* add_breakpoint_params[] = {
+ ISOLATE_PARAMETER,
+ new IdParameter("scriptId", true),
+ new UIntParameter("line", true),
+ NULL,
+};
+
+
+static bool AddBreakpoint(Isolate* isolate, JSONStream* js) {
const char* line_param = js->LookupParam("line");
- intptr_t line = -1;
- if (!GetIntegerId(line_param, &line)) {
- PrintInvalidParamError(js, "line");
- return true;
- }
- const char* script_id = js->LookupParam("script");
+ intptr_t line = UIntParameter::Parse(line_param);
+ const char* script_id = js->LookupParam("scriptId");
Object& obj = Object::Handle(LookupHeapObject(isolate, script_id, NULL));
if (obj.raw() == Object::sentinel().raw() || !obj.IsScript()) {
- PrintInvalidParamError(js, "script");
+ PrintInvalidParamError(js, "scriptId");
return true;
}
const Script& script = Script::Cast(obj);
@@ -1990,7 +1765,41 @@
}
-static bool HandleIsolateRemoveBreakpoint(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* add_breakpoint_at_entry_params[] = {
+ ISOLATE_PARAMETER,
+ new IdParameter("functionId", true),
+ NULL,
+};
+
+
+static bool AddBreakpointAtEntry(Isolate* isolate, JSONStream* js) {
+ const char* function_id = js->LookupParam("functionId");
+ Object& obj = Object::Handle(LookupHeapObject(isolate, function_id, NULL));
+ if (obj.raw() == Object::sentinel().raw() || !obj.IsFunction()) {
+ PrintInvalidParamError(js, "functionId");
+ return true;
+ }
+ const Function& function = Function::Cast(obj);
+ SourceBreakpoint* bpt =
+ isolate->debugger()->SetBreakpointAtEntry(function);
+ if (bpt == NULL) {
+ const String& funcName = String::Handle(function.PrettyName());
+ PrintError(js, "Unable to set breakpoint at function '%s'",
+ funcName.ToCString());
+ return true;
+ }
+ bpt->PrintJSON(js);
+ return true;
+}
+
+
+static const MethodParameter* remove_breakpoint_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool RemoveBreakpoint(Isolate* isolate, JSONStream* js) {
if (!js->HasParam("breakpointId")) {
PrintMissingParamError(js, "breakpointId");
return true;
@@ -2004,7 +1813,6 @@
}
isolate->debugger()->RemoveBreakpoint(bpt->id());
- fprintf(stderr, "SUCCESS");
// TODO(turnidge): Consider whether the 'Success' type is proper.
JSONObject jsobj(js);
jsobj.AddProperty("type", "Success");
@@ -2027,6 +1835,7 @@
}
+
static bool HandleNativeMetricsList(Isolate* isolate, JSONStream* js) {
JSONObject obj(js);
obj.AddProperty("type", "MetricList");
@@ -2107,7 +1916,13 @@
}
-static bool HandleIsolateGetMetricList(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_isolate_metric_list_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetIsolateMetricList(Isolate* isolate, JSONStream* js) {
bool native_metrics = false;
if (js->HasParam("type")) {
if (js->ParamIs("type", "Native")) {
@@ -2129,7 +1944,13 @@
}
-static bool HandleIsolateGetMetric(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_isolate_metric_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetIsolateMetric(Isolate* isolate, JSONStream* js) {
const char* metric_id = js->LookupParam("metricId");
if (metric_id == NULL) {
PrintMissingParamError(js, "metricId");
@@ -2155,12 +1976,24 @@
}
-static bool HandleVMGetMetricList(JSONStream* js) {
+static const MethodParameter* get_vm_metric_list_params[] = {
+ NO_ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetVMMetricList(Isolate* isolate, JSONStream* js) {
return false;
}
-static bool HandleVMGetMetric(JSONStream* js) {
+static const MethodParameter* get_vm_metric_params[] = {
+ NO_ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetVMMetric(Isolate* isolate, JSONStream* js) {
const char* metric_id = js->LookupParam("metricId");
if (metric_id == NULL) {
PrintMissingParamError(js, "metricId");
@@ -2169,7 +2002,13 @@
}
-static bool HandleIsolateResume(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* resume_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool Resume(Isolate* isolate, JSONStream* js) {
const char* step_param = js->LookupParam("step");
if (isolate->message_handler()->paused_on_start()) {
isolate->message_handler()->set_pause_on_start(false);
@@ -2215,7 +2054,13 @@
}
-static bool HandleIsolateGetBreakpoints(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_breakpoints_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetBreakpoints(Isolate* isolate, JSONStream* js) {
JSONObject jsobj(js);
jsobj.AddProperty("type", "BreakpointList");
JSONArray jsarr(&jsobj, "breakpoints");
@@ -2224,7 +2069,13 @@
}
-static bool HandleIsolatePause(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* pause_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool Pause(Isolate* isolate, JSONStream* js) {
// TODO(turnidge): Don't double-interrupt the isolate here.
isolate->ScheduleInterrupts(Isolate::kApiInterrupt);
JSONObject jsobj(js);
@@ -2234,7 +2085,13 @@
}
-static bool HandleIsolateGetTagProfile(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_tag_profile_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetTagProfile(Isolate* isolate, JSONStream* js) {
JSONObject miniProfile(js);
miniProfile.AddProperty("type", "TagProfile");
miniProfile.AddProperty("id", "profile/tag");
@@ -2242,31 +2099,49 @@
return true;
}
-static bool HandleIsolateGetCpuProfile(Isolate* isolate, JSONStream* js) {
- ProfilerService::TagOrder tag_order = ProfilerService::kUserVM;
- if (js->HasParam("tags")) {
- if (js->ParamIs("tags", "None")) {
- tag_order = ProfilerService::kNoTags;
- } else if (js->ParamIs("tags", "UserVM")) {
- tag_order = ProfilerService::kUserVM;
- } else if (js->ParamIs("tags", "UserOnly")) {
- tag_order = ProfilerService::kUser;
- } else if (js->ParamIs("tags", "VMUser")) {
- tag_order = ProfilerService::kVMUser;
- } else if (js->ParamIs("tags", "VMOnly")) {
- tag_order = ProfilerService::kVM;
- } else {
- PrintInvalidParamError(js, "tags");
- return true;
- }
- }
+
+static const char* tags_enum_names[] = {
+ "None",
+ "UserVM",
+ "UserOnly",
+ "VMUser",
+ "VMOnly",
+ NULL,
+};
+
+
+static ProfilerService::TagOrder tags_enum_values[] = {
+ ProfilerService::kNoTags,
+ ProfilerService::kUserVM,
+ ProfilerService::kUser,
+ ProfilerService::kVMUser,
+ ProfilerService::kVM,
+ ProfilerService::kNoTags, // Default value.
+};
+
+
+static const MethodParameter* get_cpu_profile_params[] = {
+ ISOLATE_PARAMETER,
+ new EnumParameter("tags", true, tags_enum_names),
+ NULL,
+};
+
+
+static bool GetCpuProfile(Isolate* isolate, JSONStream* js) {
+ ProfilerService::TagOrder tag_order =
+ EnumMapper(js->LookupParam("tags"), tags_enum_names, tags_enum_values);
ProfilerService::PrintJSON(js, tag_order);
return true;
}
-static bool HandleIsolateGetAllocationProfile(Isolate* isolate,
- JSONStream* js) {
+static const MethodParameter* get_allocation_profile_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetAllocationProfile(Isolate* isolate, JSONStream* js) {
bool should_reset_accumulator = false;
bool should_collect = false;
if (js->HasParam("reset")) {
@@ -2298,13 +2173,25 @@
}
-static bool HandleIsolateGetHeapMap(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_heap_map_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetHeapMap(Isolate* isolate, JSONStream* js) {
isolate->heap()->PrintHeapMapToJSONStream(isolate, js);
return true;
}
-static bool HandleIsolateRequestHeapSnapshot(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* request_heap_snapshot_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool RequestHeapSnapshot(Isolate* isolate, JSONStream* js) {
Service::SendGraphEvent(isolate);
// TODO(koda): Provide some id that ties this request to async response(s).
JSONObject jsobj(js);
@@ -2354,7 +2241,13 @@
};
-static bool HandleIsolateGetObjectByAddress(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_object_by_address_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetObjectByAddress(Isolate* isolate, JSONStream* js) {
const char* addr_str = js->LookupParam("address");
if (addr_str == NULL) {
PrintMissingParamError(js, "address");
@@ -2379,8 +2272,8 @@
}
-static bool HandleIsolateRespondWithMalformedJson(Isolate* isolate,
- JSONStream* js) {
+static bool _RespondWithMalformedJson(Isolate* isolate,
+ JSONStream* js) {
JSONObject jsobj(js);
jsobj.AddProperty("a", "a");
JSONObject jsobj1(js);
@@ -2393,15 +2286,21 @@
}
-static bool HandleIsolateRespondWithMalformedObject(Isolate* isolate,
- JSONStream* js) {
+static bool _RespondWithMalformedObject(Isolate* isolate,
+ JSONStream* js) {
JSONObject jsobj(js);
jsobj.AddProperty("bart", "simpson");
return true;
}
-static bool HandleIsolateGetObject(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_object_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetObject(Isolate* isolate, JSONStream* js) {
const char* id = js->LookupParam("objectId");
if (id == NULL) {
PrintMissingParamError(js, "objectId");
@@ -2436,7 +2335,13 @@
}
-static bool HandleIsolateGetClassList(Isolate* isolate, JSONStream* js) {
+static const MethodParameter* get_class_list_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetClassList(Isolate* isolate, JSONStream* js) {
ClassTable* table = isolate->class_table();
JSONObject jsobj(js);
table->PrintToJSONObject(&jsobj);
@@ -2444,8 +2349,13 @@
}
-static bool HandleIsolateGetTypeArgumentsList(Isolate* isolate,
- JSONStream* js) {
+static const MethodParameter* get_type_arguments_list_params[] = {
+ ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetTypeArgumentsList(Isolate* isolate, JSONStream* js) {
bool only_with_instantiations = false;
if (js->ParamIs("onlyWithInstantiations", "true")) {
only_with_instantiations = true;
@@ -2473,122 +2383,6 @@
}
-static IsolateMessageHandlerEntry isolate_handlers_new[] = {
- { "getIsolate", HandleIsolate },
- { "getObject", HandleIsolateGetObject },
- { "getObjectByAddress", HandleIsolateGetObjectByAddress },
- { "getBreakpoints", HandleIsolateGetBreakpoints },
- { "pause", HandleIsolatePause },
- { "resume", HandleIsolateResume },
- { "getStack", HandleIsolateGetStack },
- { "getCpuProfile", HandleIsolateGetCpuProfile },
- { "getTagProfile", HandleIsolateGetTagProfile },
- { "getAllocationProfile", HandleIsolateGetAllocationProfile },
- { "getHeapMap", HandleIsolateGetHeapMap },
- { "addBreakpoint", HandleIsolateAddBreakpoint },
- { "removeBreakpoint", HandleIsolateRemoveBreakpoint },
- { "getCoverage", HandleIsolateGetCoverage },
- { "eval", HandleIsolateEval },
- { "getRetainedSize", HandleIsolateGetRetainedSize },
- { "getRetainingPath", HandleIsolateGetRetainingPath },
- { "getInboundReferences", HandleIsolateGetInboundReferences },
- { "getInstances", HandleIsolateGetInstances },
- { "requestHeapSnapshot", HandleIsolateRequestHeapSnapshot },
- { "getClassList", HandleIsolateGetClassList },
- { "getTypeArgumentsList", HandleIsolateGetTypeArgumentsList },
- { "getIsolateMetricList", HandleIsolateGetMetricList },
- { "getIsolateMetric", HandleIsolateGetMetric },
- { "_echo", HandleIsolateEcho },
- { "_triggerEchoEvent", HandleIsolateTriggerEchoEvent },
- { "_respondWithMalformedJson", HandleIsolateRespondWithMalformedJson },
- { "_respondWithMalformedObject", HandleIsolateRespondWithMalformedObject },
-};
-
-
-static IsolateMessageHandler FindIsolateMessageHandler(const char* method) {
- intptr_t num_message_handlers = sizeof(isolate_handlers_new) /
- sizeof(isolate_handlers_new[0]);
- for (intptr_t i = 0; i < num_message_handlers; i++) {
- const IsolateMessageHandlerEntry& entry = isolate_handlers_new[i];
- if (strcmp(method, entry.method) == 0) {
- return entry.handler;
- }
- }
- if (FLAG_trace_service) {
- OS::Print("Service has no isolate message handler for <%s>\n", method);
- }
- return NULL;
-}
-
-
-void Service::HandleRootMessage(const Instance& msg_instance) {
- Isolate* isolate = Isolate::Current();
- ASSERT(!msg_instance.IsNull());
- ASSERT(msg_instance.IsArray());
-
- {
- StackZone zone(isolate);
- HANDLESCOPE(isolate);
-
- const Array& msg = Array::Cast(msg_instance);
- ASSERT(msg.Length() == 5);
-
- Instance& reply_port = Instance::Handle(isolate);
- String& method = String::Handle(isolate);
- Array& param_keys = Array::Handle(isolate);
- Array& param_values = Array::Handle(isolate);
- reply_port ^= msg.At(1);
- method ^= msg.At(2);
- param_keys ^= msg.At(3);
- param_values ^= msg.At(4);
-
- ASSERT(!method.IsNull());
- ASSERT(!param_keys.IsNull());
- ASSERT(!param_values.IsNull());
- ASSERT(param_keys.Length() == param_values.Length());
-
- if (!reply_port.IsSendPort()) {
- FATAL("SendPort expected.");
- }
-
- RootMessageHandler handler =
- FindRootMessageHandler(method.ToCString());
- {
- JSONStream js;
- js.Setup(zone.GetZone(), SendPort::Cast(reply_port).Id(),
- method, param_keys, param_values);
- if (handler == NULL) {
- // Check for an embedder handler.
- EmbedderServiceHandler* e_handler =
- FindRootEmbedderHandler(method.ToCString());
- if (e_handler != NULL) {
- EmbedderHandleMessage(e_handler, &js);
- } else {
- if (FindIsolateMessageHandler(method.ToCString()) != NULL) {
- PrintMissingParamError(&js, "isolateId");
- } else {
- PrintError(&js, "Unrecognized method: %s", method.ToCString());
- }
- }
- js.PostReply();
- } else {
- if (handler(&js)) {
- // Handler returns true if the reply is ready to be posted.
- // TODO(johnmccutchan): Support asynchronous replies.
- js.PostReply();
- }
- }
- }
- }
-}
-
-
-static bool HandleRootEcho(JSONStream* js) {
- JSONObject jsobj(js);
- return HandleCommonEcho(&jsobj, js);
-}
-
-
class ServiceIsolateVisitor : public IsolateVisitor {
public:
explicit ServiceIsolateVisitor(JSONArray* jsarr)
@@ -2598,7 +2392,8 @@
virtual ~ServiceIsolateVisitor() {}
void VisitIsolate(Isolate* isolate) {
- if (isolate != Dart::vm_isolate() && !Service::IsServiceIsolate(isolate)) {
+ if ((isolate != Dart::vm_isolate()) &&
+ !ServiceIsolate::IsServiceIsolate(isolate)) {
jsarr_->AddValue(isolate);
}
}
@@ -2608,8 +2403,13 @@
};
-static bool HandleVM(JSONStream* js) {
- Isolate* isolate = Isolate::Current();
+static const MethodParameter* get_vm_params[] = {
+ NO_ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetVM(Isolate* isolate, JSONStream* js) {
JSONObject jsobj(js);
jsobj.AddProperty("type", "VM");
jsobj.AddProperty("id", "vm");
@@ -2640,13 +2440,25 @@
}
-static bool HandleVMFlagList(JSONStream* js) {
+static const MethodParameter* get_flag_list_params[] = {
+ NO_ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool GetFlagList(Isolate* isolate, JSONStream* js) {
Flags::PrintJSON(js);
return true;
}
-static bool HandleVMSetFlag(JSONStream* js) {
+static const MethodParameter* set_flags_params[] = {
+ NO_ISOLATE_PARAMETER,
+ NULL,
+};
+
+
+static bool SetFlag(Isolate* isolate, JSONStream* js) {
const char* flag_name = js->LookupParam("name");
if (flag_name == NULL) {
PrintMissingParamError(js, "name");
@@ -2672,198 +2484,91 @@
}
-static RootMessageHandlerEntry root_handlers_new[] = {
- { "getVM", HandleVM },
- { "getFlagList", HandleVMFlagList },
- { "setFlag", HandleVMSetFlag },
- { "getVMMetricList", HandleVMGetMetricList },
- { "getVMMetric", HandleVMGetMetric },
- { "_echo", HandleRootEcho },
+static ServiceMethodDescriptor service_methods_[] = {
+ { "_echo", _Echo,
+ NULL },
+ { "_respondWithMalformedJson", _RespondWithMalformedJson,
+ NULL },
+ { "_respondWithMalformedObject", _RespondWithMalformedObject,
+ NULL },
+ { "_triggerEchoEvent", _TriggerEchoEvent,
+ NULL },
+ { "addBreakpoint", AddBreakpoint,
+ add_breakpoint_params },
+ { "addBreakpointAtEntry", AddBreakpointAtEntry,
+ add_breakpoint_at_entry_params },
+ { "eval", Eval,
+ eval_params },
+ { "getAllocationProfile", GetAllocationProfile,
+ get_allocation_profile_params },
+ { "getBreakpoints", GetBreakpoints,
+ get_breakpoints_params },
+ { "getCallSiteData", GetCallSiteData,
+ get_call_site_data_params },
+ { "getClassList", GetClassList,
+ get_class_list_params },
+ { "getCoverage", GetCoverage,
+ get_coverage_params },
+ { "getCpuProfile", GetCpuProfile,
+ get_cpu_profile_params },
+ { "getFlagList", GetFlagList ,
+ get_flag_list_params },
+ { "getHeapMap", GetHeapMap,
+ get_heap_map_params },
+ { "getInboundReferences", GetInboundReferences,
+ get_inbound_references_params },
+ { "getInstances", GetInstances,
+ get_instances_params },
+ { "getIsolate", GetIsolate,
+ get_isolate_params },
+ { "getIsolateMetric", GetIsolateMetric,
+ get_isolate_metric_params },
+ { "getIsolateMetricList", GetIsolateMetricList,
+ get_isolate_metric_list_params },
+ { "getObject", GetObject,
+ get_object_params },
+ { "getObjectByAddress", GetObjectByAddress,
+ get_object_by_address_params },
+ { "getRetainedSize", GetRetainedSize,
+ get_retained_size_params },
+ { "getRetainingPath", GetRetainingPath,
+ get_retaining_path_params },
+ { "getStack", GetStack,
+ get_stack_params },
+ { "getTagProfile", GetTagProfile,
+ get_tag_profile_params },
+ { "getTypeArgumentsList", GetTypeArgumentsList,
+ get_type_arguments_list_params },
+ { "getVM", GetVM,
+ get_vm_params },
+ { "getVMMetric", GetVMMetric,
+ get_vm_metric_params },
+ { "getVMMetricList", GetVMMetricList,
+ get_vm_metric_list_params },
+ { "pause", Pause,
+ pause_params },
+ { "removeBreakpoint", RemoveBreakpoint,
+ remove_breakpoint_params },
+ { "resume", Resume,
+ resume_params },
+ { "requestHeapSnapshot", RequestHeapSnapshot,
+ request_heap_snapshot_params },
+ { "setFlag", SetFlag ,
+ set_flags_params },
};
-static RootMessageHandler FindRootMessageHandler(const char* method) {
- intptr_t num_message_handlers = sizeof(root_handlers_new) /
- sizeof(root_handlers_new[0]);
- for (intptr_t i = 0; i < num_message_handlers; i++) {
- const RootMessageHandlerEntry& entry = root_handlers_new[i];
- if (strcmp(method, entry.method) == 0) {
- return entry.handler;
+ServiceMethodDescriptor* FindMethod(const char* method_name) {
+ intptr_t num_methods = sizeof(service_methods_) /
+ sizeof(service_methods_[0]);
+ for (intptr_t i = 0; i < num_methods; i++) {
+ ServiceMethodDescriptor& method = service_methods_[i];
+ if (strcmp(method_name, method.name) == 0) {
+ return &method;
}
}
- if (FLAG_trace_service) {
- OS::Print("vm-service: No root message handler for <%s>.\n", method);
- }
return NULL;
}
-void Service::SendEvent(intptr_t eventId, const Object& eventMessage) {
- if (!IsRunning()) {
- return;
- }
- Isolate* isolate = Isolate::Current();
- ASSERT(isolate != NULL);
- HANDLESCOPE(isolate);
-
- // Construct a list of the form [eventId, eventMessage].
- const Array& list = Array::Handle(Array::New(2));
- ASSERT(!list.IsNull());
- list.SetAt(0, Integer::Handle(Integer::New(eventId)));
- list.SetAt(1, eventMessage);
-
- // Push the event to port_.
- uint8_t* data = NULL;
- MessageWriter writer(&data, &allocator, false);
- writer.WriteMessage(list);
- intptr_t len = writer.BytesWritten();
- if (FLAG_trace_service) {
- OS::Print("vm-service: Pushing event of type %" Pd ", len %" Pd "\n",
- eventId, len);
- }
- // TODO(turnidge): For now we ignore failure to send an event. Revisit?
- PortMap::PostMessage(
- new Message(service_port_, data, len, Message::kNormalPriority));
-}
-
-
-void Service::SendEvent(intptr_t eventId,
- const String& meta,
- const uint8_t* data,
- intptr_t size) {
- // Bitstream: [meta data size (big-endian 64 bit)] [meta data (UTF-8)] [data]
- const intptr_t meta_bytes = Utf8::Length(meta);
- const intptr_t total_bytes = sizeof(uint64_t) + meta_bytes + size;
- const TypedData& message = TypedData::Handle(
- TypedData::New(kTypedDataUint8ArrayCid, total_bytes));
- intptr_t offset = 0;
- // TODO(koda): Rename these methods SetHostUint64, etc.
- message.SetUint64(0, Utils::HostToBigEndian64(meta_bytes));
- offset += sizeof(uint64_t);
- {
- NoGCScope no_gc;
- meta.ToUTF8(static_cast<uint8_t*>(message.DataAddr(offset)), meta_bytes);
- offset += meta_bytes;
- }
- // TODO(koda): It would be nice to avoid this copy (requires changes to
- // MessageWriter code).
- {
- NoGCScope no_gc;
- memmove(message.DataAddr(offset), data, size);
- offset += size;
- }
- ASSERT(offset == total_bytes);
- SendEvent(eventId, message);
-}
-
-
-void Service::HandleGCEvent(GCEvent* event) {
- JSONStream js;
- event->PrintJSON(&js);
- const String& message = String::Handle(String::New(js.ToCString()));
- SendEvent(kEventFamilyGC, message);
-}
-
-
-void Service::HandleDebuggerEvent(DebuggerEvent* event) {
- JSONStream js;
- event->PrintJSON(&js);
- const String& message = String::Handle(String::New(js.ToCString()));
- SendEvent(kEventFamilyDebug, message);
-}
-
-
-void Service::EmbedderHandleMessage(EmbedderServiceHandler* handler,
- JSONStream* js) {
- ASSERT(handler != NULL);
- Dart_ServiceRequestCallback callback = handler->callback();
- ASSERT(callback != NULL);
- const char* r = NULL;
- const char* name = js->method();
- const char** keys = js->param_keys();
- const char** values = js->param_values();
- r = callback(name, keys, values, js->num_params(), handler->user_data());
- ASSERT(r != NULL);
- // TODO(johnmccutchan): Allow for NULL returns?
- TextBuffer* buffer = js->buffer();
- buffer->AddString(r);
- free(const_cast<char*>(r));
-}
-
-
-void Service::RegisterIsolateEmbedderCallback(
- const char* name,
- Dart_ServiceRequestCallback callback,
- void* user_data) {
- if (name == NULL) {
- return;
- }
- EmbedderServiceHandler* handler = FindIsolateEmbedderHandler(name);
- if (handler != NULL) {
- // Update existing handler entry.
- handler->set_callback(callback);
- handler->set_user_data(user_data);
- return;
- }
- // Create a new handler.
- handler = new EmbedderServiceHandler(name);
- handler->set_callback(callback);
- handler->set_user_data(user_data);
-
- // Insert into isolate_service_handler_head_ list.
- handler->set_next(isolate_service_handler_head_);
- isolate_service_handler_head_ = handler;
-}
-
-
-EmbedderServiceHandler* Service::FindIsolateEmbedderHandler(
- const char* name) {
- EmbedderServiceHandler* current = isolate_service_handler_head_;
- while (current != NULL) {
- if (strcmp(name, current->name()) == 0) {
- return current;
- }
- current = current->next();
- }
- return NULL;
-}
-
-
-void Service::RegisterRootEmbedderCallback(
- const char* name,
- Dart_ServiceRequestCallback callback,
- void* user_data) {
- if (name == NULL) {
- return;
- }
- EmbedderServiceHandler* handler = FindRootEmbedderHandler(name);
- if (handler != NULL) {
- // Update existing handler entry.
- handler->set_callback(callback);
- handler->set_user_data(user_data);
- return;
- }
- // Create a new handler.
- handler = new EmbedderServiceHandler(name);
- handler->set_callback(callback);
- handler->set_user_data(user_data);
-
- // Insert into root_service_handler_head_ list.
- handler->set_next(root_service_handler_head_);
- root_service_handler_head_ = handler;
-}
-
-
-EmbedderServiceHandler* Service::FindRootEmbedderHandler(
- const char* name) {
- EmbedderServiceHandler* current = root_service_handler_head_;
- while (current != NULL) {
- if (strcmp(name, current->name()) == 0) {
- return current;
- }
- current = current->next();
- }
- return NULL;
-}
-
} // namespace dart
diff --git a/runtime/vm/service.h b/runtime/vm/service.h
index 2af9b2d..2a9078f 100644
--- a/runtime/vm/service.h
+++ b/runtime/vm/service.h
@@ -25,39 +25,16 @@
class Service : public AllStatic {
public:
- static const char* kIsolateName;
- static bool IsServiceIsolateName(const char* name);
-
// Handles a message which is not directed to an isolate.
- static void HandleRootMessage(const Instance& message);
+ static void HandleRootMessage(const Array& message);
// Handles a message which is directed to a particular isolate.
static void HandleIsolateMessage(Isolate* isolate, const Array& message);
- static Isolate* GetServiceIsolate(void* callback_data);
- static bool SendIsolateStartupMessage();
- static bool SendIsolateShutdownMessage();
-
- static bool IsRunning();
- static void SetServicePort(Dart_Port port);
- static void SetServiceIsolate(Isolate* isolate);
- static bool HasServiceIsolate();
- static bool IsServiceIsolate(Isolate* isolate);
-
- static Dart_Port WaitForLoadPort();
- static Dart_Port LoadPort();
- static void SetLoadPort(Dart_Port port);
-
+ static bool EventMaskHas(uint32_t mask);
static void SetEventMask(uint32_t mask);
-
- // Is the service interested in debugger events?
- static bool NeedsDebuggerEvents() {
- return IsRunning() && ((event_mask_ & kEventFamilyDebugMask) != 0);
- }
- // Is the service interested in garbage collection events?
- static bool NeedsGCEvents() {
- return IsRunning() && ((event_mask_ & kEventFamilyGCMask) != 0);
- }
+ static bool NeedsDebuggerEvents();
+ static bool NeedsGCEvents();
static void HandleDebuggerEvent(DebuggerEvent* event);
static void HandleGCEvent(GCEvent* event);
@@ -75,17 +52,9 @@
static void SendEchoEvent(Isolate* isolate, const char* text);
static void SendGraphEvent(Isolate* isolate);
- static void MaybeInjectVMServiceLibrary(Isolate* isolate);
-
- static void RunService();
-
- static void FinishedInitializing();
-
- static Dart_IsolateCreateCallback create_callback() {
- return create_callback_;
- }
-
private:
+ static void InvokeMethod(Isolate* isolate, const Array& message);
+
// These must be kept in sync with service/constants.dart
static const int kEventFamilyDebug = 0;
static const int kEventFamilyGC = 1;
@@ -97,9 +66,6 @@
static EmbedderServiceHandler* FindIsolateEmbedderHandler(const char* name);
static EmbedderServiceHandler* FindRootEmbedderHandler(const char* name);
- static Dart_Handle GetSource(const char* name);
- static Dart_Handle LibraryTagHandler(Dart_LibraryTag tag, Dart_Handle library,
- Dart_Handle url);
static void SendEvent(intptr_t eventId, const Object& eventMessage);
// Does not take ownership of 'data'.
@@ -111,13 +77,6 @@
static EmbedderServiceHandler* isolate_service_handler_head_;
static EmbedderServiceHandler* root_service_handler_head_;
-
- static Dart_IsolateCreateCallback create_callback_;
- static Monitor* monitor_;
- static bool initializing_;
- static Isolate* service_isolate_;
- static Dart_Port service_port_;
- static Dart_Port load_port_;
static uint32_t event_mask_;
};
diff --git a/runtime/vm/service/message.dart b/runtime/vm/service/message.dart
index 011d57d..2b3f038 100644
--- a/runtime/vm/service/message.dart
+++ b/runtime/vm/service/message.dart
@@ -34,6 +34,20 @@
params.addAll(rpcParams);
}
+ static String _methodNameFromUri(Uri uri) {
+ if (uri == null) {
+ return '';
+ }
+ if (uri.pathSegments.length == 0) {
+ return '';
+ }
+ return uri.pathSegments[0];
+ }
+
+ Message.fromUri(Uri uri) : method = _methodNameFromUri(uri) {
+ params.addAll(uri.queryParameters);
+ }
+
dynamic toJson() {
return {
'path': path,
diff --git a/runtime/vm/service/running_isolates.dart b/runtime/vm/service/running_isolates.dart
index 7766491..12ca0b7 100644
--- a/runtime/vm/service/running_isolates.dart
+++ b/runtime/vm/service/running_isolates.dart
@@ -33,7 +33,7 @@
return message.response;
}
isolateParam = isolateParam.substring('isolates/'.length);
- if (isolateParam == 'isolates/root') {
+ if (isolateParam == 'root') {
isolateId = _rootPortId;
} else {
try {
diff --git a/runtime/vm/service/service.idl b/runtime/vm/service/service.idl
index 0edb79b..2764e23 100644
--- a/runtime/vm/service/service.idl
+++ b/runtime/vm/service/service.idl
@@ -24,6 +24,10 @@
scriptId string,
line string) Breakpoint
+ // Adds a breakpoint at the entrypoint of the specified function.
+ addBreakpointAtEntry(isolateId string,
+ functionId string) Breakpoint
+
// Removes the specified breakpoint
removeBreakpoint(isolateId string, breakpointId string) Response
@@ -46,6 +50,9 @@
// or function.
getCoverage(isolateId string, targetId string) CodeCoverage
+ // Returns call site cache information for a function.
+ getCallSiteData(isolateId string, targetId string) _CallSiteData
+
// Returns a full cpu profile for an isolate.
//
// <code>tagSelector</code> is optional with default 'UserVM'.
@@ -273,6 +280,26 @@
placeholder int
}
+
+struct _CacheEntry {
+ receiverClass ClassRef
+ count int
+}
+
+
+struct _CallSite {
+ name string
+ line int
+ column int
+ cacheEntries []_CacheEntry
+}
+
+
+struct _CallSiteData extends Response {
+ function FunctionRef
+ callSites []_CallSite
+}
+
// A <code>TagProfile</code> is a limited profile encoded as parallel
// arrays of tag names and tag values.
struct TagProfile extends Response {
diff --git a/runtime/vm/service_isolate.cc b/runtime/vm/service_isolate.cc
new file mode 100644
index 0000000..fd82c5a9
--- /dev/null
+++ b/runtime/vm/service_isolate.cc
@@ -0,0 +1,686 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+#include "vm/service_isolate.h"
+
+#include "vm/compiler.h"
+#include "vm/dart_api_impl.h"
+#include "vm/dart_entry.h"
+#include "vm/isolate.h"
+#include "vm/lockers.h"
+#include "vm/message.h"
+#include "vm/message_handler.h"
+#include "vm/native_entry.h"
+#include "vm/native_arguments.h"
+#include "vm/object.h"
+#include "vm/object_store.h"
+#include "vm/port.h"
+#include "vm/service.h"
+#include "vm/symbols.h"
+#include "vm/thread_pool.h"
+
+namespace dart {
+
+DEFINE_FLAG(bool, trace_service, false, "Trace VM service requests.");
+DEFINE_FLAG(bool, trace_service_pause_events, false,
+ "Trace VM service isolate pause events.");
+
+struct ResourcesEntry {
+ const char* path_;
+ const char* resource_;
+ int length_;
+};
+
+extern ResourcesEntry __service_resources_[];
+
+class Resources {
+ public:
+ static const int kNoSuchInstance = -1;
+ static int ResourceLookup(const char* path, const char** resource) {
+ ResourcesEntry* table = ResourceTable();
+ for (int i = 0; table[i].path_ != NULL; i++) {
+ const ResourcesEntry& entry = table[i];
+ if (strcmp(path, entry.path_) == 0) {
+ *resource = entry.resource_;
+ ASSERT(entry.length_ > 0);
+ return entry.length_;
+ }
+ }
+ return kNoSuchInstance;
+ }
+
+ static const char* Path(int idx) {
+ ASSERT(idx >= 0);
+ ResourcesEntry* entry = At(idx);
+ if (entry == NULL) {
+ return NULL;
+ }
+ ASSERT(entry->path_ != NULL);
+ return entry->path_;
+ }
+
+ static int Length(int idx) {
+ ASSERT(idx >= 0);
+ ResourcesEntry* entry = At(idx);
+ if (entry == NULL) {
+ return kNoSuchInstance;
+ }
+ ASSERT(entry->path_ != NULL);
+ return entry->length_;
+ }
+
+ static const uint8_t* Resource(int idx) {
+ ASSERT(idx >= 0);
+ ResourcesEntry* entry = At(idx);
+ if (entry == NULL) {
+ return NULL;
+ }
+ return reinterpret_cast<const uint8_t*>(entry->resource_);
+ }
+
+ private:
+ static ResourcesEntry* At(int idx) {
+ ASSERT(idx >= 0);
+ ResourcesEntry* table = ResourceTable();
+ for (int i = 0; table[i].path_ != NULL; i++) {
+ if (idx == i) {
+ return &table[i];
+ }
+ }
+ return NULL;
+ }
+
+ static ResourcesEntry* ResourceTable() {
+ return &__service_resources_[0];
+ }
+
+ DISALLOW_ALLOCATION();
+ DISALLOW_IMPLICIT_CONSTRUCTORS(Resources);
+};
+
+
+static uint8_t* allocator(uint8_t* ptr, intptr_t old_size, intptr_t new_size) {
+ void* new_ptr = realloc(reinterpret_cast<void*>(ptr), new_size);
+ return reinterpret_cast<uint8_t*>(new_ptr);
+}
+
+
+static Dart_Port ExtractPort(Isolate* isolate, Dart_Handle receivePort) {
+ const ReceivePort& rp = Api::UnwrapReceivePortHandle(isolate, receivePort);
+ if (rp.IsNull()) {
+ return ILLEGAL_PORT;
+ }
+ return rp.Id();
+}
+
+
+// These must be kept in sync with service/constants.dart
+#define VM_SERVICE_ISOLATE_STARTUP_MESSAGE_ID 1
+#define VM_SERVICE_ISOLATE_SHUTDOWN_MESSAGE_ID 2
+
+static RawArray* MakeServiceControlMessage(Dart_Port port_id, intptr_t code,
+ const String& name) {
+ const Array& list = Array::Handle(Array::New(4));
+ ASSERT(!list.IsNull());
+ const Integer& code_int = Integer::Handle(Integer::New(code));
+ const Integer& port_int = Integer::Handle(Integer::New(port_id));
+ const SendPort& send_port = SendPort::Handle(SendPort::New(port_id));
+ list.SetAt(0, code_int);
+ list.SetAt(1, port_int);
+ list.SetAt(2, send_port);
+ list.SetAt(3, name);
+ return list.raw();
+}
+
+
+const char* ServiceIsolate::kName = "vm-service";
+Isolate* ServiceIsolate::isolate_ = NULL;
+Dart_Port ServiceIsolate::port_ = ILLEGAL_PORT;
+Dart_Port ServiceIsolate::load_port_ = ILLEGAL_PORT;
+Dart_IsolateCreateCallback ServiceIsolate::create_callback_ = NULL;
+Monitor* ServiceIsolate::monitor_ = NULL;
+bool ServiceIsolate::initializing_ = true;
+
+
+class RegisterRunningIsolatesVisitor : public IsolateVisitor {
+ public:
+ explicit RegisterRunningIsolatesVisitor(Isolate* service_isolate)
+ : IsolateVisitor(),
+ register_function_(Function::Handle(service_isolate)),
+ service_isolate_(service_isolate) {
+ ASSERT(ServiceIsolate::IsServiceIsolate(Isolate::Current()));
+ // Get library.
+ const String& library_url = Symbols::DartVMService();
+ ASSERT(!library_url.IsNull());
+ const Library& library =
+ Library::Handle(Library::LookupLibrary(library_url));
+ ASSERT(!library.IsNull());
+ // Get function.
+ const String& function_name =
+ String::Handle(String::New("_registerIsolate"));
+ ASSERT(!function_name.IsNull());
+ register_function_ = library.LookupFunctionAllowPrivate(function_name);
+ ASSERT(!register_function_.IsNull());
+ }
+
+ virtual void VisitIsolate(Isolate* isolate) {
+ ASSERT(ServiceIsolate::IsServiceIsolate(Isolate::Current()));
+ if (ServiceIsolate::IsServiceIsolate(isolate) ||
+ (isolate == Dart::vm_isolate())) {
+ // We do not register the service or vm isolate.
+ return;
+ }
+ // Setup arguments for call.
+ Dart_Port port_id = isolate->main_port();
+ const Integer& port_int = Integer::Handle(Integer::New(port_id));
+ ASSERT(!port_int.IsNull());
+ const SendPort& send_port = SendPort::Handle(SendPort::New(port_id));
+ const String& name = String::Handle(String::New(isolate->name()));
+ ASSERT(!name.IsNull());
+ const Array& args = Array::Handle(Array::New(3));
+ ASSERT(!args.IsNull());
+ args.SetAt(0, port_int);
+ args.SetAt(1, send_port);
+ args.SetAt(2, name);
+ Object& r = Object::Handle(service_isolate_);
+ r = DartEntry::InvokeFunction(register_function_, args);
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Isolate %s %" Pd64 " registered.\n",
+ name.ToCString(),
+ port_id);
+ }
+ ASSERT(!r.IsError());
+ }
+
+ private:
+ Function& register_function_;
+ Isolate* service_isolate_;
+};
+
+
+
+class ServiceIsolateNatives : public AllStatic {
+ public:
+ static void SendIsolateServiceMessage(Dart_NativeArguments args) {
+ NativeArguments* arguments = reinterpret_cast<NativeArguments*>(args);
+ Isolate* isolate = arguments->isolate();
+ StackZone zone(isolate);
+ HANDLESCOPE(isolate);
+ GET_NON_NULL_NATIVE_ARGUMENT(SendPort, sp, arguments->NativeArgAt(0));
+ GET_NON_NULL_NATIVE_ARGUMENT(Array, message, arguments->NativeArgAt(1));
+
+ // Set the type of the OOB message.
+ message.SetAt(0, Smi::Handle(isolate, Smi::New(Message::kServiceOOBMsg)));
+
+ // Serialize message.
+ uint8_t* data = NULL;
+ MessageWriter writer(&data, &allocator, false);
+ writer.WriteMessage(message);
+
+ // TODO(turnidge): Throw an exception when the return value is false?
+ PortMap::PostMessage(new Message(sp.Id(), data, writer.BytesWritten(),
+ Message::kOOBPriority));
+ }
+
+ static void SendRootServiceMessage(Dart_NativeArguments args) {
+ NativeArguments* arguments = reinterpret_cast<NativeArguments*>(args);
+ Isolate* isolate = arguments->isolate();
+ StackZone zone(isolate);
+ HANDLESCOPE(isolate);
+ GET_NON_NULL_NATIVE_ARGUMENT(Array, message, arguments->NativeArgAt(0));
+ Service::HandleRootMessage(message);
+ }
+
+ static void SetEventMask(Dart_NativeArguments args) {
+ NativeArguments* arguments = reinterpret_cast<NativeArguments*>(args);
+ Isolate* isolate = arguments->isolate();
+ StackZone zone(isolate);
+ HANDLESCOPE(isolate);
+ GET_NON_NULL_NATIVE_ARGUMENT(Integer, mask, arguments->NativeArgAt(0));
+ Service::SetEventMask(mask.AsTruncatedUint32Value());
+ }
+
+ static void OnStart(Dart_NativeArguments args) {
+ NativeArguments* arguments = reinterpret_cast<NativeArguments*>(args);
+ Isolate* isolate = arguments->isolate();
+ StackZone zone(isolate);
+ HANDLESCOPE(isolate);
+ {
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Booting dart:vmservice library.\n");
+ }
+ // Boot the dart:vmservice library.
+ Dart_EnterScope();
+ Dart_Handle url_str =
+ Dart_NewStringFromCString(Symbols::Name(Symbols::kDartVMServiceId));
+ Dart_Handle library = Dart_LookupLibrary(url_str);
+ ASSERT(Dart_IsLibrary(library));
+ Dart_Handle result =
+ Dart_Invoke(library, Dart_NewStringFromCString("boot"), 0, NULL);
+ ASSERT(!Dart_IsError(result));
+ Dart_Port port = ExtractPort(isolate, result);
+ ASSERT(port != ILLEGAL_PORT);
+ ServiceIsolate::SetServicePort(port);
+ Dart_ExitScope();
+ }
+
+ {
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Registering running isolates.\n");
+ }
+ // Register running isolates with service.
+ RegisterRunningIsolatesVisitor register_isolates(isolate);
+ Isolate::VisitIsolates(®ister_isolates);
+ }
+ }
+};
+
+
+struct ServiceNativeEntry {
+ const char* name;
+ int num_arguments;
+ Dart_NativeFunction function;
+};
+
+
+static ServiceNativeEntry _ServiceNativeEntries[] = {
+ {"VMService_SendIsolateServiceMessage", 2,
+ ServiceIsolateNatives::SendIsolateServiceMessage},
+ {"VMService_SendRootServiceMessage", 1,
+ ServiceIsolateNatives::SendRootServiceMessage},
+ {"VMService_SetEventMask", 1,
+ ServiceIsolateNatives::SetEventMask},
+ {"VMService_OnStart", 0,
+ ServiceIsolateNatives::OnStart },
+};
+
+
+static Dart_NativeFunction ServiceNativeResolver(Dart_Handle name,
+ int num_arguments,
+ bool* auto_setup_scope) {
+ const Object& obj = Object::Handle(Api::UnwrapHandle(name));
+ if (!obj.IsString()) {
+ return NULL;
+ }
+ const char* function_name = obj.ToCString();
+ ASSERT(function_name != NULL);
+ ASSERT(auto_setup_scope != NULL);
+ *auto_setup_scope = true;
+ intptr_t n = sizeof(_ServiceNativeEntries) /
+ sizeof(_ServiceNativeEntries[0]);
+ for (intptr_t i = 0; i < n; i++) {
+ ServiceNativeEntry entry = _ServiceNativeEntries[i];
+ if ((strcmp(function_name, entry.name) == 0) &&
+ (num_arguments == entry.num_arguments)) {
+ return entry.function;
+ }
+ }
+ return NULL;
+}
+
+
+bool ServiceIsolate::NameEquals(const char* name) {
+ ASSERT(name != NULL);
+ return strcmp(name, kName) == 0;
+}
+
+
+bool ServiceIsolate::Exists() {
+ MonitorLocker ml(monitor_);
+ return isolate_ != NULL;
+}
+
+
+bool ServiceIsolate::IsRunning() {
+ MonitorLocker ml(monitor_);
+ return (port_ != ILLEGAL_PORT) && (isolate_ != NULL);
+}
+
+
+bool ServiceIsolate::IsServiceIsolate(Isolate* isolate) {
+ MonitorLocker ml(monitor_);
+ return isolate == isolate_;
+}
+
+
+Dart_Port ServiceIsolate::Port() {
+ MonitorLocker ml(monitor_);
+ return port_;
+}
+
+
+Dart_Port ServiceIsolate::WaitForLoadPort() {
+ MonitorLocker ml(monitor_);
+
+ while (initializing_ && (load_port_ == ILLEGAL_PORT)) {
+ ml.Wait();
+ }
+
+ return load_port_;
+}
+
+
+Dart_Port ServiceIsolate::LoadPort() {
+ MonitorLocker ml(monitor_);
+ return load_port_;
+}
+
+
+bool ServiceIsolate::SendIsolateStartupMessage() {
+ if (!IsRunning()) {
+ return false;
+ }
+ Isolate* isolate = Isolate::Current();
+ if (IsServiceIsolate(isolate)) {
+ return false;
+ }
+ ASSERT(isolate != NULL);
+ HANDLESCOPE(isolate);
+ const String& name = String::Handle(String::New(isolate->name()));
+ ASSERT(!name.IsNull());
+ const Array& list = Array::Handle(
+ MakeServiceControlMessage(Dart_GetMainPortId(),
+ VM_SERVICE_ISOLATE_STARTUP_MESSAGE_ID,
+ name));
+ ASSERT(!list.IsNull());
+ uint8_t* data = NULL;
+ MessageWriter writer(&data, &allocator, false);
+ writer.WriteMessage(list);
+ intptr_t len = writer.BytesWritten();
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Isolate %s %" Pd64 " registered.\n",
+ name.ToCString(),
+ Dart_GetMainPortId());
+ }
+ return PortMap::PostMessage(
+ new Message(port_, data, len, Message::kNormalPriority));
+}
+
+
+bool ServiceIsolate::SendIsolateShutdownMessage() {
+ if (!IsRunning()) {
+ return false;
+ }
+ Isolate* isolate = Isolate::Current();
+ if (IsServiceIsolate(isolate)) {
+ return false;
+ }
+ ASSERT(isolate != NULL);
+ HANDLESCOPE(isolate);
+ const String& name = String::Handle(String::New(isolate->name()));
+ ASSERT(!name.IsNull());
+ const Array& list = Array::Handle(
+ MakeServiceControlMessage(Dart_GetMainPortId(),
+ VM_SERVICE_ISOLATE_SHUTDOWN_MESSAGE_ID,
+ name));
+ ASSERT(!list.IsNull());
+ uint8_t* data = NULL;
+ MessageWriter writer(&data, &allocator, false);
+ writer.WriteMessage(list);
+ intptr_t len = writer.BytesWritten();
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Isolate %s %" Pd64 " deregistered.\n",
+ name.ToCString(),
+ Dart_GetMainPortId());
+ }
+ return PortMap::PostMessage(
+ new Message(port_, data, len, Message::kNormalPriority));
+}
+
+
+void ServiceIsolate::SetServicePort(Dart_Port port) {
+ MonitorLocker ml(monitor_);
+ port_ = port;
+}
+
+
+void ServiceIsolate::SetServiceIsolate(Isolate* isolate) {
+ MonitorLocker ml(monitor_);
+ isolate_ = isolate;
+ if (isolate_ != NULL) {
+ isolate_->is_service_isolate_ = true;
+ }
+}
+
+void ServiceIsolate::SetLoadPort(Dart_Port port) {
+ MonitorLocker ml(monitor_);
+ load_port_ = port;
+}
+
+
+void ServiceIsolate::MaybeInjectVMServiceLibrary(Isolate* isolate) {
+ ASSERT(isolate != NULL);
+ ASSERT(isolate->name() != NULL);
+ if (!ServiceIsolate::NameEquals(isolate->name())) {
+ // Not service isolate.
+ return;
+ }
+ if (Exists()) {
+ // Service isolate already exists.
+ return;
+ }
+ SetServiceIsolate(isolate);
+
+ StackZone zone(isolate);
+ HANDLESCOPE(isolate);
+
+ // Register dart:vmservice library.
+ const String& url_str = String::Handle(Symbols::DartVMService().raw());
+ const Library& library = Library::Handle(Library::New(url_str));
+ library.Register();
+ library.set_native_entry_resolver(ServiceNativeResolver);
+
+ // Temporarily install our library tag handler.
+ isolate->set_library_tag_handler(LibraryTagHandler);
+
+ // Get script source.
+ const char* resource = NULL;
+ const char* path = "/vmservice.dart";
+ intptr_t r = Resources::ResourceLookup(path, &resource);
+ ASSERT(r != Resources::kNoSuchInstance);
+ ASSERT(resource != NULL);
+ const String& source_str = String::Handle(
+ String::FromUTF8(reinterpret_cast<const uint8_t*>(resource), r));
+ ASSERT(!source_str.IsNull());
+ const Script& script = Script::Handle(
+ isolate, Script::New(url_str, source_str, RawScript::kLibraryTag));
+
+ // Compile script.
+ Dart_EnterScope(); // Need to enter scope for tag handler.
+ library.SetLoadInProgress();
+ const Error& error = Error::Handle(isolate,
+ Compiler::Compile(library, script));
+ ASSERT(error.IsNull());
+ Dart_Handle result = Dart_FinalizeLoading(false);
+ ASSERT(!Dart_IsError(result));
+ Dart_ExitScope();
+
+ // Uninstall our library tag handler.
+ isolate->set_library_tag_handler(NULL);
+}
+
+
+void ServiceIsolate::FinishedInitializing() {
+ MonitorLocker ml(monitor_);
+ initializing_ = false;
+ ml.NotifyAll();
+}
+
+
+class RunServiceTask : public ThreadPool::Task {
+ public:
+ virtual void Run() {
+ ASSERT(Isolate::Current() == NULL);
+ char* error = NULL;
+ Isolate* isolate = NULL;
+
+ Dart_IsolateCreateCallback create_callback =
+ ServiceIsolate::create_callback();
+ // TODO(johnmccutchan): Support starting up service isolate without embedder
+ // provided isolate creation callback.
+ if (create_callback == NULL) {
+ ServiceIsolate::FinishedInitializing();
+ return;
+ }
+
+ isolate =
+ reinterpret_cast<Isolate*>(create_callback(ServiceIsolate::kName,
+ NULL,
+ NULL,
+ NULL,
+ &error));
+ if (isolate == NULL) {
+ OS::PrintErr("vm-service: Isolate creation error: %s\n", error);
+ ServiceIsolate::FinishedInitializing();
+ return;
+ }
+
+ Isolate::SetCurrent(NULL);
+
+ RunMain(isolate);
+
+ ServiceIsolate::FinishedInitializing();
+
+ isolate->message_handler()->Run(Dart::thread_pool(),
+ NULL,
+ ShutdownIsolate,
+ reinterpret_cast<uword>(isolate));
+ }
+
+ protected:
+ static void ShutdownIsolate(uword parameter) {
+ Isolate* isolate = reinterpret_cast<Isolate*>(parameter);
+ ASSERT(ServiceIsolate::IsServiceIsolate(isolate));
+ {
+ // Print the error if there is one. This may execute dart code to
+ // print the exception object, so we need to use a StartIsolateScope.
+ StartIsolateScope start_scope(isolate);
+ StackZone zone(isolate);
+ HandleScope handle_scope(isolate);
+ Error& error = Error::Handle();
+ error = isolate->object_store()->sticky_error();
+ if (!error.IsNull()) {
+ OS::PrintErr("vm-service: Error: %s\n", error.ToErrorCString());
+ }
+ Dart::RunShutdownCallback();
+ }
+ {
+ // Shut the isolate down.
+ SwitchIsolateScope switch_scope(isolate);
+ Dart::ShutdownIsolate();
+ }
+ ServiceIsolate::SetServiceIsolate(NULL);
+ ServiceIsolate::SetServicePort(ILLEGAL_PORT);
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Shutdown.\n");
+ }
+ }
+
+ void RunMain(Isolate* isolate) {
+ StartIsolateScope iso_scope(isolate);
+ StackZone zone(isolate);
+ HANDLESCOPE(isolate);
+ // Invoke main which will return the loadScriptPort.
+ const Library& root_library =
+ Library::Handle(isolate, isolate->object_store()->root_library());
+ if (root_library.IsNull()) {
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Embedder did not install a script.");
+ }
+ // Service isolate is not supported by embedder.
+ return;
+ }
+ ASSERT(!root_library.IsNull());
+ const String& entry_name = String::Handle(isolate, String::New("main"));
+ ASSERT(!entry_name.IsNull());
+ const Function& entry =
+ Function::Handle(isolate,
+ root_library.LookupFunctionAllowPrivate(entry_name));
+ if (entry.IsNull()) {
+ // Service isolate is not supported by embedder.
+ if (FLAG_trace_service) {
+ OS::Print("vm-service: Embedder did not provide a main function.");
+ }
+ return;
+ }
+ ASSERT(!entry.IsNull());
+ const Object& result =
+ Object::Handle(isolate,
+ DartEntry::InvokeFunction(entry,
+ Object::empty_array()));
+ ASSERT(!result.IsNull());
+ if (result.IsError()) {
+ // Service isolate did not initialize properly.
+ if (FLAG_trace_service) {
+ const Error& error = Error::Cast(result);
+ OS::Print("vm-service: Calling main resulted in an error: %s",
+ error.ToErrorCString());
+ }
+ return;
+ }
+ ASSERT(result.IsReceivePort());
+ const ReceivePort& rp = ReceivePort::Cast(result);
+ ServiceIsolate::SetLoadPort(rp.Id());
+ }
+};
+
+
+void ServiceIsolate::Run() {
+ ASSERT(monitor_ == NULL);
+ monitor_ = new Monitor();
+ ASSERT(monitor_ != NULL);
+ // Grab the isolate create callback here to avoid race conditions with tests
+ // that change this after Dart_Initialize returns.
+ create_callback_ = Isolate::CreateCallback();
+ Dart::thread_pool()->Run(new RunServiceTask());
+}
+
+
+Dart_Handle ServiceIsolate::GetSource(const char* name) {
+ ASSERT(name != NULL);
+ int i = 0;
+ while (true) {
+ const char* path = Resources::Path(i);
+ if (path == NULL) {
+ break;
+ }
+ ASSERT(*path != '\0');
+ // Skip the '/'.
+ path++;
+ if (strcmp(name, path) == 0) {
+ const uint8_t* str = Resources::Resource(i);
+ intptr_t length = Resources::Length(i);
+ return Dart_NewStringFromUTF8(str, length);
+ }
+ i++;
+ }
+ FATAL1("vm-service: Could not find embedded source file: %s ", name);
+ return Dart_Null();
+}
+
+
+Dart_Handle ServiceIsolate::LibraryTagHandler(Dart_LibraryTag tag,
+ Dart_Handle library,
+ Dart_Handle url) {
+ if (tag == Dart_kCanonicalizeUrl) {
+ // url is already canonicalized.
+ return url;
+ }
+ if (tag != Dart_kSourceTag) {
+ FATAL("ServiceIsolate::LibraryTagHandler encountered an unexpected tag.");
+ }
+ ASSERT(tag == Dart_kSourceTag);
+ const char* url_string = NULL;
+ Dart_Handle result = Dart_StringToCString(url, &url_string);
+ if (Dart_IsError(result)) {
+ return result;
+ }
+ Dart_Handle source = GetSource(url_string);
+ if (Dart_IsError(source)) {
+ return source;
+ }
+ return Dart_LoadSource(library, url, source, 0, 0);
+}
+
+} // namespace dart
diff --git a/runtime/vm/service_isolate.h b/runtime/vm/service_isolate.h
new file mode 100644
index 0000000..824d136
--- /dev/null
+++ b/runtime/vm/service_isolate.h
@@ -0,0 +1,60 @@
+// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+#ifndef VM_SERVICE_ISOLATE_H_
+#define VM_SERVICE_ISOLATE_H_
+
+#include "include/dart_api.h"
+
+#include "vm/allocation.h"
+#include "vm/os_thread.h"
+
+namespace dart {
+
+class ServiceIsolate : public AllStatic {
+ public:
+ static const char* kName;
+ static bool NameEquals(const char* name);
+
+ static bool Exists();
+ static bool IsRunning();
+ static bool IsServiceIsolate(Isolate* isolate);
+ static Dart_Port Port();
+
+ static Dart_Port WaitForLoadPort();
+ static Dart_Port LoadPort();
+
+ static void Run();
+ static bool SendIsolateStartupMessage();
+ static bool SendIsolateShutdownMessage();
+
+ protected:
+ static void SetServicePort(Dart_Port port);
+ static void SetServiceIsolate(Isolate* isolate);
+ static void SetLoadPort(Dart_Port port);
+ static void FinishedInitializing();
+ static void MaybeInjectVMServiceLibrary(Isolate* isolate);
+ static Dart_IsolateCreateCallback create_callback() {
+ return create_callback_;
+ }
+
+ static Dart_Handle GetSource(const char* name);
+ static Dart_Handle LibraryTagHandler(Dart_LibraryTag tag, Dart_Handle library,
+ Dart_Handle url);
+
+ static Dart_IsolateCreateCallback create_callback_;
+ static Monitor* monitor_;
+ static bool initializing_;
+ static Isolate* isolate_;
+ static Dart_Port port_;
+ static Dart_Port load_port_;
+
+ friend class Dart;
+ friend class RunServiceTask;
+ friend class ServiceIsolateNatives;
+};
+
+} // namespace dart
+
+#endif // VM_SERVICE_ISOLATE_H_
diff --git a/runtime/vm/service_test.cc b/runtime/vm/service_test.cc
index 17691b4..1670e0d 100644
--- a/runtime/vm/service_test.cc
+++ b/runtime/vm/service_test.cc
@@ -89,7 +89,7 @@
};
-static RawArray* Eval(Dart_Handle lib, const char* expr) {
+static RawArray* EvalVM(Dart_Handle lib, const char* expr) {
Dart_Handle expr_val = Dart_EvaluateExpr(lib, NewString(expr));
EXPECT_VALID(expr_val);
Isolate* isolate = Isolate::Current();
@@ -107,6 +107,29 @@
}
+static RawArray* Eval(Dart_Handle lib, const char* expr) {
+ const String& dummy_isolate_id = String::Handle(String::New("isolateId"));
+ Dart_Handle expr_val = Dart_EvaluateExpr(lib, NewString(expr));
+ EXPECT_VALID(expr_val);
+ Isolate* isolate = Isolate::Current();
+ const GrowableObjectArray& value =
+ Api::UnwrapGrowableObjectArrayHandle(isolate, expr_val);
+ const Array& result = Array::Handle(Array::MakeArray(value));
+ GrowableObjectArray& growable = GrowableObjectArray::Handle();
+ growable ^= result.At(3);
+ // Append dummy isolate id to parameter values.
+ growable.Add(dummy_isolate_id);
+ Array& array = Array::Handle(Array::MakeArray(growable));
+ result.SetAt(3, array);
+ growable ^= result.At(4);
+ // Append dummy isolate id to parameter values.
+ growable.Add(dummy_isolate_id);
+ array = Array::MakeArray(growable);
+ result.SetAt(4, array);
+ return result.raw();
+}
+
+
static RawArray* EvalF(Dart_Handle lib, const char* fmt, ...) {
Isolate* isolate = Isolate::Current();
@@ -1052,7 +1075,7 @@
EXPECT_VALID(Dart_SetField(lib, NewString("port"), port));
Array& service_msg = Array::Handle();
- service_msg = Eval(lib, "[0, port, 'getVM', [], []]");
+ service_msg = EvalVM(lib, "[0, port, 'getVM', [], []]");
Service::HandleRootMessage(service_msg);
handler.HandleNextMessage();
@@ -1084,7 +1107,7 @@
EXPECT_VALID(Dart_SetField(lib, NewString("port"), port));
Array& service_msg = Array::Handle();
- service_msg = Eval(lib, "[0, port, 'getFlagList', [], []]");
+ service_msg = EvalVM(lib, "[0, port, 'getFlagList', [], []]");
// Make sure we can get the FlagList.
Service::HandleRootMessage(service_msg);
@@ -1096,15 +1119,15 @@
handler.msg());
// Modify a flag through the vm service.
- service_msg = Eval(lib,
- "[0, port, 'setFlag', "
- "['name', 'value'], ['service_testing_flag', 'true']]");
+ service_msg = EvalVM(lib,
+ "[0, port, 'setFlag', "
+ "['name', 'value'], ['service_testing_flag', 'true']]");
Service::HandleRootMessage(service_msg);
handler.HandleNextMessage();
EXPECT_SUBSTRING("Success", handler.msg());
// Make sure that the flag changed.
- service_msg = Eval(lib, "[0, port, 'getFlagList', [], []]");
+ service_msg = EvalVM(lib, "[0, port, 'getFlagList', [], []]");
Service::HandleRootMessage(service_msg);
handler.HandleNextMessage();
EXPECT_SUBSTRING(
@@ -1435,8 +1458,8 @@
service_msg = Eval(lib, "[0, port, 'getCpuProfile', [], []]");
Service::HandleIsolateMessage(isolate, service_msg);
handler.HandleNextMessage();
- // Expect profile
- EXPECT_SUBSTRING("\"type\":\"CpuProfile\"", handler.msg());
+ // Expect error (tags required).
+ EXPECT_SUBSTRING("\"type\":\"Error\"", handler.msg());
service_msg =
Eval(lib, "[0, port, 'getCpuProfile', ['tags'], ['None']]");
diff --git a/runtime/vm/simulator_arm.cc b/runtime/vm/simulator_arm.cc
index d3cfe92..c181db5 100644
--- a/runtime/vm/simulator_arm.cc
+++ b/runtime/vm/simulator_arm.cc
@@ -56,7 +56,8 @@
link_ = sim->last_setjmp_buffer();
sim->set_last_setjmp_buffer(this);
sp_ = static_cast<uword>(sim->get_register(SP));
- native_sp_ = reinterpret_cast<uword>(&sim); // Current C++ stack pointer.
+ }
+>>>>>>> .merge-right.r43886
}
~SimulatorSetjmpBuffer() {
@@ -67,11 +68,9 @@
SimulatorSetjmpBuffer* link() { return link_; }
uword sp() { return sp_; }
- uword native_sp() { return native_sp_; }
private:
uword sp_;
- uword native_sp_;
Simulator* simulator_;
SimulatorSetjmpBuffer* link_;
jmp_buf buffer_;
@@ -1524,7 +1523,7 @@
(redirection->call_kind() == kBootstrapNativeCall) ||
(redirection->call_kind() == kNativeCall)) {
// Set the top_exit_frame_info of this simulator to the native stack.
- set_top_exit_frame_info(reinterpret_cast<uword>(&buffer));
+ set_top_exit_frame_info(Isolate::GetCurrentStackPointer());
}
if (redirection->call_kind() == kRuntimeCall) {
NativeArguments arguments;
@@ -3859,11 +3858,8 @@
// The C++ caller has not cleaned up the stack memory of C++ frames.
// Prepare for unwinding frames by destroying all the stack resources
// in the previous C++ frames.
- uword native_sp = buf->native_sp();
- while (isolate->top_resource() != NULL &&
- (reinterpret_cast<uword>(isolate->top_resource()) < native_sp)) {
- isolate->top_resource()->~StackResource();
- }
+ StackResource::Unwind(isolate);
+>>>>>>> .merge-right.r43886
// Unwind the C++ stack and continue simulation in the target frame.
set_register(PC, static_cast<int32_t>(pc));
diff --git a/runtime/vm/simulator_arm64.cc b/runtime/vm/simulator_arm64.cc
index 84f5257..7ffde6f 100644
--- a/runtime/vm/simulator_arm64.cc
+++ b/runtime/vm/simulator_arm64.cc
@@ -55,7 +55,8 @@
link_ = sim->last_setjmp_buffer();
sim->set_last_setjmp_buffer(this);
sp_ = static_cast<uword>(sim->get_register(R31, R31IsSP));
- native_sp_ = reinterpret_cast<uword>(&sim); // Current C++ stack pointer.
+ }
+>>>>>>> .merge-right.r43886
}
~SimulatorSetjmpBuffer() {
@@ -66,11 +67,9 @@
SimulatorSetjmpBuffer* link() { return link_; }
uword sp() { return sp_; }
- uword native_sp() { return native_sp_; }
private:
uword sp_;
- uword native_sp_;
Simulator* simulator_;
SimulatorSetjmpBuffer* link_;
jmp_buf buffer_;
@@ -1586,7 +1585,7 @@
(redirection->call_kind() == kBootstrapNativeCall) ||
(redirection->call_kind() == kNativeCall)) {
// Set the top_exit_frame_info of this simulator to the native stack.
- set_top_exit_frame_info(reinterpret_cast<uword>(&buffer));
+ set_top_exit_frame_info(Isolate::GetCurrentStackPointer());
}
if (redirection->call_kind() == kRuntimeCall) {
NativeArguments* arguments =
@@ -3482,11 +3481,8 @@
// The C++ caller has not cleaned up the stack memory of C++ frames.
// Prepare for unwinding frames by destroying all the stack resources
// in the previous C++ frames.
- uword native_sp = buf->native_sp();
- while (isolate->top_resource() != NULL &&
- (reinterpret_cast<uword>(isolate->top_resource()) < native_sp)) {
- isolate->top_resource()->~StackResource();
- }
+ StackResource::Unwind(isolate);
+>>>>>>> .merge-right.r43886
// Unwind the C++ stack and continue simulation in the target frame.
set_pc(static_cast<int64_t>(pc));
diff --git a/runtime/vm/simulator_mips.cc b/runtime/vm/simulator_mips.cc
index b665764..9dece24 100644
--- a/runtime/vm/simulator_mips.cc
+++ b/runtime/vm/simulator_mips.cc
@@ -55,7 +55,8 @@
link_ = sim->last_setjmp_buffer();
sim->set_last_setjmp_buffer(this);
sp_ = static_cast<uword>(sim->get_register(SP));
- native_sp_ = reinterpret_cast<uword>(&sim); // Current C++ stack pointer.
+ }
+>>>>>>> .merge-right.r43886
}
~SimulatorSetjmpBuffer() {
@@ -66,11 +67,9 @@
SimulatorSetjmpBuffer* link() { return link_; }
uword sp() { return sp_; }
- uword native_sp() { return native_sp_; }
private:
uword sp_;
- uword native_sp_;
Simulator* simulator_;
SimulatorSetjmpBuffer* link_;
jmp_buf buffer_;
@@ -1241,7 +1240,7 @@
(redirection->call_kind() == kBootstrapNativeCall) ||
(redirection->call_kind() == kNativeCall)) {
// Set the top_exit_frame_info of this simulator to the native stack.
- set_top_exit_frame_info(reinterpret_cast<uword>(&buffer));
+ set_top_exit_frame_info(Isolate::GetCurrentStackPointer());
}
if (redirection->call_kind() == kRuntimeCall) {
NativeArguments arguments;
@@ -2475,11 +2474,8 @@
// The C++ caller has not cleaned up the stack memory of C++ frames.
// Prepare for unwinding frames by destroying all the stack resources
// in the previous C++ frames.
- uword native_sp = buf->native_sp();
- while (isolate->top_resource() != NULL &&
- (reinterpret_cast<uword>(isolate->top_resource()) < native_sp)) {
- isolate->top_resource()->~StackResource();
- }
+ StackResource::Unwind(isolate);
+>>>>>>> .merge-right.r43886
// Unwind the C++ stack and continue simulation in the target frame.
set_pc(static_cast<int32_t>(pc));
diff --git a/runtime/vm/snapshot.cc b/runtime/vm/snapshot.cc
index 7bbf5ef..9420790 100644
--- a/runtime/vm/snapshot.cc
+++ b/runtime/vm/snapshot.cc
@@ -7,6 +7,7 @@
#include "platform/assert.h"
#include "vm/bootstrap.h"
#include "vm/class_finalizer.h"
+#include "vm/dart_entry.h"
#include "vm/exceptions.h"
#include "vm/heap.h"
#include "vm/lockers.h"
@@ -223,11 +224,15 @@
// Read the library/class information and lookup the class.
str_ ^= ReadObjectImpl(class_header);
library_ = Library::LookupLibrary(str_);
- ASSERT(!library_.IsNull());
+ if (library_.IsNull() || !library_.Loaded()) {
+ SetReadException("Invalid object found in message.");
+ }
str_ ^= ReadObjectImpl();
cls = library_.LookupClass(str_);
+ if (cls.IsNull()) {
+ SetReadException("Invalid object found in message.");
+ }
cls.EnsureIsFinalized(isolate());
- ASSERT(!cls.IsNull());
return cls.raw();
}
@@ -247,6 +252,24 @@
}
+void SnapshotReader::SetReadException(const char* msg) {
+ Isolate* isolate = Isolate::Current();
+ const String& error_str = String::Handle(isolate, String::New(msg));
+ const Array& args = Array::Handle(isolate, Array::New(1));
+ args.SetAt(0, error_str);
+ Object& result = Object::Handle(isolate);
+ const Library& library = Library::Handle(isolate, Library::CoreLibrary());
+ result = DartLibraryCalls::InstanceCreate(library,
+ Symbols::ArgumentError(),
+ Symbols::Dot(),
+ args);
+ const Stacktrace& stacktrace = Stacktrace::Handle(isolate);
+ const UnhandledException& error = UnhandledException::Handle(
+ isolate, UnhandledException::New(Instance::Cast(result), stacktrace));
+ isolate->long_jump_base()->Jump(1, error);
+}
+
+
RawObject* SnapshotReader::ReadObjectImpl(intptr_t header_value) {
if (IsVMIsolateObject(header_value)) {
return ReadVMIsolateObject(header_value);
diff --git a/runtime/vm/snapshot.h b/runtime/vm/snapshot.h
index f0ef323..9440e1a 100644
--- a/runtime/vm/snapshot.h
+++ b/runtime/vm/snapshot.h
@@ -368,6 +368,8 @@
intptr_t NextAvailableObjectId() const;
+ void SetReadException(const char* msg);
+
Snapshot::Kind kind_; // Indicates type of snapshot(full, script, message).
Isolate* isolate_; // Current isolate.
Heap* heap_; // Heap of the current isolate.
diff --git a/runtime/vm/stack_frame_arm.h b/runtime/vm/stack_frame_arm.h
index b23b719..e391334 100644
--- a/runtime/vm/stack_frame_arm.h
+++ b/runtime/vm/stack_frame_arm.h
@@ -43,7 +43,7 @@
static const int kCallerSpSlotFromFp = 3;
// Entry and exit frame layout.
-static const int kExitLinkSlotFromEntryFp = -25;
+static const int kExitLinkSlotFromEntryFp = -26;
} // namespace dart
diff --git a/runtime/vm/stack_frame_arm64.h b/runtime/vm/stack_frame_arm64.h
index d8a848f..f252897 100644
--- a/runtime/vm/stack_frame_arm64.h
+++ b/runtime/vm/stack_frame_arm64.h
@@ -44,7 +44,7 @@
static const int kSavedAboveReturnAddress = 3; // Saved above return address.
// Entry and exit frame layout.
-static const int kExitLinkSlotFromEntryFp = -20;
+static const int kExitLinkSlotFromEntryFp = -21;
} // namespace dart
diff --git a/runtime/vm/stack_frame_ia32.h b/runtime/vm/stack_frame_ia32.h
index 7b5032f..f1a379b 100644
--- a/runtime/vm/stack_frame_ia32.h
+++ b/runtime/vm/stack_frame_ia32.h
@@ -42,7 +42,7 @@
static const int kSavedCallerPpSlotFromFp = kSavedCallerFpSlotFromFp;
// Entry and exit frame layout.
-static const int kExitLinkSlotFromEntryFp = -5;
+static const int kExitLinkSlotFromEntryFp = -6;
} // namespace dart
diff --git a/runtime/vm/stack_frame_mips.h b/runtime/vm/stack_frame_mips.h
index 891fa2e..142ed61 100644
--- a/runtime/vm/stack_frame_mips.h
+++ b/runtime/vm/stack_frame_mips.h
@@ -41,7 +41,7 @@
static const int kCallerSpSlotFromFp = 3;
// Entry and exit frame layout.
-static const int kExitLinkSlotFromEntryFp = -22;
+static const int kExitLinkSlotFromEntryFp = -23;
} // namespace dart
diff --git a/runtime/vm/stack_frame_x64.h b/runtime/vm/stack_frame_x64.h
index a80a291..3d87d27 100644
--- a/runtime/vm/stack_frame_x64.h
+++ b/runtime/vm/stack_frame_x64.h
@@ -46,9 +46,9 @@
// Entry and exit frame layout.
#if defined(_WIN64)
-static const int kExitLinkSlotFromEntryFp = -30;
+static const int kExitLinkSlotFromEntryFp = -31;
#else
-static const int kExitLinkSlotFromEntryFp = -8;
+static const int kExitLinkSlotFromEntryFp = -9;
#endif // defined(_WIN64)
} // namespace dart
diff --git a/runtime/vm/stub_code_arm.cc b/runtime/vm/stub_code_arm.cc
index a5b46fc..d8d9371 100644
--- a/runtime/vm/stub_code_arm.cc
+++ b/runtime/vm/stub_code_arm.cc
@@ -764,14 +764,17 @@
__ LoadImmediate(R5, VMTag::kDartTagId);
__ StoreToOffset(kWord, R5, R8, Isolate::vm_tag_offset());
- // Save the top exit frame info. Use R5 as a temporary register.
+ // Save top resource and top exit frame info. Use R4-6 as temporary registers.
// StackFrameIterator reads the top exit frame info saved in this frame.
__ LoadFromOffset(kWord, R5, R8, Isolate::top_exit_frame_info_offset());
+ __ LoadFromOffset(kWord, R4, R8, Isolate::top_resource_offset());
__ LoadImmediate(R6, 0);
+ __ StoreToOffset(kWord, R6, R8, Isolate::top_resource_offset());
__ StoreToOffset(kWord, R6, R8, Isolate::top_exit_frame_info_offset());
// kExitLinkSlotFromEntryFp must be kept in sync with the code below.
- ASSERT(kExitLinkSlotFromEntryFp == -25);
+ __ Push(R4);
+ ASSERT(kExitLinkSlotFromEntryFp == -26);
__ Push(R5);
// Load arguments descriptor array into R4, which is passed to Dart code.
@@ -807,11 +810,12 @@
__ AddImmediate(SP, FP, kExitLinkSlotFromEntryFp * kWordSize);
__ LoadIsolate(R8);
-
- // Restore the saved top exit frame info back into the Isolate structure.
- // Uses R5 as a temporary register for this.
+ // Restore the saved top exit frame info and top resource back into the
+ // Isolate structure. Uses R5 as a temporary register for this.
__ Pop(R5);
__ StoreToOffset(kWord, R5, R8, Isolate::top_exit_frame_info_offset());
+ __ Pop(R5);
+ __ StoreToOffset(kWord, R5, R8, Isolate::top_resource_offset());
// Restore the current VMTag from the stack.
__ Pop(R4);
diff --git a/runtime/vm/stub_code_arm64.cc b/runtime/vm/stub_code_arm64.cc
index 90056a8..6621689 100644
--- a/runtime/vm/stub_code_arm64.cc
+++ b/runtime/vm/stub_code_arm64.cc
@@ -805,13 +805,15 @@
__ LoadImmediate(R6, VMTag::kDartTagId, PP);
__ StoreToOffset(R6, R5, Isolate::vm_tag_offset(), PP);
- // Save the top exit frame info. Use R6 as a temporary register.
+ // Save top resource and top exit frame info. Use R6 as a temporary register.
// StackFrameIterator reads the top exit frame info saved in this frame.
+ __ LoadFromOffset(R6, R5, Isolate::top_resource_offset(), PP);
+ __ StoreToOffset(ZR, R5, Isolate::top_resource_offset(), PP);
+ __ Push(R6);
__ LoadFromOffset(R6, R5, Isolate::top_exit_frame_info_offset(), PP);
__ StoreToOffset(ZR, R5, Isolate::top_exit_frame_info_offset(), PP);
-
// kExitLinkSlotFromEntryFp must be kept in sync with the code below.
- ASSERT(kExitLinkSlotFromEntryFp == -20);
+ ASSERT(kExitLinkSlotFromEntryFp == -21);
__ Push(R6);
// Load arguments descriptor array into R4, which is passed to Dart code.
@@ -852,10 +854,12 @@
__ LoadIsolate(R28, PP);
- // Restore the saved top exit frame info back into the Isolate structure.
- // Uses R6 as a temporary register for this.
+ // Restore the saved top exit frame info and top resource back into the
+ // Isolate structure. Uses R6 as a temporary register for this.
__ Pop(R6);
__ StoreToOffset(R6, R28, Isolate::top_exit_frame_info_offset(), PP);
+ __ Pop(R6);
+ __ StoreToOffset(R6, R28, Isolate::top_resource_offset(), PP);
// Restore the current VMTag from the stack.
__ Pop(R4);
diff --git a/runtime/vm/stub_code_ia32.cc b/runtime/vm/stub_code_ia32.cc
index 611d119..6e35450 100644
--- a/runtime/vm/stub_code_ia32.cc
+++ b/runtime/vm/stub_code_ia32.cc
@@ -713,11 +713,14 @@
__ movl(Address(ESI, Isolate::vm_tag_offset()),
Immediate(VMTag::kDartTagId));
- // Save the top exit frame info. Use EDX as a temporary register.
+ // Save top resource and top exit frame info. Use EDX as a temporary register.
// StackFrameIterator reads the top exit frame info saved in this frame.
+ __ movl(EDX, Address(ESI, Isolate::top_resource_offset()));
+ __ pushl(EDX);
+ __ movl(Address(ESI, Isolate::top_resource_offset()), Immediate(0));
// The constant kExitLinkSlotFromEntryFp must be kept in sync with the
// code below.
- ASSERT(kExitLinkSlotFromEntryFp == -5);
+ ASSERT(kExitLinkSlotFromEntryFp == -6);
__ movl(EDX, Address(ESI, Isolate::top_exit_frame_info_offset()));
__ pushl(EDX);
__ movl(Address(ESI, Isolate::top_exit_frame_info_offset()), Immediate(0));
@@ -761,9 +764,11 @@
// Get rid of arguments pushed on the stack.
__ leal(ESP, Address(ESP, EDX, TIMES_2, 0)); // EDX is a Smi.
- // Restore the saved top exit frame info back into the Isolate structure.
+ // Restore the saved top exit frame info and top resource back into the
+ // Isolate structure.
__ LoadIsolate(ESI);
__ popl(Address(ESI, Isolate::top_exit_frame_info_offset()));
+ __ popl(Address(ESI, Isolate::top_resource_offset()));
// Restore the current VMTag from the stack.
__ popl(Address(ESI, Isolate::vm_tag_offset()));
diff --git a/runtime/vm/stub_code_mips.cc b/runtime/vm/stub_code_mips.cc
index ecdacc1..a00fd1f 100644
--- a/runtime/vm/stub_code_mips.cc
+++ b/runtime/vm/stub_code_mips.cc
@@ -819,8 +819,8 @@
// Save new context and C++ ABI callee-saved registers.
- // The saved vm tag and the top exit frame.
- const intptr_t kPreservedSlots = 2;
+ // The saved vm tag, top resource, and top exit frame info.
+ const intptr_t kPreservedSlots = 3;
const intptr_t kPreservedRegSpace =
kWordSize * (kAbiPreservedCpuRegCount + kAbiPreservedFpuRegCount +
kPreservedSlots);
@@ -850,23 +850,25 @@
// Save the current VMTag on the stack.
__ lw(T1, Address(T2, Isolate::vm_tag_offset()));
- __ sw(T1, Address(SP, 1 * kWordSize));
+ __ sw(T1, Address(SP, 2 * kWordSize));
// Mark that the isolate is executing Dart code.
__ LoadImmediate(T0, VMTag::kDartTagId);
__ sw(T0, Address(T2, Isolate::vm_tag_offset()));
- // Save the top exit frame info. Use T0 as a temporary register.
+ // Save top resource and top exit frame info. Use T0 as a temporary register.
// StackFrameIterator reads the top exit frame info saved in this frame.
+ __ lw(T0, Address(T2, Isolate::top_resource_offset()));
+ __ sw(ZR, Address(T2, Isolate::top_resource_offset()));
+ __ sw(T0, Address(SP, 1 * kWordSize));
__ lw(T0, Address(T2, Isolate::top_exit_frame_info_offset()));
__ sw(ZR, Address(T2, Isolate::top_exit_frame_info_offset()));
-
// kExitLinkSlotFromEntryFp must be kept in sync with the code below.
- ASSERT(kExitLinkSlotFromEntryFp == -22);
+ ASSERT(kExitLinkSlotFromEntryFp == -23);
__ sw(T0, Address(SP, 0 * kWordSize));
// After the call, The stack pointer is restored to this location.
- // Pushed S0-7, F20-31, T0, T1 = 22.
+ // Pushed S0-7, F20-31, T0, T0, T1 = 23.
// Load arguments descriptor array into S4, which is passed to Dart code.
__ lw(S4, Address(A1, VMHandles::kOffsetOfRawPtrInHandle));
@@ -906,11 +908,13 @@
__ LoadIsolate(S6);
// Restore the current VMTag from the stack.
- __ lw(T1, Address(SP, 1 * kWordSize));
+ __ lw(T1, Address(SP, 2 * kWordSize));
__ sw(T1, Address(S6, Isolate::vm_tag_offset()));
- // Restore the saved top exit frame info back into the Isolate structure.
- // Uses T0 as a temporary register for this.
+ // Restore the saved top resource and top exit frame info back into the
+ // Isolate structure. Uses T0 as a temporary register for this.
+ __ lw(T0, Address(SP, 1 * kWordSize));
+ __ sw(T0, Address(S6, Isolate::top_resource_offset()));
__ lw(T0, Address(SP, 0 * kWordSize));
__ sw(T0, Address(S6, Isolate::top_exit_frame_info_offset()));
diff --git a/runtime/vm/stub_code_x64.cc b/runtime/vm/stub_code_x64.cc
index 16e0858..8132e99 100644
--- a/runtime/vm/stub_code_x64.cc
+++ b/runtime/vm/stub_code_x64.cc
@@ -740,11 +740,15 @@
__ movq(Address(kIsolateReg, Isolate::vm_tag_offset()),
Immediate(VMTag::kDartTagId));
- // Save the top exit frame info. Use RAX as a temporary register.
+ // Save top resource and top exit frame info. Use RAX as a temporary register.
// StackFrameIterator reads the top exit frame info saved in this frame.
+ __ movq(RAX, Address(kIsolateReg, Isolate::top_resource_offset()));
+ __ pushq(RAX);
+ __ movq(Address(kIsolateReg, Isolate::top_resource_offset()),
+ Immediate(0));
+ __ movq(RAX, Address(kIsolateReg, Isolate::top_exit_frame_info_offset()));
// The constant kExitLinkSlotFromEntryFp must be kept in sync with the
// code below.
- __ movq(RAX, Address(kIsolateReg, Isolate::top_exit_frame_info_offset()));
__ pushq(RAX);
#if defined(DEBUG)
{
@@ -756,7 +760,6 @@
__ Bind(&ok);
}
#endif
-
__ movq(Address(kIsolateReg, Isolate::top_exit_frame_info_offset()),
Immediate(0));
@@ -798,9 +801,11 @@
// Get rid of arguments pushed on the stack.
__ leaq(RSP, Address(RSP, RDX, TIMES_4, 0)); // RDX is a Smi.
- // Restore the saved top exit frame info back into the Isolate structure.
+ // Restore the saved top exit frame info and top resource back into the
+ // Isolate structure.
__ LoadIsolate(kIsolateReg);
__ popq(Address(kIsolateReg, Isolate::top_exit_frame_info_offset()));
+ __ popq(Address(kIsolateReg, Isolate::top_resource_offset()));
// Restore the current VMTag from the stack.
__ popq(Address(kIsolateReg, Isolate::vm_tag_offset()));
diff --git a/runtime/vm/symbols.h b/runtime/vm/symbols.h
index 90a1b41..a4dbc5a 100644
--- a/runtime/vm/symbols.h
+++ b/runtime/vm/symbols.h
@@ -79,6 +79,8 @@
V(StackTraceParameter, ":stack_trace") \
V(ExceptionVar, ":exception_var") \
V(StackTraceVar, ":stack_trace_var") \
+ V(SavedExceptionVar, ":saved_exception_var") \
+ V(SavedStackTraceVar, ":saved_stack_trace_var") \
V(ListLiteralElement, "list literal element") \
V(ForInIter, ":for-in-iter") \
V(Library, "library") \
@@ -175,7 +177,7 @@
V(_CapabilityImpl, "_CapabilityImpl") \
V(_RawReceivePortImpl, "_RawReceivePortImpl") \
V(_SendPortImpl, "_SendPortImpl") \
- V(StackTrace, "StackTrace") \
+ V(_StackTrace, "_StackTrace") \
V(JSSyntaxRegExp, "_JSSyntaxRegExp") \
V(RegExp, "RegExp") \
V(Irregexp, ":irregexp") \
@@ -285,7 +287,6 @@
V(IsolateUnhandledException, "_IsolateUnhandledException") \
V(JavascriptIntegerOverflowError, "_JavascriptIntegerOverflowError") \
V(JavascriptCompatibilityError, "_JavascriptCompatibilityError") \
- V(_setupFullStackTrace, "_setupFullStackTrace") \
V(BooleanExpression, "boolean expression") \
V(Malformed, "malformed") \
V(Malbounded, "malbounded") \
diff --git a/runtime/vm/vm_sources.gypi b/runtime/vm/vm_sources.gypi
index 46f92a3..5eaba92 100644
--- a/runtime/vm/vm_sources.gypi
+++ b/runtime/vm/vm_sources.gypi
@@ -383,8 +383,10 @@
'scopes.h',
'scopes_test.cc',
'service.cc',
- 'service_test.cc',
'service.h',
+ 'service_isolate.cc',
+ 'service_isolate.h',
+ 'service_test.cc',
'signal_handler_android.cc',
'signal_handler_linux.cc',
'signal_handler_macos.cc',
diff --git a/sdk/bin/pub b/sdk/bin/pub
index 1fd6864..1e787e0 100755
--- a/sdk/bin/pub
+++ b/sdk/bin/pub
@@ -52,6 +52,6 @@
DART="$BUILD_DIR/dart-sdk/bin/dart"
PACKAGES_DIR="$BUILD_DIR/packages/"
-# Run the async/await compiled pub.
-PUB="$SDK_DIR/lib/_internal/pub_generated/bin/pub.dart"
+# Run pub.
+PUB="$SDK_DIR/lib/_internal/pub/bin/pub.dart"
exec "$DART" "${VM_OPTIONS[@]}" "--package-root=$PACKAGES_DIR" "$PUB" "$@"
diff --git a/sdk/bin/pub.bat b/sdk/bin/pub.bat
index 98d5420..7fd3f91 100644
--- a/sdk/bin/pub.bat
+++ b/sdk/bin/pub.bat
@@ -23,14 +23,19 @@
set VM_OPTIONS=
+rem We allow extra vm options to be passed in through an environment variable.
+if not "_%DART_VM_OPTIONS%_" == "__" (
+ set VM_OPTIONS=%VM_OPTIONS% %DART_VM_OPTIONS%
+)
+
rem Use the Dart binary in the built SDK so pub can find the version file next
rem to it.
set BUILD_DIR=%SDK_DIR%\..\build\ReleaseIA32
set PACKAGES_DIR=%BUILD_DIR%\packages
set DART=%BUILD_DIR%\dart-sdk\bin\dart
-rem Run the async/await compiled pub.
-set PUB="%SDK_DIR%\lib\_internal\pub_generated\bin\pub.dart"
+rem Run pub.
+set PUB="%SDK_DIR%\lib\_internal\pub.dart"
"%DART%" %VM_OPTIONS% --package-root="%PACKAGES_DIR%" "%PUB%" %*
endlocal
diff --git a/sdk/bin/pub_sdk b/sdk/bin/pub_sdk
index ade0583..bf48a16 100755
--- a/sdk/bin/pub_sdk
+++ b/sdk/bin/pub_sdk
@@ -26,10 +26,6 @@
unset VM_OPTIONS
declare -a VM_OPTIONS
-# Give the VM extra memory for dart2js.
-# TODO(rnystrom): Remove when #8355 is fixed.
-VM_OPTIONS+=("--old_gen_heap_size=1024")
-
# Allow extra VM options to be passed in through an environment variable.
if [[ $DART_VM_OPTIONS ]]; then
read -a OPTIONS <<< "$DART_VM_OPTIONS"
diff --git a/sdk/bin/pub_sdk.bat b/sdk/bin/pub_sdk.bat
index 2c4977e..0f0024d 100644
--- a/sdk/bin/pub_sdk.bat
+++ b/sdk/bin/pub_sdk.bat
@@ -19,10 +19,10 @@
set VM_OPTIONS=
-rem Give the VM extra memory for dart2js.
-rem # TODO(rnystrom): Remove when #8355 is fixed.
-rem See comments regarding options below in dart2js shell script.
-set VM_OPTIONS=%VM_OPTIONS% --old_gen_heap_size=1024
+rem We allow extra vm options to be passed in through an environment variable.
+if not "_%DART_VM_OPTIONS%_" == "__" (
+ set VM_OPTIONS=%VM_OPTIONS% %DART_VM_OPTIONS%
+)
"%BIN_DIR%\dart" %VM_OPTIONS% "%BIN_DIR%\snapshots\pub.dart.snapshot" %*
diff --git a/sdk/lib/_internal/compiler/js_lib/async_patch.dart b/sdk/lib/_internal/compiler/js_lib/async_patch.dart
index e0813ad..1377957 100644
--- a/sdk/lib/_internal/compiler/js_lib/async_patch.dart
+++ b/sdk/lib/_internal/compiler/js_lib/async_patch.dart
@@ -121,5 +121,3 @@
return new TimerImpl.periodic(milliseconds, callback);
}
}
-
-bool get _hasDocument => JS('String', 'typeof document') == 'object';
diff --git a/sdk/lib/_internal/compiler/js_lib/collection_patch.dart b/sdk/lib/_internal/compiler/js_lib/collection_patch.dart
index 184e8ce..0d56162 100644
--- a/sdk/lib/_internal/compiler/js_lib/collection_patch.dart
+++ b/sdk/lib/_internal/compiler/js_lib/collection_patch.dart
@@ -5,7 +5,8 @@
// Patch file for dart:collection classes.
import 'dart:_foreign_helper' show JS;
import 'dart:_js_helper' show
- fillLiteralMap, InternalMap, NoInline, NoThrows, patch;
+ fillLiteralMap, InternalMap, NoInline, NoThrows, patch, JsLinkedHashMap,
+ LinkedHashMapCell, LinkedHashMapKeyIterable, LinkedHashMapKeyIterator;
@patch
class HashMap<K, V> {
@@ -491,7 +492,7 @@
if (isValidKey == null) {
if (hashCode == null) {
if (equals == null) {
- return new _LinkedHashMap<K, V>();
+ return new JsLinkedHashMap<K, V>();
}
hashCode = _defaultHashCode;
} else {
@@ -520,343 +521,36 @@
// Private factory constructor called by generated code for map literals.
@NoInline()
factory LinkedHashMap._literal(List keyValuePairs) {
- return fillLiteralMap(keyValuePairs, new _LinkedHashMap<K, V>());
+ return fillLiteralMap(keyValuePairs, new JsLinkedHashMap<K, V>());
}
// Private factory constructor called by generated code for map literals.
@NoThrows() @NoInline()
factory LinkedHashMap._empty() {
- return new _LinkedHashMap<K, V>();
+ return new JsLinkedHashMap<K, V>();
}
}
-class _LinkedHashMap<K, V> implements LinkedHashMap<K, V>, InternalMap {
- int _length = 0;
-
- // The hash map contents are divided into three parts: one part for
- // string keys, one for numeric keys, and one for the rest. String
- // and numeric keys map directly to their linked cells, but the rest
- // of the entries are stored in bucket lists of the form:
- //
- // [cell-0, cell-1, ...]
- //
- // where all keys in the same bucket share the same hash code.
- var _strings;
- var _nums;
- var _rest;
-
- // The keys and values are stored in cells that are linked together
- // to form a double linked list.
- LinkedHashMapCell _first;
- LinkedHashMapCell _last;
-
- // We track the number of modifications done to the key set of the
- // hash map to be able to throw when the map is modified while being
- // iterated over.
- int _modifications = 0;
-
- _LinkedHashMap();
-
-
- int get length => _length;
- bool get isEmpty => _length == 0;
- bool get isNotEmpty => !isEmpty;
-
- Iterable<K> get keys {
- return new LinkedHashMapKeyIterable<K>(this);
- }
-
- Iterable<V> get values {
- return new MappedIterable<K, V>(keys, (each) => this[each]);
- }
-
- bool containsKey(Object key) {
- if (_isStringKey(key)) {
- var strings = _strings;
- if (strings == null) return false;
- LinkedHashMapCell cell = _getTableEntry(strings, key);
- return cell != null;
- } else if (_isNumericKey(key)) {
- var nums = _nums;
- if (nums == null) return false;
- LinkedHashMapCell cell = _getTableEntry(nums, key);
- return cell != null;
- } else {
- return _containsKey(key);
- }
- }
-
- bool _containsKey(Object key) {
- var rest = _rest;
- if (rest == null) return false;
- var bucket = _getBucket(rest, key);
- return _findBucketIndex(bucket, key) >= 0;
- }
-
- bool containsValue(Object value) {
- return keys.any((each) => this[each] == value);
- }
-
- void addAll(Map<K, V> other) {
- other.forEach((K key, V value) {
- this[key] = value;
- });
- }
-
- V operator[](Object key) {
- if (_isStringKey(key)) {
- var strings = _strings;
- if (strings == null) return null;
- LinkedHashMapCell cell = _getTableEntry(strings, key);
- return (cell == null) ? null : cell._value;
- } else if (_isNumericKey(key)) {
- var nums = _nums;
- if (nums == null) return null;
- LinkedHashMapCell cell = _getTableEntry(nums, key);
- return (cell == null) ? null : cell._value;
- } else {
- return _get(key);
- }
- }
-
- V _get(Object key) {
- var rest = _rest;
- if (rest == null) return null;
- var bucket = _getBucket(rest, key);
- int index = _findBucketIndex(bucket, key);
- if (index < 0) return null;
- LinkedHashMapCell cell = JS('var', '#[#]', bucket, index);
- return cell._value;
- }
-
- void operator[]=(K key, V value) {
- if (_isStringKey(key)) {
- var strings = _strings;
- if (strings == null) _strings = strings = _newHashTable();
- _addHashTableEntry(strings, key, value);
- } else if (_isNumericKey(key)) {
- var nums = _nums;
- if (nums == null) _nums = nums = _newHashTable();
- _addHashTableEntry(nums, key, value);
- } else {
- _set(key, value);
- }
- }
-
- void _set(K key, V value) {
- var rest = _rest;
- if (rest == null) _rest = rest = _newHashTable();
- var hash = _computeHashCode(key);
- var bucket = JS('var', '#[#]', rest, hash);
- if (bucket == null) {
- LinkedHashMapCell cell = _newLinkedCell(key, value);
- _setTableEntry(rest, hash, JS('var', '[#]', cell));
- } else {
- int index = _findBucketIndex(bucket, key);
- if (index >= 0) {
- LinkedHashMapCell cell = JS('var', '#[#]', bucket, index);
- cell._value = value;
- } else {
- LinkedHashMapCell cell = _newLinkedCell(key, value);
- JS('void', '#.push(#)', bucket, cell);
- }
- }
- }
-
- V putIfAbsent(K key, V ifAbsent()) {
- if (containsKey(key)) return this[key];
- V value = ifAbsent();
- this[key] = value;
- return value;
- }
-
- V remove(Object key) {
- if (_isStringKey(key)) {
- return _removeHashTableEntry(_strings, key);
- } else if (_isNumericKey(key)) {
- return _removeHashTableEntry(_nums, key);
- } else {
- return _remove(key);
- }
- }
-
- V _remove(Object key) {
- var rest = _rest;
- if (rest == null) return null;
- var bucket = _getBucket(rest, key);
- int index = _findBucketIndex(bucket, key);
- if (index < 0) return null;
- // Use splice to remove the [cell] element at the index and
- // unlink the cell before returning its value.
- LinkedHashMapCell cell = JS('var', '#.splice(#, 1)[0]', bucket, index);
- _unlinkCell(cell);
- // TODO(kasperl): Consider getting rid of the bucket list when
- // the length reaches zero.
- return cell._value;
- }
-
- void clear() {
- if (_length > 0) {
- _strings = _nums = _rest = _first = _last = null;
- _length = 0;
- _modified();
- }
- }
-
- void forEach(void action(K key, V value)) {
- LinkedHashMapCell cell = _first;
- int modifications = _modifications;
- while (cell != null) {
- action(cell._key, cell._value);
- if (modifications != _modifications) {
- throw new ConcurrentModificationError(this);
- }
- cell = cell._next;
- }
- }
-
- void _addHashTableEntry(var table, K key, V value) {
- LinkedHashMapCell cell = _getTableEntry(table, key);
- if (cell == null) {
- _setTableEntry(table, key, _newLinkedCell(key, value));
- } else {
- cell._value = value;
- }
- }
-
- V _removeHashTableEntry(var table, Object key) {
- if (table == null) return null;
- LinkedHashMapCell cell = _getTableEntry(table, key);
- if (cell == null) return null;
- _unlinkCell(cell);
- _deleteTableEntry(table, key);
- return cell._value;
- }
-
- void _modified() {
- // Value cycles after 2^30 modifications. If you keep hold of an
- // iterator for that long, you might miss a modification
- // detection, and iteration can go sour. Don't do that.
- _modifications = (_modifications + 1) & 0x3ffffff;
- }
-
- // Create a new cell and link it in as the last one in the list.
- LinkedHashMapCell _newLinkedCell(K key, V value) {
- LinkedHashMapCell cell = new LinkedHashMapCell(key, value);
- if (_first == null) {
- _first = _last = cell;
- } else {
- LinkedHashMapCell last = _last;
- cell._previous = last;
- _last = last._next = cell;
- }
- _length++;
- _modified();
- return cell;
- }
-
- // Unlink the given cell from the linked list of cells.
- void _unlinkCell(LinkedHashMapCell cell) {
- LinkedHashMapCell previous = cell._previous;
- LinkedHashMapCell next = cell._next;
- if (previous == null) {
- assert(cell == _first);
- _first = next;
- } else {
- previous._next = next;
- }
- if (next == null) {
- assert(cell == _last);
- _last = previous;
- } else {
- next._previous = previous;
- }
- _length--;
- _modified();
- }
-
- static bool _isStringKey(var key) {
- return key is String && key != '__proto__';
- }
-
- static bool _isNumericKey(var key) {
- // Only treat unsigned 30-bit integers as numeric keys. This way,
- // we avoid converting them to strings when we use them as keys in
- // the JavaScript hash table object.
- return key is num && JS('bool', '(# & 0x3ffffff) === #', key, key);
- }
-
- int _computeHashCode(var key) {
- // We force the hash codes to be unsigned 30-bit integers to avoid
- // issues with problematic keys like '__proto__'. Another option
- // would be to throw an exception if the hash code isn't a number.
- return JS('int', '# & 0x3ffffff', key.hashCode);
- }
-
- static _getTableEntry(var table, var key) {
- return JS('var', '#[#]', table, key);
- }
-
- static void _setTableEntry(var table, var key, var value) {
- assert(value != null);
- JS('void', '#[#] = #', table, key, value);
- }
-
- static void _deleteTableEntry(var table, var key) {
- JS('void', 'delete #[#]', table, key);
- }
-
- List _getBucket(var table, var key) {
- var hash = _computeHashCode(key);
- return JS('var', '#[#]', table, hash);
- }
-
- int _findBucketIndex(var bucket, var key) {
- if (bucket == null) return -1;
- int length = JS('int', '#.length', bucket);
- for (int i = 0; i < length; i++) {
- LinkedHashMapCell cell = JS('var', '#[#]', bucket, i);
- if (cell._key == key) return i;
- }
- return -1;
- }
-
- static _newHashTable() {
- // Create a new JavaScript object to be used as a hash table. Use
- // Object.create to avoid the properties on Object.prototype
- // showing up as entries.
- var table = JS('var', 'Object.create(null)');
- // Attempt to force the hash table into 'dictionary' mode by
- // adding a property to it and deleting it again.
- var temporaryKey = '<non-identifier-key>';
- _setTableEntry(table, temporaryKey, table);
- _deleteTableEntry(table, temporaryKey);
- return table;
- }
-
- String toString() => Maps.mapToString(this);
-}
-
-class _LinkedIdentityHashMap<K, V> extends _LinkedHashMap<K, V> {
- int _computeHashCode(var key) {
+class _LinkedIdentityHashMap<K, V> extends JsLinkedHashMap<K, V> {
+ int internalComputeHashCode(var key) {
// We force the hash codes to be unsigned 30-bit integers to avoid
// issues with problematic keys like '__proto__'. Another option
// would be to throw an exception if the hash code isn't a number.
return JS('int', '# & 0x3ffffff', identityHashCode(key));
}
- int _findBucketIndex(var bucket, var key) {
+ int internalFindBucketIndex(var bucket, var key) {
if (bucket == null) return -1;
int length = JS('int', '#.length', bucket);
for (int i = 0; i < length; i++) {
LinkedHashMapCell cell = JS('var', '#[#]', bucket, i);
- if (identical(cell._key, key)) return i;
+ if (identical(cell.key, key)) return i;
}
return -1;
}
}
-class _LinkedCustomHashMap<K, V> extends _LinkedHashMap<K, V> {
+class _LinkedCustomHashMap<K, V> extends JsLinkedHashMap<K, V> {
final _Equality<K> _equals;
final _Hasher<K> _hashCode;
final _Predicate _validKey;
@@ -866,106 +560,41 @@
V operator[](Object key) {
if (!_validKey(key)) return null;
- return super._get(key);
+ return super.internalGet(key);
}
void operator[]=(K key, V value) {
- super._set(key, value);
+ super.internalSet(key, value);
}
bool containsKey(Object key) {
if (!_validKey(key)) return false;
- return super._containsKey(key);
+ return super.internalContainsKey(key);
}
V remove(Object key) {
if (!_validKey(key)) return null;
- return super._remove(key);
+ return super.internalRemove(key);
}
- int _computeHashCode(var key) {
+ int internalComputeHashCode(var key) {
// We force the hash codes to be unsigned 30-bit integers to avoid
// issues with problematic keys like '__proto__'. Another option
// would be to throw an exception if the hash code isn't a number.
return JS('int', '# & 0x3ffffff', _hashCode(key));
}
- int _findBucketIndex(var bucket, var key) {
+ int internalFindBucketIndex(var bucket, var key) {
if (bucket == null) return -1;
int length = JS('int', '#.length', bucket);
for (int i = 0; i < length; i++) {
LinkedHashMapCell cell = JS('var', '#[#]', bucket, i);
- if (_equals(cell._key, key)) return i;
+ if (_equals(cell.key, key)) return i;
}
return -1;
}
}
-class LinkedHashMapCell {
- final _key;
- var _value;
-
- LinkedHashMapCell _next;
- LinkedHashMapCell _previous;
-
- LinkedHashMapCell(this._key, this._value);
-}
-
-class LinkedHashMapKeyIterable<E> extends IterableBase<E>
- implements EfficientLength {
- final _map;
- LinkedHashMapKeyIterable(this._map);
-
- int get length => _map._length;
- bool get isEmpty => _map._length == 0;
-
- Iterator<E> get iterator {
- return new LinkedHashMapKeyIterator<E>(_map, _map._modifications);
- }
-
- bool contains(Object element) {
- return _map.containsKey(element);
- }
-
- void forEach(void f(E element)) {
- LinkedHashMapCell cell = _map._first;
- int modifications = _map._modifications;
- while (cell != null) {
- f(cell._key);
- if (modifications != _map._modifications) {
- throw new ConcurrentModificationError(_map);
- }
- cell = cell._next;
- }
- }
-}
-
-class LinkedHashMapKeyIterator<E> implements Iterator<E> {
- final _map;
- final int _modifications;
- LinkedHashMapCell _cell;
- E _current;
-
- LinkedHashMapKeyIterator(this._map, this._modifications) {
- _cell = _map._first;
- }
-
- E get current => _current;
-
- bool moveNext() {
- if (_modifications != _map._modifications) {
- throw new ConcurrentModificationError(_map);
- } else if (_cell == null) {
- _current = null;
- return false;
- } else {
- _current = _cell._key;
- _cell = _cell._next;
- return true;
- }
- }
-}
-
@patch
class HashSet<E> {
@patch
diff --git a/sdk/lib/_internal/compiler/js_lib/constant_map.dart b/sdk/lib/_internal/compiler/js_lib/constant_map.dart
index 181e522..1742e61 100644
--- a/sdk/lib/_internal/compiler/js_lib/constant_map.dart
+++ b/sdk/lib/_internal/compiler/js_lib/constant_map.dart
@@ -112,11 +112,15 @@
// We cannot create the backing map on creation since hashCode interceptors
// have not been defined when constants are created.
Map<K, V> _getMap() {
- if (JS('bool', r'!this.$map')) {
- Map backingMap = new LinkedHashMap<K, V>();
- JS('', r'this.$map = #', fillLiteralMap(_jsData, backingMap));
+<<<<<<< .working
+ LinkedHashMap<K, V> backingMap = JS('LinkedHashMap|Null', r'#.$map', this);
+ if (backingMap == null) {
+ backingMap = new JsLinkedHashMap<K, V>();
+ fillLiteralMap(_jsData, backingMap);
+ JS('', r'#.$map = #', this, backingMap);
+>>>>>>> .merge-right.r43886
}
- return JS('Map', r'this.$map');
+ return backingMap;
}
bool containsValue(V needle) {
diff --git a/sdk/lib/_internal/compiler/js_lib/core_patch.dart b/sdk/lib/_internal/compiler/js_lib/core_patch.dart
index 0485767..21be5ac 100644
--- a/sdk/lib/_internal/compiler/js_lib/core_patch.dart
+++ b/sdk/lib/_internal/compiler/js_lib/core_patch.dart
@@ -71,8 +71,8 @@
static apply(Function function,
List positionalArguments,
[Map<Symbol, dynamic> namedArguments]) {
- //TODO(zarah): implement for new emitter.
- throw new UnsupportedError('Function.apply is currently not supported.');
+ return Primitives.applyFunctionNewEmitter(function, positionalArguments,
+ namedArguments == null ? null : _symbolMapToStringMap(namedArguments));
}
static Map<String, dynamic> _toMangledNames(
diff --git a/sdk/lib/_internal/compiler/js_lib/interceptors.dart b/sdk/lib/_internal/compiler/js_lib/interceptors.dart
index 7203a7b..e9f5422 100644
--- a/sdk/lib/_internal/compiler/js_lib/interceptors.dart
+++ b/sdk/lib/_internal/compiler/js_lib/interceptors.dart
@@ -30,6 +30,7 @@
stringReplaceAllFuncUnchecked,
stringReplaceAllUnchecked,
stringReplaceFirstUnchecked,
+ stringReplaceFirstMappedUnchecked,
lookupAndCacheInterceptor,
lookupDispatchRecord,
StringMatch,
diff --git a/sdk/lib/_internal/compiler/js_lib/js_array.dart b/sdk/lib/_internal/compiler/js_lib/js_array.dart
index 615ed61..a170af2 100644
--- a/sdk/lib/_internal/compiler/js_lib/js_array.dart
+++ b/sdk/lib/_internal/compiler/js_lib/js_array.dart
@@ -114,12 +114,23 @@
void insertAll(int index, Iterable<E> iterable) {
checkGrowable('insertAll');
- IterableMixinWorkaround.insertAllList(this, index, iterable);
+ RangeError.checkValueInInterval(index, 0, this.length, "index");
+ if (iterable is! EfficientLength) {
+ iterable = iterable.toList();
+ }
+ int insertionLength = iterable.length;
+ this.length += insertionLength;
+ int end = index + insertionLength;
+ this.setRange(end, this.length, this, index);
+ this.setRange(index, end, iterable);
}
void setAll(int index, Iterable<E> iterable) {
checkMutable('setAll');
- IterableMixinWorkaround.setAllList(this, index, iterable);
+ RangeError.checkValueInInterval(index, 0, this.length, "index");
+ for (var element in iterable) {
+ this[index++] = element;
+ }
}
E removeLast() {
@@ -139,22 +150,52 @@
return false;
}
+ /**
+ * Removes elements matching [test] from [this] List.
+ */
void removeWhere(bool test(E element)) {
- // This could, and should, be optimized.
- IterableMixinWorkaround.removeWhereList(this, test);
+ checkGrowable('removeWhere');
+ _removeWhere(test, true);
}
void retainWhere(bool test(E element)) {
- IterableMixinWorkaround.removeWhereList(this,
- (E element) => !test(element));
+ checkGrowable('retainWhere');
+ _removeWhere(test, false);
+ }
+
+ void _removeWhere(bool test(E element), bool removeMatching) {
+ // Performed in two steps, to avoid exposing an inconsistent state
+ // to the [test] function. First the elements to retain are found, and then
+ // the original list is updated to contain those elements.
+
+ // TODO(sra): Replace this algorthim with one that retains a list of ranges
+ // to be removed. Most real uses remove 0, 1 or a few clustered elements.
+
+ List retained = [];
+ int end = this.length;
+ for (int i = 0; i < end; i++) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ // !test() ensures bool conversion in checked mode.
+ if (!test(element) == removeMatching) {
+ retained.add(element);
+ }
+ if (this.length != end) throw new ConcurrentModificationError(this);
+ }
+ if (retained.length == end) return;
+ this.length = retained.length;
+ for (int i = 0; i < retained.length; i++) {
+ this[i] = retained[i];
+ }
}
Iterable<E> where(bool f(E element)) {
- return new IterableMixinWorkaround<E>().where(this, f);
+ return new WhereIterable<E>(this, f);
}
Iterable expand(Iterable f(E element)) {
- return IterableMixinWorkaround.expand(this, f);
+ return new ExpandIterable<E, dynamic>(this, f);
}
void addAll(Iterable<E> collection) {
@@ -168,17 +209,18 @@
}
void forEach(void f(E element)) {
- int length = this.length;
- for (int i = 0; i < length; i++) {
- f(JS('', '#[#]', this, i));
- if (length != this.length) {
- throw new ConcurrentModificationError(this);
- }
+ int end = this.length;
+ for (int i = 0; i < end; i++) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ f(element);
+ if (this.length != end) throw new ConcurrentModificationError(this);
}
}
Iterable map(f(E element)) {
- return IterableMixinWorkaround.mapList(this, f);
+ return new MappedListIterable(this, f);
}
String join([String separator = ""]) {
@@ -190,39 +232,97 @@
}
Iterable<E> take(int n) {
- return new IterableMixinWorkaround<E>().takeList(this, n);
+ return new SubListIterable<E>(this, 0, n);
}
Iterable<E> takeWhile(bool test(E value)) {
- return new IterableMixinWorkaround<E>().takeWhile(this, test);
+ return new TakeWhileIterable<E>(this, test);
}
Iterable<E> skip(int n) {
- return new IterableMixinWorkaround<E>().skipList(this, n);
+ return new SubListIterable<E>(this, n, null);
}
Iterable<E> skipWhile(bool test(E value)) {
- return new IterableMixinWorkaround<E>().skipWhile(this, test);
+ return new SkipWhileIterable<E>(this, test);
}
- E reduce(E combine(E value, E element)) {
- return IterableMixinWorkaround.reduce(this, combine);
+ E reduce(E combine(E previousValue, E element)) {
+ int length = this.length;
+ if (length == 0) throw IterableElementError.noElement();
+ E value = this[0];
+ for (int i = 1; i < length; i++) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ value = combine(value, element);
+ if (length != this.length) throw new ConcurrentModificationError(this);
+ }
+ return value;
}
- fold(initialValue, combine(previousValue, E element)) {
- return IterableMixinWorkaround.fold(this, initialValue, combine);
+ fold(var initialValue, combine(var previousValue, E element)) {
+ var value = initialValue;
+ int length = this.length;
+ for (int i = 0; i < length; i++) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ value = combine(value, element);
+ if (this.length != length) throw new ConcurrentModificationError(this);
+ }
+ return value;
}
E firstWhere(bool test(E value), {E orElse()}) {
- return IterableMixinWorkaround.firstWhere(this, test, orElse);
+ var end = this.length;
+ for (int i = 0; i < end; ++i) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ if (test(element)) return element;
+ if (this.length != end) throw new ConcurrentModificationError(this);
+ }
+ if (orElse != null) return orElse();
+ throw IterableElementError.noElement();
}
- E lastWhere(bool test(E value), {E orElse()}) {
- return IterableMixinWorkaround.lastWhereList(this, test, orElse);
+ E lastWhere(bool test(E element), { E orElse() }) {
+ int length = this.length;
+ for (int i = length - 1; i >= 0; i--) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ if (test(element)) return element;
+ if (length != this.length) {
+ throw new ConcurrentModificationError(this);
+ }
+ }
+ if (orElse != null) return orElse();
+ throw IterableElementError.noElement();
}
- E singleWhere(bool test(E value)) {
- return IterableMixinWorkaround.singleWhere(this, test);
+ E singleWhere(bool test(E element)) {
+ int length = this.length;
+ E match = null;
+ bool matchFound = false;
+ for (int i = 0; i < length; i++) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ if (test(element)) {
+ if (matchFound) {
+ throw IterableElementError.tooMany();
+ }
+ matchFound = true;
+ match = element;
+ }
+ if (length != this.length) {
+ throw new ConcurrentModificationError(this);
+ }
+ }
+ if (matchFound) return match;
+ throw IterableElementError.noElement();
}
E elementAt(int index) {
@@ -250,79 +350,185 @@
Iterable<E> getRange(int start, int end) {
- return new IterableMixinWorkaround<E>().getRangeList(this, start, end);
+ RangeError.checkValidRange(start, end, this.length);
+ return new SubListIterable<E>(this, start, end);
}
E get first {
if (length > 0) return this[0];
- throw new StateError("No elements");
+ throw IterableElementError.noElement();
}
E get last {
if (length > 0) return this[length - 1];
- throw new StateError("No elements");
+ throw IterableElementError.noElement();
}
E get single {
if (length == 1) return this[0];
- if (length == 0) throw new StateError("No elements");
- throw new StateError("More than one element");
+ if (length == 0) throw IterableElementError.noElement();
+ throw IterableElementError.tooMany();
}
void removeRange(int start, int end) {
checkGrowable('removeRange');
- int receiverLength = this.length;
- if (start < 0 || start > receiverLength) {
- throw new RangeError.range(start, 0, receiverLength);
- }
- if (end < start || end > receiverLength) {
- throw new RangeError.range(end, start, receiverLength);
- }
- Lists.copy(this,
- end,
- this,
- start,
- receiverLength - end);
- this.length = receiverLength - (end - start);
+ RangeError.checkValidRange(start, end, this.length);
+ int deleteCount = end - start;
+ JS('', '#.splice(#, #)', this, start, deleteCount);
}
void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) {
checkMutable('set range');
- IterableMixinWorkaround.setRangeList(this, start, end, iterable, skipCount);
+
+ RangeError.checkValidRange(start, end, this.length);
+ int length = end - start;
+ if (length == 0) return;
+ RangeError.checkNotNegative(skipCount, "skipCount");
+
+ List otherList;
+ int otherStart;
+ // TODO(floitsch): Make this accept more.
+ if (iterable is List) {
+ otherList = iterable;
+ otherStart = skipCount;
+ } else {
+ otherList = iterable.skip(skipCount).toList(growable: false);
+ otherStart = 0;
+ }
+ if (otherStart + length > otherList.length) {
+ throw IterableElementError.tooFew();
+ }
+ if (otherStart < start) {
+ // Copy backwards to ensure correct copy if [from] is this.
+ // TODO(sra): If [from] is the same Array as [this], we can copy without
+ // type annotation checks on the stores.
+ for (int i = length - 1; i >= 0; i--) {
+ // Use JS to avoid bounds check (the bounds check elimination
+ // optimzation is too weak). The 'E' type annotation is a store type
+ // check - we can't rely on iterable, it could be List<dynamic>.
+ E element = otherList[otherStart + i];
+ JS('', '#[#] = #', this, start + i, element);
+ }
+ } else {
+ for (int i = 0; i < length; i++) {
+ E element = otherList[otherStart + i];
+ JS('', '#[#] = #', this, start + i, element);
+ }
+ }
}
void fillRange(int start, int end, [E fillValue]) {
checkMutable('fill range');
- IterableMixinWorkaround.fillRangeList(this, start, end, fillValue);
+ RangeError.checkValidRange(start, end, this.length);
+ for (int i = start; i < end; i++) {
+ // Store is safe since [fillValue] type has been checked as parameter.
+ JS('', '#[#] = #', this, i, fillValue);
+ }
}
- void replaceRange(int start, int end, Iterable<E> iterable) {
- checkGrowable('removeRange');
- IterableMixinWorkaround.replaceRangeList(this, start, end, iterable);
+ void replaceRange(int start, int end, Iterable<E> replacement) {
+ checkGrowable('replace range');
+ RangeError.checkValidRange(start, end, this.length);
+ if (replacement is! EfficientLength) {
+ replacement = replacement.toList();
+ }
+ int removeLength = end - start;
+ int insertLength = replacement.length;
+ if (removeLength >= insertLength) {
+ int delta = removeLength - insertLength;
+ int insertEnd = start + insertLength;
+ int newLength = this.length - delta;
+ this.setRange(start, insertEnd, replacement);
+ if (delta != 0) {
+ this.setRange(insertEnd, newLength, this, end);
+ this.length = newLength;
+ }
+ } else {
+ int delta = insertLength - removeLength;
+ int newLength = this.length + delta;
+ int insertEnd = start + insertLength; // aka. end + delta.
+ this.length = newLength;
+ this.setRange(insertEnd, newLength, this, end);
+ this.setRange(start, insertEnd, replacement);
+ }
}
- bool any(bool f(E element)) => IterableMixinWorkaround.any(this, f);
+ bool any(bool test(E element)) {
+ int end = this.length;
+ for (int i = 0; i < end; i++) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ if (test(element)) return true;
+ if (this.length != end) throw new ConcurrentModificationError(this);
+ }
+ return false;
+ }
- bool every(bool f(E element)) => IterableMixinWorkaround.every(this, f);
+ bool every(bool test(E element)) {
+ int end = this.length;
+ for (int i = 0; i < end; i++) {
+ // TODO(22407): Improve bounds check elimination to allow this JS code to
+ // be replaced by indexing.
+ var element = JS('', '#[#]', this, i);
+ if (!test(element)) return false;
+ if (this.length != end) throw new ConcurrentModificationError(this);
+ }
+ return true;
+ }
- Iterable<E> get reversed =>
- new IterableMixinWorkaround<E>().reversedList(this);
+ Iterable<E> get reversed => new ReversedListIterable<E>(this);
void sort([int compare(E a, E b)]) {
checkMutable('sort');
- IterableMixinWorkaround.sortList(this, compare);
+ Sort.sort(this, compare == null ? Comparable.compare : compare);
}
void shuffle([Random random]) {
- IterableMixinWorkaround.shuffleList(this, random);
+ checkMutable('shuffle');
+ if (random == null) random = new Random();
+ int length = this.length;
+ while (length > 1) {
+ int pos = random.nextInt(length);
+ length -= 1;
+ var tmp = this[length];
+ this[length] = this[pos];
+ this[pos] = tmp;
+ }
}
int indexOf(Object element, [int start = 0]) {
- return IterableMixinWorkaround.indexOfList(this, element, start);
+ if (start >= this.length) {
+ return -1;
+ }
+ if (start < 0) {
+ start = 0;
+ }
+ for (int i = start; i < this.length; i++) {
+ if (this[i] == element) {
+ return i;
+ }
+ }
+ return -1;
}
- int lastIndexOf(Object element, [int start]) {
- return IterableMixinWorkaround.lastIndexOfList(this, element, start);
+ int lastIndexOf(Object element, [int startIndex]) {
+ if (startIndex == null) {
+ startIndex = this.length - 1;
+ } else {
+ if (startIndex < 0) {
+ return -1;
+ }
+ if (startIndex >= this.length) {
+ startIndex = this.length - 1;
+ }
+ }
+ for (int i = startIndex; i >= 0; i--) {
+ if (this[i] == element) {
+ return i;
+ }
+ }
+ return -1;
}
bool contains(Object other) {
@@ -375,7 +581,7 @@
}
Map<int, E> asMap() {
- return new IterableMixinWorkaround<E>().asMapList(this);
+ return new ListMapView<E>(this);
}
}
diff --git a/sdk/lib/_internal/compiler/js_lib/js_helper.dart b/sdk/lib/_internal/compiler/js_lib/js_helper.dart
index 49107bc..4376b05 100644
--- a/sdk/lib/_internal/compiler/js_lib/js_helper.dart
+++ b/sdk/lib/_internal/compiler/js_lib/js_helper.dart
@@ -21,6 +21,7 @@
NATIVE_SUPERCLASS_TAG_NAME;
import 'dart:collection';
+
import 'dart:_isolate_helper' show
IsolateNatives,
enterJsAsync,
@@ -67,7 +68,7 @@
import 'dart:_interceptors';
import 'dart:_internal' as _symbol_dev;
-import 'dart:_internal' show MappedIterable;
+import 'dart:_internal' show MappedIterable, EfficientLength;
import 'dart:_native_typed_data';
@@ -83,6 +84,7 @@
part 'regexp_helper.dart';
part 'string_helper.dart';
part 'js_rti.dart';
+part 'linked_hash_map.dart';
/// Marks the internal map in dart2js, so that internal libraries can is-check
/// them.
@@ -1045,6 +1047,68 @@
namedArgumentList));
}
+ static applyFunctionNewEmitter(Function function,
+ List positionalArguments,
+ Map<String, dynamic> namedArguments) {
+ if (namedArguments == null) {
+ int requiredParameterCount = JS('int', r'#[#]', function,
+ JS_GET_NAME("REQUIRED_PARAMETER_PROPERTY"));
+ int argumentCount = positionalArguments.length;
+ if (argumentCount < requiredParameterCount) {
+ return functionNoSuchMethod(function, positionalArguments, null);
+ }
+ String selectorName = '${JS_GET_NAME("CALL_PREFIX")}\$$argumentCount';
+ var jsStub = JS('var', r'#[#]', function, selectorName);
+ if (jsStub == null) {
+ // Do a dynamic call.
+ var interceptor = getInterceptor(function);
+ var jsFunction = JS('', '#[#]', interceptor,
+ JS_GET_NAME('CALL_CATCH_ALL'));
+ var defaultValues = JS('var', r'#[#]', function,
+ JS_GET_NAME("DEFAULT_VALUES_PROPERTY"));
+ if (!JS('bool', '# instanceof Array', defaultValues)) {
+ // The function expects named arguments!
+ return functionNoSuchMethod(function, positionalArguments, null);
+ }
+ int defaultsLength = JS('int', "#.length", defaultValues);
+ int maxArguments = requiredParameterCount + defaultsLength;
+ if (argumentCount > maxArguments) {
+ // The function expects less arguments!
+ return functionNoSuchMethod(function, positionalArguments, null);
+ }
+ List arguments = new List.from(positionalArguments);
+ List missingDefaults = JS('JSArray', '#.slice(#)', defaultValues,
+ argumentCount - requiredParameterCount);
+ arguments.addAll(missingDefaults);
+ return JS('var', '#.apply(#, #)', jsFunction, function, arguments);
+ }
+ return JS('var', '#.apply(#, #)', jsStub, function, positionalArguments);
+ } else {
+ var interceptor = getInterceptor(function);
+ var jsFunction = JS('', '#[#]', interceptor,
+ JS_GET_NAME('CALL_CATCH_ALL'));
+ var defaultValues = JS('JSArray', r'#[#]', function,
+ JS_GET_NAME("DEFAULT_VALUES_PROPERTY"));
+ List keys = JS('JSArray', r'Object.keys(#)', defaultValues);
+ List arguments = new List.from(positionalArguments);
+ int used = 0;
+ for (String key in keys) {
+ var value = namedArguments[key];
+ if (value != null) {
+ used++;
+ arguments.add(value);
+ } else {
+ arguments.add(JS('var', r'#[#]', defaultValues, key));
+ }
+ }
+ if (used != namedArguments.length) {
+ return functionNoSuchMethod(function, positionalArguments,
+ namedArguments);
+ }
+ return JS('var', r'#.apply(#, #)', jsFunction, function, arguments);
+ }
+ }
+
static applyFunction(Function function,
List positionalArguments,
Map<String, dynamic> namedArguments) {
@@ -1079,11 +1143,22 @@
String selectorName = '${JS_GET_NAME("CALL_PREFIX")}\$$argumentCount';
var jsFunction = JS('var', '#[#]', function, selectorName);
if (jsFunction == null) {
+ var interceptor = getInterceptor(function);
+ jsFunction = JS('', '#["call*"]', interceptor);
- // TODO(ahe): This might occur for optional arguments if there is no call
- // selector with that many arguments.
-
- return functionNoSuchMethod(function, positionalArguments, null);
+ if (jsFunction == null) {
+ return functionNoSuchMethod(function, positionalArguments, null);
+ }
+ ReflectionInfo info = new ReflectionInfo(jsFunction);
+ int maxArgumentCount = info.requiredParameterCount +
+ info.optionalParameterCount;
+ if (info.areOptionalParametersNamed || maxArgumentCount < argumentCount) {
+ return functionNoSuchMethod(function, positionalArguments, null);
+ }
+ arguments = new List.from(arguments);
+ for (int pos = argumentCount; pos < maxArgumentCount; pos++) {
+ arguments.add(info.defaultValue(pos));
+ }
}
// We bound 'this' to [function] because of how we compile
// closures: escaped local variables are stored and accessed through
@@ -1101,7 +1176,7 @@
// TODO(ahe): The following code can be shared with
// JsInstanceMirror.invoke.
var interceptor = getInterceptor(function);
- var jsFunction = JS('', '#["call*"]', interceptor);
+ var jsFunction = JS('', '#[#]', interceptor, JS_GET_NAME('CALL_CATCH_ALL'));
if (jsFunction == null) {
return functionNoSuchMethod(
@@ -1707,6 +1782,9 @@
// Note that we are checking if the object has the property. If it
// has, it could be set to null if the thrown value is null.
if (ex == null) return null;
+ if (ex is ExceptionAndStackTrace) {
+ return saveStackTrace(ex.dartException);
+ }
if (JS('bool', 'typeof # !== "object"', ex)) return ex;
if (JS('bool', r'"dartException" in #', ex)) {
@@ -1830,7 +1908,12 @@
* Called by generated code to fetch the stack trace from an
* exception. Should never return null.
*/
-StackTrace getTraceFromException(exception) => new _StackTrace(exception);
+StackTrace getTraceFromException(exception) {
+ if (exception is ExceptionAndStackTrace) {
+ return exception.stackTrace;
+ }
+ return new _StackTrace(exception);
+}
class _StackTrace implements StackTrace {
var _exception;
@@ -1841,7 +1924,8 @@
if (_trace != null) return JS('String', '#', _trace);
String trace;
- if (JS('bool', 'typeof # === "object"', _exception)) {
+ if (JS('bool', '# !== null', _exception) &&
+ JS('bool', 'typeof # === "object"', _exception)) {
trace = JS("String|Null", r"#.stack", _exception);
}
return _trace = (trace == null) ? '' : trace;
@@ -1985,7 +2069,8 @@
// through the namer.
var function = JS('', '#[#]', functions, 0);
String name = JS('String|Null', '#.\$stubName', function);
- String callName = JS('String|Null', '#.\$callName', function);
+ String callName = JS('String|Null', '#[#]', function,
+ JS_GET_NAME("CALL_NAME_PROPERTY"));
var functionType;
if (reflectionInfo is List) {
@@ -2087,14 +2172,19 @@
JS('', '#[#] = #', prototype, callName, trampoline);
for (int i = 1; i < functions.length; i++) {
var stub = functions[i];
- var stubCallName = JS('String|Null', '#.\$callName', stub);
+ var stubCallName = JS('String|Null', '#[#]', stub,
+ JS_GET_NAME("CALL_NAME_PROPERTY"));
if (stubCallName != null) {
JS('', '#[#] = #', prototype, stubCallName,
isStatic ? stub : forwardCallTo(receiver, stub, isIntercepted));
}
}
- JS('', '#["call*"] = #', prototype, trampoline);
+ JS('', '#[#] = #', prototype, JS_GET_NAME('CALL_CATCH_ALL'), trampoline);
+ String reqArgProperty = JS_GET_NAME("REQUIRED_PARAMETER_PROPERTY");
+ String defValProperty = JS_GET_NAME("DEFAULT_VALUES_PROPERTY");
+ JS('', '#.# = #.#', prototype, reqArgProperty, function, reqArgProperty);
+ JS('', '#.# = #.#', prototype, defValProperty, function, defValProperty);
return constructor;
}
@@ -3472,6 +3562,15 @@
throw new MainError("'main' expects too many parameters.");
}
+/// A wrapper around an exception, much like the one created by [wrapException]
+/// but with a pre-given stack-trace.
+class ExceptionAndStackTrace {
+ dynamic dartException;
+ StackTrace stackTrace;
+
+ ExceptionAndStackTrace(this.dartException, this.stackTrace);
+}
+
/// Runtime support for async-await transformation.
///
/// This function is called by a transformed function on each await and return
@@ -3503,15 +3602,35 @@
Future future = object is Future ? object : new Future.value(object);
future.then(_wrapJsFunctionForAsync(bodyFunctionOrErrorCode,
async_error_codes.SUCCESS),
- onError: _wrapJsFunctionForAsync(bodyFunctionOrErrorCode,
- async_error_codes.ERROR));
+ onError: (dynamic error, StackTrace stackTrace) {
+ ExceptionAndStackTrace wrapped =
+ new ExceptionAndStackTrace(error, stackTrace);
+ return _wrapJsFunctionForAsync(bodyFunctionOrErrorCode,
+ async_error_codes.ERROR)(wrapped);
+ });
return completer.future;
}
Function _wrapJsFunctionForAsync(dynamic /* js function */ function,
int errorCode) {
+ var protected = JS('', """
+ // Invokes [function] with [errorCode] and [result].
+ //
+ // If (and as long as) the invocation throws, calls [function] again,
+ // with an error-code.
+ function(errorCode, result) {
+ while (true) {
+ try {
+ #(errorCode, result);
+ break;
+ } catch (error) {
+ result = error;
+ errorCode = #;
+ }
+ }
+ }""", function, async_error_codes.ERROR);
return (result) {
- JS('', '#(#, #)', function, errorCode, result);
+ JS('', '#(#, #)', protected, errorCode, result);
};
}
@@ -3603,8 +3722,13 @@
Future future = object is Future ? object : new Future.value(object);
future.then(_wrapJsFunctionForAsync(bodyFunctionOrErrorCode,
async_error_codes.SUCCESS),
- onError: _wrapJsFunctionForAsync(bodyFunctionOrErrorCode,
- async_error_codes.ERROR));
+ onError: (error, StackTrace stackTrace) {
+ ExceptionAndStackTrace wrapped =
+ new ExceptionAndStackTrace(error, stackTrace);
+ return _wrapJsFunctionForAsync(bodyFunctionOrErrorCode,
+ async_error_codes.ERROR)
+ (wrapped);
+ });
}
Stream streamOfController(AsyncStarStreamController controller) {
@@ -3629,16 +3753,18 @@
addError(error, stackTrace) => controller.addError(error, stackTrace);
close() => controller.close();
- AsyncStarStreamController(helperCallback) {
+ AsyncStarStreamController(body) {
controller = new StreamController(
onListen: () {
scheduleMicrotask(() {
- JS('', '#(#, null)', helperCallback, async_error_codes.SUCCESS);
+ Function wrapped = _wrapJsFunctionForAsync(body,
+ async_error_codes.SUCCESS);
+ wrapped(null);
});
},
onResume: () {
if (!isAdding) {
- asyncStarHelper(null, helperCallback, this);
+ asyncStarHelper(null, body, this);
}
}, onCancel: () {
stopRunning = true;
@@ -3646,8 +3772,8 @@
}
}
-makeAsyncStarController(helperCallback) {
- return new AsyncStarStreamController(helperCallback);
+makeAsyncStarController(body) {
+ return new AsyncStarStreamController(body);
}
class IterationMarker {
@@ -3681,7 +3807,7 @@
}
class SyncStarIterator implements Iterator {
- final Function _body;
+ final dynamic _body;
// If [runningNested] this is the nested iterator, otherwise it is the
// current value.
@@ -3690,8 +3816,27 @@
get current => _runningNested ? _current.current : _current;
- SyncStarIterator(body)
- : _body = (() => JS('', '#()', body));
+ SyncStarIterator(this._body);
+
+ runBody() {
+ return JS('', '''
+ // Invokes [body] with [errorCode] and [result].
+ //
+ // If (and as long as) the invocation throws, calls [function] again,
+ // with an error-code.
+ (function(body) {
+ var errorValue, errorCode = #;
+ while (true) {
+ try {
+ return body(errorCode, errorValue);
+ } catch (error) {
+ errorValue = error;
+ errorCode = #
+ }
+ }
+ })(#)''', async_error_codes.SUCCESS, async_error_codes.ERROR, _body);
+ }
+
bool moveNext() {
if (_runningNested) {
@@ -3701,7 +3846,7 @@
_runningNested = false;
}
}
- _current = _body();
+ _current = runBody();
if (_current is IterationMarker) {
if (_current.state == IterationMarker.ITERATION_ENDED) {
_current = null;
diff --git a/sdk/lib/_internal/compiler/js_lib/js_mirrors.dart b/sdk/lib/_internal/compiler/js_lib/js_mirrors.dart
index 9d55eed..2b00057 100644
--- a/sdk/lib/_internal/compiler/js_lib/js_mirrors.dart
+++ b/sdk/lib/_internal/compiler/js_lib/js_mirrors.dart
@@ -2234,7 +2234,9 @@
String callPrefix = "${JS_GET_NAME("CALL_PREFIX")}\$";
var extractCallName = JS('', r'''
function(reflectee) {
- for (var property in reflectee) {
+ var properties = Object.keys(reflectee.constructor.prototype);
+ for (var i = 0; i < properties.length; i++) {
+ var property = properties[i];
if (# == property.substring(0, #) &&
property[#] >= '0' &&
property[#] <= '9') return property;
diff --git a/sdk/lib/_internal/compiler/js_lib/js_names.dart b/sdk/lib/_internal/compiler/js_lib/js_names.dart
index 3933e78..87cc6c0 100644
--- a/sdk/lib/_internal/compiler/js_lib/js_names.dart
+++ b/sdk/lib/_internal/compiler/js_lib/js_names.dart
@@ -79,14 +79,7 @@
@NoInline()
List extractKeys(victim) {
- var result = JS('', '''
-(function(victim, hasOwnProperty) {
- var result = [];
- for (var key in victim) {
- if (hasOwnProperty.call(victim, key)) result.push(key);
- }
- return result;
-})(#, Object.prototype.hasOwnProperty)''', victim);
+ var result = JS('', '# ? Object.keys(#) : []', victim, victim);
return new JSArray.markFixed(result);
}
diff --git a/sdk/lib/_internal/compiler/js_lib/js_number.dart b/sdk/lib/_internal/compiler/js_lib/js_number.dart
index a94b46b..c05f4f4 100644
--- a/sdk/lib/_internal/compiler/js_lib/js_number.dart
+++ b/sdk/lib/_internal/compiler/js_lib/js_number.dart
@@ -72,13 +72,33 @@
return JS('int', r'# + 0', truncateToDouble()); // Converts -0.0 to +0.0.
}
// This is either NaN, Infinity or -Infinity.
- throw new UnsupportedError(JS("String", "''+#", this));
+ throw new UnsupportedError(JS("String", '"" + #', this));
}
int truncate() => toInt();
+
int ceil() => ceilToDouble().toInt();
+
int floor() => floorToDouble().toInt();
- int round() => roundToDouble().toInt();
+
+ int round() {
+ if (this > 0) {
+ // This path excludes the special cases -0.0, NaN and -Infinity, leaving
+ // only +Infinity, for which a direct test is faster than [isFinite].
+ if (JS('bool', r'# !== (1/0)', this)) {
+ return JS('int', r'Math.round(#)', this);
+ }
+ } else if (JS('bool', '# > (-1/0)', this)) {
+ // This test excludes NaN and -Infinity, leaving only -0.0.
+ //
+ // Subtraction from zero rather than negation forces -0.0 to 0.0 so code
+ // inside Math.round and code to handle result never sees -0.0, which on
+ // some JavaScript VMs can be a slow path.
+ return JS('int', r'0 - Math.round(0 - #)', this);
+ }
+ // This is either NaN, Infinity or -Infinity.
+ throw new UnsupportedError(JS("String", '"" + #', this));
+ }
double ceilToDouble() => JS('num', r'Math.ceil(#)', this);
diff --git a/sdk/lib/_internal/compiler/js_lib/js_string.dart b/sdk/lib/_internal/compiler/js_lib/js_string.dart
index 67f37d5..e682626 100644
--- a/sdk/lib/_internal/compiler/js_lib/js_string.dart
+++ b/sdk/lib/_internal/compiler/js_lib/js_string.dart
@@ -73,12 +73,18 @@
String replaceFirst(Pattern from, String to, [int startIndex = 0]) {
checkString(to);
checkInt(startIndex);
- if (startIndex < 0 || startIndex > this.length) {
- throw new RangeError.range(startIndex, 0, this.length);
- }
+ RangeError.checkValueInInterval(startIndex, 0, this.length, "startIndex");
return stringReplaceFirstUnchecked(this, from, to, startIndex);
}
+ String replaceFirstMapped(Pattern from, String replace(Match match),
+ [int startIndex = 0]) {
+ checkNull(replace);
+ checkInt(startIndex);
+ RangeError.checkValueInInterval(startIndex, 0, this.length, "startIndex");
+ return stringReplaceFirstMappedUnchecked(this, from, replace, startIndex);
+ }
+
List<String> split(Pattern pattern) {
checkNull(pattern);
if (pattern is String) {
diff --git a/sdk/lib/_internal/compiler/js_lib/linked_hash_map.dart b/sdk/lib/_internal/compiler/js_lib/linked_hash_map.dart
new file mode 100644
index 0000000..0187c15
--- /dev/null
+++ b/sdk/lib/_internal/compiler/js_lib/linked_hash_map.dart
@@ -0,0 +1,380 @@
+// 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.
+
+// Efficient JavaScript based implementation of a linked hash map used as a
+// backing map for constant maps and the [LinkedHashMap] patch
+
+part of _js_helper;
+
+class JsLinkedHashMap<K, V> implements LinkedHashMap<K, V>, InternalMap {
+ int _length = 0;
+
+ // The hash map contents are divided into three parts: one part for
+ // string keys, one for numeric keys, and one for the rest. String
+ // and numeric keys map directly to their linked cells, but the rest
+ // of the entries are stored in bucket lists of the form:
+ //
+ // [cell-0, cell-1, ...]
+ //
+ // where all keys in the same bucket share the same hash code.
+ var _strings;
+ var _nums;
+ var _rest;
+
+ // The keys and values are stored in cells that are linked together
+ // to form a double linked list.
+ LinkedHashMapCell _first;
+ LinkedHashMapCell _last;
+
+ // We track the number of modifications done to the key set of the
+ // hash map to be able to throw when the map is modified while being
+ // iterated over.
+ int _modifications = 0;
+
+ JsLinkedHashMap();
+
+
+ int get length => _length;
+ bool get isEmpty => _length == 0;
+ bool get isNotEmpty => !isEmpty;
+
+ Iterable<K> get keys {
+ return new LinkedHashMapKeyIterable<K>(this);
+ }
+
+ Iterable<V> get values {
+ return new MappedIterable<K, V>(keys, (each) => this[each]);
+ }
+
+ bool containsKey(Object key) {
+ if (_isStringKey(key)) {
+ var strings = _strings;
+ if (strings == null) return false;
+ LinkedHashMapCell cell = _getTableEntry(strings, key);
+ return cell != null;
+ } else if (_isNumericKey(key)) {
+ var nums = _nums;
+ if (nums == null) return false;
+ LinkedHashMapCell cell = _getTableEntry(nums, key);
+ return cell != null;
+ } else {
+ return internalContainsKey(key);
+ }
+ }
+
+ bool internalContainsKey(Object key) {
+ var rest = _rest;
+ if (rest == null) return false;
+ var bucket = _getBucket(rest, key);
+ return internalFindBucketIndex(bucket, key) >= 0;
+ }
+
+ bool containsValue(Object value) {
+ return keys.any((each) => this[each] == value);
+ }
+
+ void addAll(Map<K, V> other) {
+ other.forEach((K key, V value) {
+ this[key] = value;
+ });
+ }
+
+ V operator[](Object key) {
+ if (_isStringKey(key)) {
+ var strings = _strings;
+ if (strings == null) return null;
+ LinkedHashMapCell cell = _getTableEntry(strings, key);
+ return (cell == null) ? null : cell.value;
+ } else if (_isNumericKey(key)) {
+ var nums = _nums;
+ if (nums == null) return null;
+ LinkedHashMapCell cell = _getTableEntry(nums, key);
+ return (cell == null) ? null : cell.value;
+ } else {
+ return internalGet(key);
+ }
+ }
+
+ V internalGet(Object key) {
+ var rest = _rest;
+ if (rest == null) return null;
+ var bucket = _getBucket(rest, key);
+ int index = internalFindBucketIndex(bucket, key);
+ if (index < 0) return null;
+ LinkedHashMapCell cell = JS('var', '#[#]', bucket, index);
+ return cell.value;
+ }
+
+ void operator[]=(K key, V value) {
+ if (_isStringKey(key)) {
+ var strings = _strings;
+ if (strings == null) _strings = strings = _newHashTable();
+ _addHashTableEntry(strings, key, value);
+ } else if (_isNumericKey(key)) {
+ var nums = _nums;
+ if (nums == null) _nums = nums = _newHashTable();
+ _addHashTableEntry(nums, key, value);
+ } else {
+ internalSet(key, value);
+ }
+ }
+
+ void internalSet(K key, V value) {
+ var rest = _rest;
+ if (rest == null) _rest = rest = _newHashTable();
+ var hash = internalComputeHashCode(key);
+ var bucket = JS('var', '#[#]', rest, hash);
+ if (bucket == null) {
+ LinkedHashMapCell cell = _newLinkedCell(key, value);
+ _setTableEntry(rest, hash, JS('var', '[#]', cell));
+ } else {
+ int index = internalFindBucketIndex(bucket, key);
+ if (index >= 0) {
+ LinkedHashMapCell cell = JS('var', '#[#]', bucket, index);
+ cell.value = value;
+ } else {
+ LinkedHashMapCell cell = _newLinkedCell(key, value);
+ JS('void', '#.push(#)', bucket, cell);
+ }
+ }
+ }
+
+ V putIfAbsent(K key, V ifAbsent()) {
+ if (containsKey(key)) return this[key];
+ V value = ifAbsent();
+ this[key] = value;
+ return value;
+ }
+
+ V remove(Object key) {
+ if (_isStringKey(key)) {
+ return _removeHashTableEntry(_strings, key);
+ } else if (_isNumericKey(key)) {
+ return _removeHashTableEntry(_nums, key);
+ } else {
+ return internalRemove(key);
+ }
+ }
+
+ V internalRemove(Object key) {
+ var rest = _rest;
+ if (rest == null) return null;
+ var bucket = _getBucket(rest, key);
+ int index = internalFindBucketIndex(bucket, key);
+ if (index < 0) return null;
+ // Use splice to remove the [cell] element at the index and
+ // unlink the cell before returning its value.
+ LinkedHashMapCell cell = JS('var', '#.splice(#, 1)[0]', bucket, index);
+ _unlinkCell(cell);
+ // TODO(kasperl): Consider getting rid of the bucket list when
+ // the length reaches zero.
+ return cell.value;
+ }
+
+ void clear() {
+ if (_length > 0) {
+ _strings = _nums = _rest = _first = _last = null;
+ _length = 0;
+ _modified();
+ }
+ }
+
+ void forEach(void action(K key, V value)) {
+ LinkedHashMapCell cell = _first;
+ int modifications = _modifications;
+ while (cell != null) {
+ action(cell.key, cell.value);
+ if (modifications != _modifications) {
+ throw new ConcurrentModificationError(this);
+ }
+ cell = cell._next;
+ }
+ }
+
+ void _addHashTableEntry(var table, K key, V value) {
+ LinkedHashMapCell cell = _getTableEntry(table, key);
+ if (cell == null) {
+ _setTableEntry(table, key, _newLinkedCell(key, value));
+ } else {
+ cell.value = value;
+ }
+ }
+
+ V _removeHashTableEntry(var table, Object key) {
+ if (table == null) return null;
+ LinkedHashMapCell cell = _getTableEntry(table, key);
+ if (cell == null) return null;
+ _unlinkCell(cell);
+ _deleteTableEntry(table, key);
+ return cell.value;
+ }
+
+ void _modified() {
+ // Value cycles after 2^30 modifications. If you keep hold of an
+ // iterator for that long, you might miss a modification
+ // detection, and iteration can go sour. Don't do that.
+ _modifications = (_modifications + 1) & 0x3ffffff;
+ }
+
+ // Create a new cell and link it in as the last one in the list.
+ LinkedHashMapCell _newLinkedCell(K key, V value) {
+ LinkedHashMapCell cell = new LinkedHashMapCell(key, value);
+ if (_first == null) {
+ _first = _last = cell;
+ } else {
+ LinkedHashMapCell last = _last;
+ cell._previous = last;
+ _last = last._next = cell;
+ }
+ _length++;
+ _modified();
+ return cell;
+ }
+
+ // Unlink the given cell from the linked list of cells.
+ void _unlinkCell(LinkedHashMapCell cell) {
+ LinkedHashMapCell previous = cell._previous;
+ LinkedHashMapCell next = cell._next;
+ if (previous == null) {
+ assert(cell == _first);
+ _first = next;
+ } else {
+ previous._next = next;
+ }
+ if (next == null) {
+ assert(cell == _last);
+ _last = previous;
+ } else {
+ next._previous = previous;
+ }
+ _length--;
+ _modified();
+ }
+
+ static bool _isStringKey(var key) {
+ return key is String && key != '__proto__';
+ }
+
+ static bool _isNumericKey(var key) {
+ // Only treat unsigned 30-bit integers as numeric keys. This way,
+ // we avoid converting them to strings when we use them as keys in
+ // the JavaScript hash table object.
+ return key is num && JS('bool', '(# & 0x3ffffff) === #', key, key);
+ }
+
+ int internalComputeHashCode(var key) {
+ // We force the hash codes to be unsigned 30-bit integers to avoid
+ // issues with problematic keys like '__proto__'. Another option
+ // would be to throw an exception if the hash code isn't a number.
+ return JS('int', '# & 0x3ffffff', key.hashCode);
+ }
+
+ static _getTableEntry(var table, var key) {
+ return JS('var', '#[#]', table, key);
+ }
+
+ static void _setTableEntry(var table, var key, var value) {
+ assert(value != null);
+ JS('void', '#[#] = #', table, key, value);
+ }
+
+ static void _deleteTableEntry(var table, var key) {
+ JS('void', 'delete #[#]', table, key);
+ }
+
+ List _getBucket(var table, var key) {
+ var hash = internalComputeHashCode(key);
+ return JS('var', '#[#]', table, hash);
+ }
+
+ int internalFindBucketIndex(var bucket, var key) {
+ if (bucket == null) return -1;
+ int length = JS('int', '#.length', bucket);
+ for (int i = 0; i < length; i++) {
+ LinkedHashMapCell cell = JS('var', '#[#]', bucket, i);
+ if (cell.key == key) return i;
+ }
+ return -1;
+ }
+
+ static _newHashTable() {
+ // Create a new JavaScript object to be used as a hash table. Use
+ // Object.create to avoid the properties on Object.prototype
+ // showing up as entries.
+ var table = JS('var', 'Object.create(null)');
+ // Attempt to force the hash table into 'dictionary' mode by
+ // adding a property to it and deleting it again.
+ var temporaryKey = '<non-identifier-key>';
+ _setTableEntry(table, temporaryKey, table);
+ _deleteTableEntry(table, temporaryKey);
+ return table;
+ }
+
+ String toString() => Maps.mapToString(this);
+}
+
+class LinkedHashMapCell {
+ final key;
+ var value;
+
+ LinkedHashMapCell _next;
+ LinkedHashMapCell _previous;
+
+ LinkedHashMapCell(this.key, this.value);
+}
+
+class LinkedHashMapKeyIterable<E> extends IterableBase<E>
+ implements EfficientLength {
+ final _map;
+ LinkedHashMapKeyIterable(this._map);
+
+ int get length => _map._length;
+ bool get isEmpty => _map._length == 0;
+
+ Iterator<E> get iterator {
+ return new LinkedHashMapKeyIterator<E>(_map, _map._modifications);
+ }
+
+ bool contains(Object element) {
+ return _map.containsKey(element);
+ }
+
+ void forEach(void f(E element)) {
+ LinkedHashMapCell cell = _map._first;
+ int modifications = _map._modifications;
+ while (cell != null) {
+ f(cell.key);
+ if (modifications != _map._modifications) {
+ throw new ConcurrentModificationError(_map);
+ }
+ cell = cell._next;
+ }
+ }
+}
+
+class LinkedHashMapKeyIterator<E> implements Iterator<E> {
+ final _map;
+ final int _modifications;
+ LinkedHashMapCell _cell;
+ E _current;
+
+ LinkedHashMapKeyIterator(this._map, this._modifications) {
+ _cell = _map._first;
+ }
+
+ E get current => _current;
+
+ bool moveNext() {
+ if (_modifications != _map._modifications) {
+ throw new ConcurrentModificationError(_map);
+ } else if (_cell == null) {
+ _current = null;
+ return false;
+ } else {
+ _current = _cell.key;
+ _cell = _cell._next;
+ return true;
+ }
+ }
+}
diff --git a/sdk/lib/_internal/compiler/js_lib/shared/embedded_names.dart b/sdk/lib/_internal/compiler/js_lib/shared/embedded_names.dart
index 9ae4f9f..2735d38 100644
--- a/sdk/lib/_internal/compiler/js_lib/shared/embedded_names.dart
+++ b/sdk/lib/_internal/compiler/js_lib/shared/embedded_names.dart
@@ -58,6 +58,8 @@
const TYPEDEF_TYPE_PROPERTY_NAME = r"$typedefType";
const TYPEDEF_PREDICATE_PROPERTY_NAME = r"$$isTypedef";
const NATIVE_SUPERCLASS_TAG_NAME = r"$nativeSuperclassTag";
+const ARGUMENT_COUNT_PROPERTY = r"$argumentCount";
+const DEFAULT_VALUES_PROPERTY = r"$defaultValues";
/// Returns the type given the name of a class.
/// This function is called by the runtime when computing rti.
diff --git a/sdk/lib/_internal/compiler/js_lib/string_helper.dart b/sdk/lib/_internal/compiler/js_lib/string_helper.dart
index ff25057..77b8ab9 100644
--- a/sdk/lib/_internal/compiler/js_lib/string_helper.dart
+++ b/sdk/lib/_internal/compiler/js_lib/string_helper.dart
@@ -193,21 +193,34 @@
}
-stringReplaceFirstUnchecked(receiver, from, to, [int startIndex = 0]) {
+stringReplaceFirstUnchecked(receiver, from, to, int startIndex) {
if (from is String) {
- var index = receiver.indexOf(from, startIndex);
+ int index = receiver.indexOf(from, startIndex);
if (index < 0) return receiver;
return '${receiver.substring(0, index)}$to'
'${receiver.substring(index + from.length)}';
- } else if (from is JSSyntaxRegExp) {
+ }
+ if (from is JSSyntaxRegExp) {
return startIndex == 0 ?
stringReplaceJS(receiver, regExpGetNative(from), to) :
stringReplaceFirstRE(receiver, from, to, startIndex);
- } else {
- checkNull(from);
- // TODO(floitsch): implement generic String.replace (with patterns).
- throw "String.replace(Pattern) UNIMPLEMENTED";
}
+ checkNull(from);
+ Iterator<Match> matches = from.allMatches(receiver, startIndex).iterator;
+ if (!matches.moveNext()) return receiver;
+ Match match = matches.current;
+ return '${receiver.substring(0, match.start)}$to'
+ '${receiver.substring(match.end)}';
+}
+
+stringReplaceFirstMappedUnchecked(receiver, from, replace,
+ int startIndex) {
+ Iterator<Match> matches = from.allMatches(receiver, startIndex).iterator;
+ if (!matches.moveNext()) return receiver;
+ Match match = matches.current;
+ String replacement = "${replace(match)}";
+ return '${receiver.substring(0, match.start)}$replacement'
+ '${receiver.substring(match.end)}';
}
stringJoinUnchecked(array, separator) {
diff --git a/sdk/lib/_internal/pub/bin/async_compile.dart b/sdk/lib/_internal/pub/bin/async_compile.dart
deleted file mode 100644
index 7fded88..0000000
--- a/sdk/lib/_internal/pub/bin/async_compile.dart
+++ /dev/null
@@ -1,294 +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 'dart:io';
-
-import 'package:args/args.dart';
-import 'package:analyzer/src/services/formatter_impl.dart';
-import 'package:async_await/async_await.dart' as async_await;
-import 'package:stack_trace/stack_trace.dart';
-import 'package:path/path.dart' as p;
-
-/// The path to pub's root directory (sdk/lib/_internal/pub) in the Dart repo.
-///
-/// This assumes this script is itself being run from within the repo.
-final sourceDir = p.dirname(p.dirname(p.fromUri(Platform.script)));
-
-/// The [sourceDir] as a URL, for use in import strings.
-final sourceUrl = p.toUri(sourceDir).toString();
-
-/// The directory that compiler output should be written to.
-String generatedDir;
-
-/// `true` if any file failed to compile.
-bool hadFailure = false;
-
-bool verbose = false;
-
-/// Prefix for imports in pub that import dart2js libraries.
-final _compilerPattern = new RegExp(r"import '(\.\./)+compiler");
-
-/// Matches the Git commit hash of the compiler stored in the README.md file.
-///
-/// This is used both to find the current commit and replace it with the new
-/// one.
-final _commitPattern = new RegExp(r"[a-f0-9]{40}");
-
-/// The template for the README that's added to the generated source.
-///
-/// This is used to store the current commit of the async_await compiler.
-const _README = """
-Pub is currently dogfooding the new Dart async/await syntax. Since the Dart VM
-doesn't natively support it yet, we are using the [async-await][] compiler
-package.
-
-[async-await]: https://github.com/dart-lang/async_await
-
-We run that to compile pub-using-await from sdk/lib/_internal/pub down to
-vanilla Dart code which is what you see here. To interoperate more easily with
-the rest of the repositry, we check in that generated code.
-
-When bug #104 is fixed, we can remove this entirely.
-
-The code here was compiled using the async-await compiler at commit:
-
- <<COMMIT>>
-
-(Note: this file is also parsed by a tool to update the above commit, so be
-careful not to reformat it.)
-""";
-
-/// This runs the async/await compiler on all of the pub source code.
-///
-/// It reads from the repo and writes the compiled output into the given build
-/// directory (using the same file names and relative layout). Does not
-/// compile files that haven't changed since the last time they were compiled.
-// TODO(rnystrom): Remove this when #104 is fixed.
-void main(List<String> arguments) {
- var parser = new ArgParser(allowTrailingOptions: true);
-
- parser.addFlag("verbose", callback: (value) => verbose = value);
-
- var force = false;
- parser.addFlag("force", callback: (value) => force = value);
-
- var buildDir;
- parser.addOption("snapshot-build-dir", callback: (value) => buildDir = value);
-
- try {
- var rest = parser.parse(arguments).rest;
- if (rest.isEmpty) {
- throw new FormatException('Missing generated directory.');
- } else if (rest.length > 1) {
- throw new FormatException(
- 'Unexpected arguments: ${rest.skip(1).join(" ")}.');
- }
-
- generatedDir = rest.first;
- } on FormatException catch(ex) {
- stderr.writeln(ex);
- stderr.writeln();
- stderr.writeln(
- "Usage: dart async_compile.dart [--verbose] [--force] "
- "[--snapshot-build-dir <dir>] <generated dir>");
- exit(64);
- }
-
- // See what version (i.e. Git commit) of the async-await compiler we
- // currently have. If this is different from the version that was used to
- // compile the sources, recompile everything.
- var currentCommit = _getCurrentCommit();
-
- var readmePath = p.join(generatedDir, "README.md");
- var lastCommit;
- try {
- var readme = new File(readmePath).readAsStringSync();
- var match = _commitPattern.firstMatch(readme);
- if (match == null) {
- stderr.writeln("Could not find compiler commit hash in README.md.");
- exit(1);
- }
-
- lastCommit = match[0];
- } on IOException catch (error, stackTrace) {
- if (verbose) {
- stderr.writeln("Failed to load $readmePath: $error\n"
- "${new Trace.from(stackTrace)}");
- }
- }
-
- var numFiles = 0;
- var numCompiled = 0;
-
- // Compile any modified or missing files.
- var sources = new Set();
- for (var entry in new Directory(sourceDir).listSync(recursive: true)) {
- if (p.extension(entry.path) != ".dart") continue;
-
- numFiles++;
- var relative = p.relative(entry.path, from: sourceDir);
- sources.add(relative);
-
- var sourceFile = entry as File;
- var destPath = p.join(generatedDir, relative);
- var destFile = new File(destPath);
- if (force ||
- currentCommit != lastCommit ||
- !destFile.existsSync() ||
- entry.lastModifiedSync().isAfter(destFile.lastModifiedSync())) {
- _compile(sourceFile.path, sourceFile.readAsStringSync(), destPath);
- numCompiled++;
- if (verbose) print("Compiled $relative");
- }
- }
-
- // Delete any previously compiled files whose source no longer exists.
- for (var entry in new Directory(generatedDir).listSync(recursive: true)) {
- if (p.extension(entry.path) != ".dart") continue;
-
- var relative = p.relative(entry.path, from: generatedDir);
-
- if (!sources.contains(relative)) {
- _deleteFile(entry.path);
- if (verbose) print("Deleted $relative");
- }
- }
-
- // Update the README.
- if (currentCommit != lastCommit) {
- _writeFile(readmePath, _README.replaceAll("<<COMMIT>>", currentCommit));
- if (verbose) print("Updated README.md");
- }
-
- if (numCompiled > 0 && buildDir != null) _generateSnapshot(buildDir);
-
- if (verbose) print("Compiled $numCompiled out of $numFiles files");
-
- if (hadFailure) exit(1);
-}
-
-String _getCurrentCommit() {
- var command = "git";
- var args = ["rev-parse", "HEAD"];
-
- // Spawning a process on Windows will not look for the executable in the
- // system path so spawn git through a shell to find it.
- if (Platform.operatingSystem == "windows") {
- command = "cmd";
- args = ["/c", "git"]..addAll(args);
- }
-
- var result = Process.runSync(command, args, workingDirectory:
- p.join(sourceDir, "../../../../third_party/pkg/async_await"));
- if (result.exitCode != 0) {
- stderr.writeln("Could not get Git revision of async_await compiler.");
- exit(1);
- }
-
- return result.stdout.trim();
-}
-
-void _compile(String sourcePath, String source, String destPath) {
- var destDir = new Directory(p.dirname(destPath));
- destDir.createSync(recursive: true);
-
- source = _translateAsyncAwait(sourcePath, source);
- if (source != null) source = _fixDart2jsImports(sourcePath, source, destPath);
-
- if (source == null) {
- // If the async compile fails, delete the file so that we don't try to
- // run the stale previous output and so that we try to recompile it later.
- _deleteFile(destPath);
- } else {
- _writeFile(destPath, source);
- }
-}
-
-/// Runs the async/await compiler on [source].
-///
-/// Returns the translated Dart code or `null` if the compiler failed.
-String _translateAsyncAwait(String sourcePath, String source) {
- if (p.isWithin(p.join(sourceDir, "asset"), sourcePath)) {
- // Don't run the async compiler on the special "asset" source files. These
- // have preprocessor comments that get discarded by the compiler.
- return source;
- }
-
- try {
- source = async_await.compile(source);
-
- // Reformat the result since the compiler ditches all whitespace.
- // TODO(rnystrom): Remove when this is fixed:
- // https://github.com/dart-lang/async_await/issues/12
- var result = new CodeFormatter().format(CodeKind.COMPILATION_UNIT, source);
- return result.source;
- } catch (ex) {
- stderr.writeln("Async compile failed on $sourcePath:\n$ex");
- hadFailure = true;
- return null;
- }
-}
-
-/// Fix relative imports to dart2js libraries.
-///
-/// Pub imports dart2js using relative imports that reach outside of pub's
-/// source tree. Since the build directory is in a different location, we need
-/// to fix those to be valid relative imports from the build directory.
-String _fixDart2jsImports(String sourcePath, String source, String destPath) {
- var compilerDir = p.url.join(sourceUrl, "../compiler");
- var relative = p.url.relative(compilerDir,
- from: p.url.dirname(p.toUri(destPath).toString()));
- return source.replaceAll(_compilerPattern, "import '$relative");
-}
-
-/// Regenerate the pub snapshot from the async/await-compiled output. We do
-/// this here since the tests need it and it's faster than doing a full SDK
-/// build.
-void _generateSnapshot(String buildDir) {
- buildDir = p.normalize(buildDir);
- new Directory(buildDir).createSync(recursive: true);
-
- var entrypoint = p.join(generatedDir, 'bin/pub.dart');
- var packageRoot = p.join(buildDir, 'packages');
- var snapshot = p.join(buildDir, 'dart-sdk/bin/snapshots/pub.dart.snapshot');
-
- var result = Process.runSync(Platform.executable, [
- "--package-root=$packageRoot",
- "--snapshot=$snapshot",
- entrypoint
- ]);
-
- if (result.exitCode != 0) {
- stderr.writeln("Failed to generate snapshot:");
- if (result.stderr.trim().isNotEmpty) stderr.writeln(result.stderr);
- if (result.stdout.trim().isNotEmpty) stderr.writeln(result.stdout);
- exit(result.exitCode);
- }
-
- if (verbose) print("Created pub snapshot");
-}
-
-/// Deletes the file at [path], ignoring any IO errors that occur.
-///
-/// This swallows errors to accommodate multiple compilers running concurrently.
-/// Since they will produce the same output anyway, a failure of one is fine.
-void _deleteFile(String path) {
- try {
- new File(path).deleteSync();
- } on IOException catch (ex) {
- // Do nothing.
- }
-}
-
-/// Writes [contents] to [path], ignoring any IO errors that occur.
-///
-/// This swallows errors to accommodate multiple compilers running concurrently.
-/// Since they will produce the same output anyway, a failure of one is fine.
-void _writeFile(String path, String contents) {
- try {
- new File(path).writeAsStringSync(contents);
- } on IOException catch (ex) {
- // Do nothing.
- }
-}
diff --git a/sdk/lib/_internal/pub/lib/src/barback/asset_environment.dart b/sdk/lib/_internal/pub/lib/src/barback/asset_environment.dart
index 035dbe6..c07d860 100644
--- a/sdk/lib/_internal/pub/lib/src/barback/asset_environment.dart
+++ b/sdk/lib/_internal/pub/lib/src/barback/asset_environment.dart
@@ -266,7 +266,7 @@
}
log.fine("Executables for $packageName: $executableIds");
- if (executableIds.isEmpty) return [];
+ if (executableIds.isEmpty) return {};
var package = graph.packages[packageName];
var server = await servePackageBinDirectory(packageName);
diff --git a/sdk/lib/_internal/pub/lib/src/barback/dart2js_transformer.dart b/sdk/lib/_internal/pub/lib/src/barback/dart2js_transformer.dart
index dead76f..e95c25e 100644
--- a/sdk/lib/_internal/pub/lib/src/barback/dart2js_transformer.dart
+++ b/sdk/lib/_internal/pub/lib/src/barback/dart2js_transformer.dart
@@ -272,7 +272,7 @@
var sourcePath = path.fromUri(resourceUri);
return _readResource(resourceUri).then((source) {
_sourceFiles[resourceUri.toString()] =
- new StringSourceFile(path.relative(sourcePath), source);
+ new StringSourceFile(resourceUri, path.relative(sourcePath), source);
return source;
});
}
diff --git a/sdk/lib/_internal/pub/lib/src/command/build.dart b/sdk/lib/_internal/pub/lib/src/command/build.dart
index 4b76909..7a6685a 100644
--- a/sdk/lib/_internal/pub/lib/src/command/build.dart
+++ b/sdk/lib/_internal/pub/lib/src/command/build.dart
@@ -128,7 +128,9 @@
Future _writeAsset(Asset asset) async {
// In release mode, strip out .dart files since all relevant ones have been
// compiled to JavaScript already.
- if (mode == BarbackMode.RELEASE && asset.id.extension == ".dart") return;
+ if (mode == BarbackMode.RELEASE && asset.id.extension == ".dart") {
+ return null;
+ }
var destPath = _idToPath(asset.id);
diff --git a/sdk/lib/_internal/pub/lib/src/executable.dart b/sdk/lib/_internal/pub/lib/src/executable.dart
index 966b68f..1c22b80 100644
--- a/sdk/lib/_internal/pub/lib/src/executable.dart
+++ b/sdk/lib/_internal/pub/lib/src/executable.dart
@@ -186,9 +186,9 @@
}
var exitCode = await runProcess(stdin1);
- if (recompile == null || exitCode != 255) return exitCode;
+ if (recompile == null || exitCode != 253) return exitCode;
- // Exit code 255 indicates that the snapshot version was out-of-date. If we
+ // Exit code 253 indicates that the snapshot version was out-of-date. If we
// can recompile, do so.
await recompile();
return runProcess(stdin2);
diff --git a/sdk/lib/_internal/pub/lib/src/global_packages.dart b/sdk/lib/_internal/pub/lib/src/global_packages.dart
index 6ce58a7..d8c7250 100644
--- a/sdk/lib/_internal/pub/lib/src/global_packages.dart
+++ b/sdk/lib/_internal/pub/lib/src/global_packages.dart
@@ -660,9 +660,9 @@
if (snapshot != null) {
batch += """
-rem The VM exits with code 255 if the snapshot version is out-of-date.
+rem The VM exits with code 253 if the snapshot version is out-of-date.
rem If it is, we need to delete it and run "pub global" manually.
-if not errorlevel 255 (
+if not errorlevel 253 (
exit /b %errorlevel%
)
@@ -685,10 +685,10 @@
if (snapshot != null) {
bash += """
-# The VM exits with code 255 if the snapshot version is out-of-date.
+# The VM exits with code 253 if the snapshot version is out-of-date.
# If it is, we need to delete it and run "pub global" manually.
exit_code=\$?
-if [ \$exit_code != 255 ]; then
+if [ \$exit_code != 253 ]; then
exit \$exit_code
fi
diff --git a/sdk/lib/_internal/pub/lib/src/validator/dependency.dart b/sdk/lib/_internal/pub/lib/src/validator/dependency.dart
index 37f55d7..88282fb 100644
--- a/sdk/lib/_internal/pub/lib/src/validator/dependency.dart
+++ b/sdk/lib/_internal/pub/lib/src/validator/dependency.dart
@@ -15,14 +15,16 @@
import '../validator.dart';
/// The range of all pub versions that don't support `^` version constraints.
+///
+/// This is the actual range of pub versions, whereas [_postCaretPubVersions] is
+/// the nicer-looking range that doesn't include a prerelease tag.
final _preCaretPubVersions = new VersionConstraint.parse("<1.8.0-dev.3.0");
-// TODO(nweiz): replace this with "^1.8.0" for the 1.8 release.
/// The range of all pub versions that do support `^` version constraints.
///
/// This is intersected with the user's SDK constraint to provide a suggested
/// constraint.
-final _postCaretPubVersions = new VersionConstraint.parse("^1.8.0-dev.3.0");
+final _postCaretPubVersions = new VersionConstraint.parse("^1.8.0");
/// A validator that validates a package's dependencies.
class DependencyValidator extends Validator {
diff --git a/sdk/lib/_internal/pub/pub.status b/sdk/lib/_internal/pub/pub.status
index f2be2f2..058e2d7 100644
--- a/sdk/lib/_internal/pub/pub.status
+++ b/sdk/lib/_internal/pub/pub.status
@@ -6,11 +6,6 @@
test/serve/web_socket/url_to_asset_id_test: Pass, Slow
test/transformer/loads_a_diamond_transformer_dependency_graph_test: Pass, Slow
-test/global/binstubs/outdated_binstub_runs_pub_global_test: Fail # 22284
-test/global/binstubs/outdated_snapshot_test: Fail # 22284
-test/global/run/recompiles_if_sdk_is_out_of_date_test: Fail # 22284
-test/snapshot/recompiles_if_the_sdk_is_out_of_date_test: Fail # 22284
-
# Pub only runs on the VM, so just rule out all compilers.
[ $compiler == dart2js || $compiler == dart2dart ]
*: Skip
@@ -21,3 +16,6 @@
[ $runtime == vm && $system == windows ]
test/run/app_can_read_from_stdin_test: Fail # Issue 19448
+
+[ $runtime == vm && $system == windows ]
+test/real_version_test: RuntimeError # Issue 22543
diff --git a/sdk/lib/_internal/pub/test/async_compile_test.dart b/sdk/lib/_internal/pub/test/async_compile_test.dart
deleted file mode 100644
index a3216d7..0000000
--- a/sdk/lib/_internal/pub/test/async_compile_test.dart
+++ /dev/null
@@ -1,28 +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 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/descriptor.dart' as d;
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_process.dart';
-
-import 'test_pub.dart';
-import '../lib/src/io.dart';
-
-void main() {
- integration("the generated pub source is up to date", () {
- var compilerArgs = Platform.executableArguments.toList()..addAll([
- p.join(pubRoot, 'bin', 'async_compile.dart'),
- '--force', '--verbose',
- p.join(sandboxDir, "pub_generated")
- ]);
-
- new ScheduledProcess.start(Platform.executable, compilerArgs).shouldExit(0);
-
- new d.DirectoryDescriptor.fromFilesystem("pub_generated",
- p.join(pubRoot, "..", "pub_generated")).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub/test/cache/repair/updates_binstubs_test.dart b/sdk/lib/_internal/pub/test/cache/repair/updates_binstubs_test.dart
index 1d612a1..e84f4e8 100644
--- a/sdk/lib/_internal/pub/test/cache/repair/updates_binstubs_test.dart
+++ b/sdk/lib/_internal/pub/test/cache/repair/updates_binstubs_test.dart
@@ -57,8 +57,8 @@
// The broken versions should have been replaced.
d.dir(cachePath, [
d.dir('bin', [
- // 255 is the VM's exit code upon seeing an out-of-date snapshot.
- d.matcherFile(binStubName('foo-script'), contains('255'))
+ // 253 is the VM's exit code upon seeing an out-of-date snapshot.
+ d.matcherFile(binStubName('foo-script'), contains('253'))
])
]).validate();
});
diff --git a/sdk/lib/_internal/pub/test/global/activate/outdated_binstub_test.dart b/sdk/lib/_internal/pub/test/global/activate/outdated_binstub_test.dart
index 51bcc83..51780ce 100644
--- a/sdk/lib/_internal/pub/test/global/activate/outdated_binstub_test.dart
+++ b/sdk/lib/_internal/pub/test/global/activate/outdated_binstub_test.dart
@@ -50,8 +50,8 @@
d.dir(cachePath, [
d.dir('bin', [
- // 255 is the VM's exit code upon seeing an out-of-date snapshot.
- d.matcherFile(binStubName('foo-script'), contains("255"))
+ // 253 is the VM's exit code upon seeing an out-of-date snapshot.
+ d.matcherFile(binStubName('foo-script'), contains("253"))
])
]).validate();
});
diff --git a/sdk/lib/_internal/pub/test/test_pub.dart b/sdk/lib/_internal/pub/test/test_pub.dart
index 4b6afb3..cb555a0 100644
--- a/sdk/lib/_internal/pub/test/test_pub.dart
+++ b/sdk/lib/_internal/pub/test/test_pub.dart
@@ -809,16 +809,8 @@
}
/// Resolves [target] relative to the path to pub's `test/asset` directory.
-String testAssetPath(String target) {
- var libPath = libraryPath('test_pub');
-
- // We are running from the generated directory, but non-dart assets are only
- // in the canonical directory.
- // TODO(rnystrom): Remove this when #104 is fixed.
- libPath = libPath.replaceAll('pub_generated', 'pub');
-
- return p.join(p.dirname(libPath), 'asset', target);
-}
+String testAssetPath(String target) =>
+ p.join(p.dirname(libraryPath('test_pub')), 'asset', target);
/// Returns a Map in the format used by the pub.dartlang.org API to represent a
/// package version.
diff --git a/sdk/lib/_internal/pub_generated/README.md b/sdk/lib/_internal/pub_generated/README.md
deleted file mode 100644
index 903a085..0000000
--- a/sdk/lib/_internal/pub_generated/README.md
+++ /dev/null
@@ -1,18 +0,0 @@
-Pub is currently dogfooding the new Dart async/await syntax. Since the Dart VM
-doesn't natively support it yet, we are using the [async-await][] compiler
-package.
-
-[async-await]: https://github.com/dart-lang/async_await
-
-We run that to compile pub-using-await from sdk/lib/_internal/pub down to
-vanilla Dart code which is what you see here. To interoperate more easily with
-the rest of the repositry, we check in that generated code.
-
-When bug #104 is fixed, we can remove this entirely.
-
-The code here was compiled using the async-await compiler at commit:
-
- 8b401a9f2e5e81dca5f70dbe7564112a0823dee6
-
-(Note: this file is also parsed by a tool to update the above commit, so be
-careful not to reformat it.)
diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize.dart
deleted file mode 100644
index f37ab70..0000000
--- a/sdk/lib/_internal/pub_generated/asset/dart/serialize.dart
+++ /dev/null
@@ -1,184 +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.
-
-library pub.asset.serialize;
-
-import 'dart:async';
-import 'dart:isolate';
-
-import 'package:barback/barback.dart';
-
-//# if source_maps >=0.9.0 <0.10.0
-//> import 'package:source_maps/span.dart';
-//# end
-
-//# if source_span
-import 'package:source_span/source_span.dart';
-//# end
-
-import 'serialize/exception.dart';
-import 'utils.dart';
-
-export 'serialize/aggregate_transform.dart';
-export 'serialize/exception.dart';
-export 'serialize/transform.dart';
-export 'serialize/transformer.dart';
-
-/// Converts [id] into a serializable map.
-Map serializeId(AssetId id) => {'package': id.package, 'path': id.path};
-
-/// Converts a serializable map into an [AssetId].
-AssetId deserializeId(Map id) => new AssetId(id['package'], id['path']);
-
-/// Converts [span] into a serializable map.
-///
-/// [span] may be a [SourceSpan] or a [Span].
-Map serializeSpan(span) {
- // TODO(nweiz): convert FileSpans to FileSpans.
- // Handily, this code works for both source_map and source_span spans.
- return {
- 'sourceUrl': span.sourceUrl.toString(),
- 'start': serializeLocation(span.start),
- 'end': serializeLocation(span.end),
- 'text': span.text,
- };
-}
-
-/// Converts a serializable map into a [SourceSpan].
-SourceSpan deserializeSpan(Map span) {
- return new SourceSpan(
- deserializeLocation(span['start']),
- deserializeLocation(span['end']),
- span['text']);
-}
-
-/// Converts [location] into a serializable map.
-///
-/// [location] may be a [SourceLocation] or a [SourceLocation].
-Map serializeLocation(location) {
-//# if source_maps >=0.9.0 <0.10.0
-//> if (location is Location) {
-//> return {
-//> 'sourceUrl': location.sourceUrl,
-//> 'offset': location.offset,
-//> 'line': location.line,
-//> 'column': location.column
-//> };
-//> }
-//# end
-
-//# if source_span
- // TODO(nweiz): convert FileLocations to FileLocations.
- if (location is SourceLocation) {
- return {
- 'sourceUrl': location.sourceUrl.toString(),
- 'offset': location.offset,
- 'line': location.line,
- 'column': location.column
- };
- }
-//# end
-
- throw new ArgumentError("Unknown type ${location.runtimeType} for location.");
-}
-
-/// Converts a serializable map into a [Location].
-SourceLocation deserializeLocation(Map location) {
- return new SourceLocation(location['offset'],
- sourceUrl: location['sourceUrl'],
- line: location['line'],
- column: location['column']);
-}
-
-/// Converts [stream] into a serializable map.
-///
-/// [serializeEvent] is used to serialize each event from the stream.
-Map serializeStream(Stream stream, serializeEvent(event)) {
- var receivePort = new ReceivePort();
- var map = {'replyTo': receivePort.sendPort};
-
- receivePort.first.then((message) {
- var sendPort = message['replyTo'];
- stream.listen((event) {
- sendPort.send({
- 'type': 'event',
- 'value': serializeEvent(event)
- });
- }, onError: (error, stackTrace) {
- sendPort.send({
- 'type': 'error',
- 'error': serializeException(error, stackTrace)
- });
- }, onDone: () => sendPort.send({'type': 'done'}));
- });
-
- return map;
-}
-
-/// Converts a serializable map into a [Stream].
-///
-/// [deserializeEvent] is used to deserialize each event from the stream.
-Stream deserializeStream(Map stream, deserializeEvent(event)) {
- return callbackStream(() {
- var receivePort = new ReceivePort();
- stream['replyTo'].send({'replyTo': receivePort.sendPort});
-
- var controller = new StreamController(sync: true);
- receivePort.listen((event) {
- switch (event['type']) {
- case 'event':
- controller.add(deserializeEvent(event['value']));
- break;
- case 'error':
- var exception = deserializeException(event['error']);
- controller.addError(exception, exception.stackTrace);
- break;
- case 'done':
- controller.close();
- receivePort.close();
- break;
- }
- });
-
- return controller.stream;
- });
-}
-
-/// Wraps [message] and sends it across [port], then waits for a response which
-/// should be sent using [respond].
-///
-/// The returned Future will complete to the value or error returned by
-/// [respond].
-Future call(SendPort port, message) {
- var receivePort = new ReceivePort();
- port.send({
- 'message': message,
- 'replyTo': receivePort.sendPort
- });
-
- return receivePort.first.then((response) {
- if (response['type'] == 'success') return response['value'];
- assert(response['type'] == 'error');
- var exception = deserializeException(response['error']);
- return new Future.error(exception, exception.stackTrace);
- });
-}
-
-/// Responds to a message sent by [call].
-///
-/// [wrappedMessage] is the raw message sent by [call]. This unwraps it and
-/// passes the contents of the message to [callback], then sends the return
-/// value of [callback] back to [call]. If [callback] returns a Future or
-/// throws an error, that will also be sent.
-void respond(wrappedMessage, callback(message)) {
- var replyTo = wrappedMessage['replyTo'];
- new Future.sync(() => callback(wrappedMessage['message']))
- .then((result) => replyTo.send({'type': 'success', 'value': result}))
- .catchError((error, stackTrace) {
- replyTo.send({
- 'type': 'error',
- 'error': serializeException(error, stackTrace)
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/aggregate_transform.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/aggregate_transform.dart
deleted file mode 100644
index 5b7acc8..0000000
--- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/aggregate_transform.dart
+++ /dev/null
@@ -1,173 +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.
-
-library pub.asset.serialize.aggregate_transform;
-
-import 'dart:async';
-import 'dart:isolate';
-
-import 'package:barback/barback.dart';
-// TODO(nweiz): don't import from "src" once issue 14966 is fixed.
-import 'package:barback/src/internal_asset.dart';
-
-import '../serialize.dart';
-import 'get_input_transform.dart';
-
-/// Serialize the methods shared between [AggregateTransform] and
-/// [DeclaringAggregateTransform].
-///
-/// [additionalFields] contains additional serialized fields to add to the
-/// serialized transform. [methodHandlers] is a set of additional methods. Each
-/// value should take a JSON message and return the response (which may be a
-/// Future).
-Map _serializeBaseAggregateTransform(transform, Map additionalFields,
- Map<String, Function> methodHandlers) {
- var receivePort = new ReceivePort();
- receivePort.listen((wrappedMessage) {
- respond(wrappedMessage, (message) {
- var handler = methodHandlers[message['type']];
- if (handler != null) return handler(message);
-
- if (message['type'] == 'consumePrimary') {
- transform.consumePrimary(deserializeId(message['assetId']));
- return null;
- }
-
- assert(message['type'] == 'log');
- var method = {
- 'Info': transform.logger.info,
- 'Fine': transform.logger.fine,
- 'Warning': transform.logger.warning,
- 'Error': transform.logger.error
- }[message['level']];
- assert(method != null);
-
- var assetId = message['assetId'] == null ? null :
- deserializeId(message['assetId']);
- var span = message['span'] == null ? null :
- deserializeSpan(message['span']);
- method(message['message'], asset: assetId, span: span);
- });
- });
-
- return {
- 'port': receivePort.sendPort,
- 'key': transform.key,
- 'package': transform.package
- }..addAll(additionalFields);
-}
-
-/// Converts [transform] into a serializable map.
-Map serializeAggregateTransform(AggregateTransform transform) {
- return _serializeBaseAggregateTransform(transform, {
- 'primaryInputs': serializeStream(transform.primaryInputs, serializeAsset)
- }, {
- 'getInput': (message) => transform.getInput(deserializeId(message['id']))
- .then((asset) => serializeAsset(asset)),
- 'addOutput': (message) =>
- transform.addOutput(deserializeAsset(message['output']))
- });
-}
-
-/// Converts [transform] into a serializable map.
-Map serializeDeclaringAggregateTransform(
- DeclaringAggregateTransform transform) {
- return _serializeBaseAggregateTransform(transform, {
- 'primaryIds': serializeStream(transform.primaryIds, serializeId)
- }, {
- 'declareOutput': (message) =>
- transform.declareOutput(deserializeId(message['output']))
- });
-}
-
-/// The base class for wrappers for [AggregateTransform]s that are in the host
-/// isolate.
-class _ForeignBaseAggregateTransform {
- /// The port with which we communicate with the host isolate.
- ///
- /// This port and all messages sent across it are specific to this transform.
- final SendPort _port;
-
- final String key;
-
- final String package;
-
- TransformLogger get logger => _logger;
- TransformLogger _logger;
-
- _ForeignBaseAggregateTransform(Map transform)
- : _port = transform['port'],
- key = transform['key'],
- package = transform['package'] {
- _logger = new TransformLogger((assetId, level, message, span) {
- call(_port, {
- 'type': 'log',
- 'level': level.name,
- 'message': message,
- 'assetId': assetId == null ? null : serializeId(assetId),
- 'span': span == null ? null : serializeSpan(span)
- });
- });
- }
-
- void consumePrimary(AssetId id) {
- call(_port, {'type': 'consumePrimary', 'assetId': serializeId(id)});
- }
-}
-
-// We can get away with only removing the class declarations in incompatible
-// barback versions because merely referencing undefined types in type
-// annotations isn't a static error. Only implementing an undefined interface is
-// a static error.
-//# if barback >=0.14.1
-
-/// A wrapper for an [AggregateTransform] that's in the host isolate.
-///
-/// This retrieves inputs from and sends outputs and logs to the host isolate.
-class ForeignAggregateTransform extends _ForeignBaseAggregateTransform
- with GetInputTransform implements AggregateTransform {
- final Stream<Asset> primaryInputs;
-
- /// Creates a transform from a serialized map sent from the host isolate.
- ForeignAggregateTransform(Map transform)
- : primaryInputs = deserializeStream(
- transform['primaryInputs'], deserializeAsset),
- super(transform);
-
- Future<Asset> getInput(AssetId id) {
- return call(_port, {
- 'type': 'getInput',
- 'id': serializeId(id)
- }).then(deserializeAsset);
- }
-
- void addOutput(Asset output) {
- call(_port, {
- 'type': 'addOutput',
- 'output': serializeAsset(output)
- });
- }
-}
-
-/// A wrapper for a [DeclaringAggregateTransform] that's in the host isolate.
-class ForeignDeclaringAggregateTransform
- extends _ForeignBaseAggregateTransform
- implements DeclaringAggregateTransform {
- final Stream<AssetId> primaryIds;
-
- /// Creates a transform from a serializable map sent from the host isolate.
- ForeignDeclaringAggregateTransform(Map transform)
- : primaryIds = deserializeStream(
- transform['primaryIds'], deserializeId),
- super(transform);
-
- void declareOutput(AssetId id) {
- call(_port, {
- 'type': 'declareOutput',
- 'output': serializeId(id)
- });
- }
-}
-
-//# end
diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/exception.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/exception.dart
deleted file mode 100644
index 26040a9..0000000
--- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/exception.dart
+++ /dev/null
@@ -1,102 +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.
-
-library pub.asset.serialize.exception;
-
-import 'package:barback/barback.dart';
-import 'package:stack_trace/stack_trace.dart';
-
-import '../utils.dart';
-
-/// An exception that was originally raised in another isolate.
-///
-/// Exception objects can't cross isolate boundaries in general, so this class
-/// wraps as much information as can be consistently serialized.
-class CrossIsolateException implements Exception {
- /// The name of the type of exception thrown.
- ///
- /// This is the return value of [error.runtimeType.toString()]. Keep in mind
- /// that objects in different libraries may have the same type name.
- final String type;
-
- /// The exception's message, or its [toString] if it didn't expose a `message`
- /// property.
- final String message;
-
- /// The exception's stack chain, or `null` if no stack chain was available.
- final Chain stackTrace;
-
- /// Loads a [CrossIsolateException] from a serialized representation.
- ///
- /// [error] should be the result of [CrossIsolateException.serialize].
- CrossIsolateException.deserialize(Map error)
- : type = error['type'],
- message = error['message'],
- stackTrace = error['stack'] == null ? null :
- new Chain.parse(error['stack']);
-
- /// Serializes [error] to an object that can safely be passed across isolate
- /// boundaries.
- static Map serialize(error, [StackTrace stack]) {
- if (stack == null && error is Error) stack = error.stackTrace;
- return {
- 'type': error.runtimeType.toString(),
- 'message': getErrorMessage(error),
- 'stack': stack == null ? null : new Chain.forTrace(stack).toString()
- };
- }
-
- String toString() => "$message\n$stackTrace";
-}
-
-/// An [AssetNotFoundException] that was originally raised in another isolate.
-class _CrossIsolateAssetNotFoundException extends CrossIsolateException
- implements AssetNotFoundException {
- final AssetId id;
-
- String get message => "Could not find asset $id.";
-
- /// Loads a [_CrossIsolateAssetNotFoundException] from a serialized
- /// representation.
- ///
- /// [error] should be the result of
- /// [_CrossIsolateAssetNotFoundException.serialize].
- _CrossIsolateAssetNotFoundException.deserialize(Map error)
- : id = new AssetId(error['package'], error['path']),
- super.deserialize(error);
-
- /// Serializes [error] to an object that can safely be passed across isolate
- /// boundaries.
- static Map serialize(AssetNotFoundException error, [StackTrace stack]) {
- var map = CrossIsolateException.serialize(error);
- map['package'] = error.id.package;
- map['path'] = error.id.path;
- return map;
- }
-}
-
-/// Serializes [error] to an object that can safely be passed across isolate
-/// boundaries.
-///
-/// This handles [AssetNotFoundException]s specially, ensuring that their
-/// metadata is preserved.
-Map serializeException(error, [StackTrace stack]) {
- if (error is AssetNotFoundException) {
- return _CrossIsolateAssetNotFoundException.serialize(error, stack);
- } else {
- return CrossIsolateException.serialize(error, stack);
- }
-}
-
-/// Loads an exception from a serialized representation.
-///
-/// This handles [AssetNotFoundException]s specially, ensuring that their
-/// metadata is preserved.
-CrossIsolateException deserializeException(Map error) {
- if (error['type'] == 'AssetNotFoundException') {
- return new _CrossIsolateAssetNotFoundException.deserialize(error);
- } else {
- return new CrossIsolateException.deserialize(error);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/get_input_transform.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/get_input_transform.dart
deleted file mode 100644
index 9ab6540..0000000
--- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/get_input_transform.dart
+++ /dev/null
@@ -1,34 +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.
-
-library pub.asset.serialize.get_input_transform;
-
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:barback/barback.dart';
-
-import '../utils.dart';
-
-/// A mixin for transforms that support [getInput] and the associated suite of
-/// methods.
-abstract class GetInputTransform {
- Future<Asset> getInput(AssetId id);
-
- Future<String> readInputAsString(AssetId id, {Encoding encoding}) {
- if (encoding == null) encoding = UTF8;
- return getInput(id).then((input) =>
- input.readAsString(encoding: encoding));
- }
-
- Stream<List<int>> readInput(AssetId id) =>
- futureStream(getInput(id).then((input) => input.read()));
-
- Future<bool> hasInput(AssetId id) {
- return getInput(id).then((_) => true).catchError((error) {
- if (error is AssetNotFoundException && error.id == id) return false;
- throw error;
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/transform.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/transform.dart
deleted file mode 100644
index 911f6f6..0000000
--- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/transform.dart
+++ /dev/null
@@ -1,149 +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.
-
-library pub.asset.serialize.transform;
-
-import 'dart:async';
-import 'dart:isolate';
-
-import 'package:barback/barback.dart';
-// TODO(nweiz): don't import from "src" once issue 14966 is fixed.
-import 'package:barback/src/internal_asset.dart';
-
-import '../serialize.dart';
-import 'get_input_transform.dart';
-
-/// Serialize the methods shared between [Transform] and [DeclaringTransform].
-///
-/// [additionalFields] contains additional serialized fields to add to the
-/// serialized transform. [methodHandlers] is a set of additional methods. Each
-/// value should take a JSON message and return the response (which may be a
-/// Future).
-Map _serializeBaseTransform(transform, Map additionalFields,
- Map<String, Function> methodHandlers) {
- var receivePort = new ReceivePort();
- receivePort.listen((wrappedMessage) {
- respond(wrappedMessage, (message) {
- var handler = methodHandlers[message['type']];
- if (handler != null) return handler(message);
-
- if (message['type'] == 'consumePrimary') {
- transform.consumePrimary();
- return null;
- }
-
- assert(message['type'] == 'log');
- var method = {
- 'Info': transform.logger.info,
- 'Fine': transform.logger.fine,
- 'Warning': transform.logger.warning,
- 'Error': transform.logger.error
- }[message['level']];
- assert(method != null);
-
- var assetId = message['assetId'] == null ? null :
- deserializeId(message['assetId']);
- var span = message['span'] == null ? null :
- deserializeSpan(message['span']);
- method(message['message'], asset: assetId, span: span);
- });
- });
-
- return {'port': receivePort.sendPort}..addAll(additionalFields);
-}
-
-/// Converts [transform] into a serializable map.
-Map serializeTransform(Transform transform) {
- return _serializeBaseTransform(transform, {
- 'primaryInput': serializeAsset(transform.primaryInput)
- }, {
- 'getInput': (message) => transform.getInput(deserializeId(message['id']))
- .then((asset) => serializeAsset(asset)),
- 'addOutput': (message) =>
- transform.addOutput(deserializeAsset(message['output']))
- });
-}
-
-/// Converts [transform] into a serializable map.
-Map serializeDeclaringTransform(DeclaringTransform transform) {
- return _serializeBaseTransform(transform, {
- 'primaryId': serializeId(transform.primaryId)
- }, {
- 'declareOutput': (message) =>
- transform.declareOutput(deserializeId(message['output']))
- });
-}
-
-/// The base class for wrappers for [Transform]s that are in the host isolate.
-class _ForeignBaseTransform {
- /// The port with which we communicate with the host isolate.
- ///
- /// This port and all messages sent across it are specific to this transform.
- final SendPort _port;
-
- TransformLogger get logger => _logger;
- TransformLogger _logger;
-
- _ForeignBaseTransform(Map transform)
- : _port = transform['port'] {
- _logger = new TransformLogger((assetId, level, message, span) {
- call(_port, {
- 'type': 'log',
- 'level': level.name,
- 'message': message,
- 'assetId': assetId == null ? null : serializeId(assetId),
- 'span': span == null ? null : serializeSpan(span)
- });
- });
- }
-
- void consumePrimary() {
- call(_port, {'type': 'consumePrimary'});
- }
-}
-
-/// A wrapper for a [Transform] that's in the host isolate.
-///
-/// This retrieves inputs from and sends outputs and logs to the host isolate.
-class ForeignTransform extends _ForeignBaseTransform
- with GetInputTransform implements Transform {
- final Asset primaryInput;
-
- /// Creates a transform from a serialized map sent from the host isolate.
- ForeignTransform(Map transform)
- : primaryInput = deserializeAsset(transform['primaryInput']),
- super(transform);
-
- Future<Asset> getInput(AssetId id) {
- return call(_port, {
- 'type': 'getInput',
- 'id': serializeId(id)
- }).then(deserializeAsset);
- }
-
- void addOutput(Asset output) {
- call(_port, {
- 'type': 'addOutput',
- 'output': serializeAsset(output)
- });
- }
-}
-
-/// A wrapper for a [DeclaringTransform] that's in the host isolate.
-class ForeignDeclaringTransform extends _ForeignBaseTransform
- implements DeclaringTransform {
- final AssetId primaryId;
-
- /// Creates a transform from a serializable map sent from the host isolate.
- ForeignDeclaringTransform(Map transform)
- : primaryId = deserializeId(transform['primaryId']),
- super(transform);
-
- void declareOutput(AssetId id) {
- call(_port, {
- 'type': 'declareOutput',
- 'output': serializeId(id)
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/transformer.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/transformer.dart
deleted file mode 100644
index 16d02de..0000000
--- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/transformer.dart
+++ /dev/null
@@ -1,126 +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.
-
-library pub.asset.serialize.transformer;
-
-import 'dart:async';
-import 'dart:isolate';
-
-import 'package:barback/barback.dart';
-
-import '../serialize.dart';
-import 'transform.dart';
-
-/// Converts [transformer] into a serializable map.
-Map _serializeTransformer(Transformer transformer) {
- var port = new ReceivePort();
- port.listen((wrappedMessage) {
- respond(wrappedMessage, (message) {
- if (message['type'] == 'isPrimary') {
- return transformer.isPrimary(deserializeId(message['id']));
- } else if (message['type'] == 'declareOutputs') {
- return new Future.sync(() {
- return (transformer as DeclaringTransformer).declareOutputs(
- new ForeignDeclaringTransform(message['transform']));
- }).then((_) => null);
- } else {
- assert(message['type'] == 'apply');
-
- // Make sure we return null so that if the transformer's [apply] returns
- // a non-serializable value it doesn't cause problems.
- return new Future.sync(() {
- return transformer.apply(new ForeignTransform(message['transform']));
- }).then((_) => null);
- }
- });
- });
-
- var type;
- if (transformer is LazyTransformer) {
- type = 'LazyTransformer';
- } else if (transformer is DeclaringTransformer) {
- type = 'DeclaringTransformer';
- } else {
- type = 'Transformer';
- }
-
- return {
- 'type': type,
- 'toString': transformer.toString(),
- 'port': port.sendPort
- };
-}
-
-/// Converts [transformer] into a serializable map.
-Map _serializeAggregateTransformer(AggregateTransformer transformer) {
- var port = new ReceivePort();
- port.listen((wrappedMessage) {
- respond(wrappedMessage, (message) {
- if (message['type'] == 'classifyPrimary') {
- return transformer.classifyPrimary(deserializeId(message['id']));
- } else if (message['type'] == 'declareOutputs') {
- return new Future.sync(() {
- return (transformer as DeclaringAggregateTransformer).declareOutputs(
- new ForeignDeclaringAggregateTransform(message['transform']));
- }).then((_) => null);
- } else {
- assert(message['type'] == 'apply');
-
- // Make sure we return null so that if the transformer's [apply] returns
- // a non-serializable value it doesn't cause problems.
- return new Future.sync(() {
- return transformer.apply(
- new ForeignAggregateTransform(message['transform']));
- }).then((_) => null);
- }
- });
- });
-
- var type;
- if (transformer is LazyAggregateTransformer) {
- type = 'LazyAggregateTransformer';
- } else if (transformer is DeclaringAggregateTransformer) {
- type = 'DeclaringAggregateTransformer';
- } else {
- type = 'AggregateTransformer';
- }
-
- return {
- 'type': type,
- 'toString': transformer.toString(),
- 'port': port.sendPort
- };
-}
-
-// Converts [group] into a serializable map.
-Map _serializeTransformerGroup(TransformerGroup group) {
- if (group.phases == null) {
- throw "TransformerGroup $group phases cannot be null.";
- }
-
- return {
- 'type': 'TransformerGroup',
- 'toString': group.toString(),
- 'phases': group.phases.map((phase) {
- return phase.map(serializeTransformerLike).toList();
- }).toList()
- };
-}
-
-/// Converts [transformerLike] into a serializable map.
-///
-/// [transformerLike] can be a [Transformer], an [AggregateTransformer], or a
-/// [TransformerGroup].
-Map serializeTransformerLike(transformerLike) {
- if (transformerLike is Transformer) {
- return _serializeTransformer(transformerLike);
- } else if (transformerLike is TransformerGroup) {
- return _serializeTransformerGroup(transformerLike);
- } else {
- // This has to be last, since "transformerLike is AggregateTransformer" will
- // throw on older versions of barback.
- assert(transformerLike is AggregateTransformer);
- return _serializeAggregateTransformer(transformerLike);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/asset/dart/transformer_isolate.dart b/sdk/lib/_internal/pub_generated/asset/dart/transformer_isolate.dart
deleted file mode 100644
index 50bb97b..0000000
--- a/sdk/lib/_internal/pub_generated/asset/dart/transformer_isolate.dart
+++ /dev/null
@@ -1,112 +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.
-
-library pub.asset.transformer_isolate;
-
-import 'dart:convert';
-import 'dart:isolate';
-import 'dart:mirrors';
-
-import 'package:barback/barback.dart';
-
-import 'serialize.dart';
-
-/// The mirror system.
-///
-/// Cached to avoid re-instantiating each time a transformer is initialized.
-final _mirrors = currentMirrorSystem();
-
-/// Sets up the initial communication with the host isolate.
-void loadTransformers(SendPort replyTo) {
- var port = new ReceivePort();
- replyTo.send(port.sendPort);
- port.listen((wrappedMessage) {
- // TODO(nweiz): When issue 19228 is fixed, spin up a separate isolate for
- // libraries loaded beyond the first so they can run in parallel.
- respond(wrappedMessage, (message) {
- var configuration = JSON.decode(message['configuration']);
- var mode = new BarbackMode(message['mode']);
- return _initialize(message['library'], configuration, mode).
- map(serializeTransformerLike).toList();
- });
- });
-}
-
-/// Loads all the transformers and groups defined in [uri].
-///
-/// Loads the library, finds any [Transformer] or [TransformerGroup] subclasses
-/// in it, instantiates them with [configuration] and [mode], and returns them.
-List _initialize(String uri, Map configuration, BarbackMode mode) {
- var transformerClass = reflectClass(Transformer);
- var aggregateClass = _aggregateTransformerClass;
- var groupClass = reflectClass(TransformerGroup);
-
- var seen = new Set();
- var transformers = [];
-
- loadFromLibrary(library) {
- if (seen.contains(library)) return;
- seen.add(library);
-
- // Load transformers from libraries exported by [library].
- for (var dependency in library.libraryDependencies) {
- if (!dependency.isExport) continue;
- loadFromLibrary(dependency.targetLibrary);
- }
-
- // TODO(nweiz): if no valid transformers are found, throw an error message
- // describing candidates and why they were rejected.
- transformers.addAll(library.declarations.values.map((declaration) {
- if (declaration is! ClassMirror) return null;
- var classMirror = declaration;
- if (classMirror.isPrivate) return null;
- if (classMirror.isAbstract) return null;
- if (!classMirror.isSubtypeOf(transformerClass) &&
- !classMirror.isSubtypeOf(groupClass) &&
- (aggregateClass == null ||
- !classMirror.isSubtypeOf(aggregateClass))) {
- return null;
- }
-
- var constructor = _getConstructor(classMirror, 'asPlugin');
- if (constructor == null) return null;
- if (constructor.parameters.isEmpty) {
- if (configuration.isNotEmpty) return null;
- return classMirror.newInstance(const Symbol('asPlugin'), []).reflectee;
- }
- if (constructor.parameters.length != 1) return null;
-
- return classMirror.newInstance(const Symbol('asPlugin'),
- [new BarbackSettings(configuration, mode)]).reflectee;
- }).where((classMirror) => classMirror != null));
- }
-
- var library = _mirrors.libraries[Uri.parse(uri)];
-
- // This should only happen if something's wrong with the logic in pub itself.
- // If it were user error, the entire isolate would fail to load.
- if (library == null) throw "Couldn't find library at $uri.";
-
- loadFromLibrary(library);
- return transformers;
-}
-
-// TODO(nweiz): clean this up when issue 13248 is fixed.
-MethodMirror _getConstructor(ClassMirror classMirror, String constructor) {
- var name = new Symbol("${MirrorSystem.getName(classMirror.simpleName)}"
- ".$constructor");
- var candidate = classMirror.declarations[name];
- if (candidate is MethodMirror && candidate.isConstructor) return candidate;
- return null;
-}
-
-// Older barbacks don't support [AggregateTransformer], and calling
-// [reflectClass] on an undefined class will throw an error, so we just define a
-// null getter for them.
-//# if barback >=0.14.1
-ClassMirror get _aggregateTransformerClass =>
- reflectClass(AggregateTransformer);
-//# else
-//> ClassMirror get _aggregateTransformerClass => null;
-//# end
diff --git a/sdk/lib/_internal/pub_generated/asset/dart/utils.dart b/sdk/lib/_internal/pub_generated/asset/dart/utils.dart
deleted file mode 100644
index 72150ed..0000000
--- a/sdk/lib/_internal/pub_generated/asset/dart/utils.dart
+++ /dev/null
@@ -1,86 +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.
-
-/// Functions go in this file as opposed to lib/src/utils.dart if they need to
-/// be accessible to the transformer-loading isolate.
-library pub.asset.utils;
-
-import 'dart:async';
-
-/// A regular expression to match the exception prefix that some exceptions'
-/// [Object.toString] values contain.
-final _exceptionPrefix = new RegExp(r'^([A-Z][a-zA-Z]*)?(Exception|Error): ');
-
-/// Get a string description of an exception.
-///
-/// Many exceptions include the exception class name at the beginning of their
-/// [toString], so we remove that if it exists.
-String getErrorMessage(error) =>
- error.toString().replaceFirst(_exceptionPrefix, '');
-
-/// Returns a buffered stream that will emit the same values as the stream
-/// returned by [future] once [future] completes.
-///
-/// If [future] completes to an error, the return value will emit that error and
-/// then close.
-///
-/// If [broadcast] is true, a broadcast stream is returned. This assumes that
-/// the stream returned by [future] will be a broadcast stream as well.
-/// [broadcast] defaults to false.
-Stream futureStream(Future<Stream> future, {bool broadcast: false}) {
- var subscription;
- var controller;
-
- future = future.catchError((e, stackTrace) {
- // Since [controller] is synchronous, it's likely that emitting an error
- // will cause it to be cancelled before we call close.
- if (controller != null) controller.addError(e, stackTrace);
- if (controller != null) controller.close();
- controller = null;
- });
-
- onListen() {
- future.then((stream) {
- if (controller == null) return;
- subscription = stream.listen(
- controller.add,
- onError: controller.addError,
- onDone: controller.close);
- });
- }
-
- onCancel() {
- if (subscription != null) subscription.cancel();
- subscription = null;
- controller = null;
- }
-
- if (broadcast) {
- controller = new StreamController.broadcast(
- sync: true, onListen: onListen, onCancel: onCancel);
- } else {
- controller = new StreamController(
- sync: true, onListen: onListen, onCancel: onCancel);
- }
- return controller.stream;
-}
-
-/// Returns a [Stream] that will emit the same values as the stream returned by
-/// [callback].
-///
-/// [callback] will only be called when the returned [Stream] gets a subscriber.
-Stream callbackStream(Stream callback()) {
- var subscription;
- var controller;
- controller = new StreamController(onListen: () {
- subscription = callback().listen(controller.add,
- onError: controller.addError,
- onDone: controller.close);
- },
- onCancel: () => subscription.cancel(),
- onPause: () => subscription.pause(),
- onResume: () => subscription.resume(),
- sync: true);
- return controller.stream;
-}
diff --git a/sdk/lib/_internal/pub_generated/bin/async_compile.dart b/sdk/lib/_internal/pub_generated/bin/async_compile.dart
deleted file mode 100644
index 2e96717..0000000
--- a/sdk/lib/_internal/pub_generated/bin/async_compile.dart
+++ /dev/null
@@ -1,294 +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 'dart:io';
-
-import 'package:args/args.dart';
-import 'package:analyzer/src/services/formatter_impl.dart';
-import 'package:async_await/async_await.dart' as async_await;
-import 'package:stack_trace/stack_trace.dart';
-import 'package:path/path.dart' as p;
-
-/// The path to pub's root directory (sdk/lib/_internal/pub) in the Dart repo.
-///
-/// This assumes this script is itself being run from within the repo.
-final sourceDir = p.dirname(p.dirname(p.fromUri(Platform.script)));
-
-/// The [sourceDir] as a URL, for use in import strings.
-final sourceUrl = p.toUri(sourceDir).toString();
-
-/// The directory that compiler output should be written to.
-String generatedDir;
-
-/// `true` if any file failed to compile.
-bool hadFailure = false;
-
-bool verbose = false;
-
-/// Prefix for imports in pub that import dart2js libraries.
-final _compilerPattern = new RegExp(r"import '(\.\./)+compiler");
-
-/// Matches the Git commit hash of the compiler stored in the README.md file.
-///
-/// This is used both to find the current commit and replace it with the new
-/// one.
-final _commitPattern = new RegExp(r"[a-f0-9]{40}");
-
-/// The template for the README that's added to the generated source.
-///
-/// This is used to store the current commit of the async_await compiler.
-const _README = """
-Pub is currently dogfooding the new Dart async/await syntax. Since the Dart VM
-doesn't natively support it yet, we are using the [async-await][] compiler
-package.
-
-[async-await]: https://github.com/dart-lang/async_await
-
-We run that to compile pub-using-await from sdk/lib/_internal/pub down to
-vanilla Dart code which is what you see here. To interoperate more easily with
-the rest of the repositry, we check in that generated code.
-
-When bug #104 is fixed, we can remove this entirely.
-
-The code here was compiled using the async-await compiler at commit:
-
- <<COMMIT>>
-
-(Note: this file is also parsed by a tool to update the above commit, so be
-careful not to reformat it.)
-""";
-
-/// This runs the async/await compiler on all of the pub source code.
-///
-/// It reads from the repo and writes the compiled output into the given build
-/// directory (using the same file names and relative layout). Does not
-/// compile files that haven't changed since the last time they were compiled.
-// TODO(rnystrom): Remove this when #104 is fixed.
-void main(List<String> arguments) {
- var parser = new ArgParser(allowTrailingOptions: true);
-
- parser.addFlag("verbose", callback: (value) => verbose = value);
-
- var force = false;
- parser.addFlag("force", callback: (value) => force = value);
-
- var buildDir;
- parser.addOption("snapshot-build-dir", callback: (value) => buildDir = value);
-
- try {
- var rest = parser.parse(arguments).rest;
- if (rest.isEmpty) {
- throw new FormatException('Missing generated directory.');
- } else if (rest.length > 1) {
- throw new FormatException(
- 'Unexpected arguments: ${rest.skip(1).join(" ")}.');
- }
-
- generatedDir = rest.first;
- } on FormatException catch (ex) {
- stderr.writeln(ex);
- stderr.writeln();
- stderr.writeln(
- "Usage: dart async_compile.dart [--verbose] [--force] "
- "[--snapshot-build-dir <dir>] <generated dir>");
- exit(64);
- }
-
- // See what version (i.e. Git commit) of the async-await compiler we
- // currently have. If this is different from the version that was used to
- // compile the sources, recompile everything.
- var currentCommit = _getCurrentCommit();
-
- var readmePath = p.join(generatedDir, "README.md");
- var lastCommit;
- try {
- var readme = new File(readmePath).readAsStringSync();
- var match = _commitPattern.firstMatch(readme);
- if (match == null) {
- stderr.writeln("Could not find compiler commit hash in README.md.");
- exit(1);
- }
-
- lastCommit = match[0];
- } on IOException catch (error, stackTrace) {
- if (verbose) {
- stderr.writeln(
- "Failed to load $readmePath: $error\n" "${new Trace.from(stackTrace)}");
- }
- }
-
- var numFiles = 0;
- var numCompiled = 0;
-
- // Compile any modified or missing files.
- var sources = new Set();
- for (var entry in new Directory(sourceDir).listSync(recursive: true)) {
- if (p.extension(entry.path) != ".dart") continue;
-
- numFiles++;
- var relative = p.relative(entry.path, from: sourceDir);
- sources.add(relative);
-
- var sourceFile = entry as File;
- var destPath = p.join(generatedDir, relative);
- var destFile = new File(destPath);
- if (force ||
- currentCommit != lastCommit ||
- !destFile.existsSync() ||
- entry.lastModifiedSync().isAfter(destFile.lastModifiedSync())) {
- _compile(sourceFile.path, sourceFile.readAsStringSync(), destPath);
- numCompiled++;
- if (verbose) print("Compiled $relative");
- }
- }
-
- // Delete any previously compiled files whose source no longer exists.
- for (var entry in new Directory(generatedDir).listSync(recursive: true)) {
- if (p.extension(entry.path) != ".dart") continue;
-
- var relative = p.relative(entry.path, from: generatedDir);
-
- if (!sources.contains(relative)) {
- _deleteFile(entry.path);
- if (verbose) print("Deleted $relative");
- }
- }
-
- // Update the README.
- if (currentCommit != lastCommit) {
- _writeFile(readmePath, _README.replaceAll("<<COMMIT>>", currentCommit));
- if (verbose) print("Updated README.md");
- }
-
- if (numCompiled > 0 && buildDir != null) _generateSnapshot(buildDir);
-
- if (verbose) print("Compiled $numCompiled out of $numFiles files");
-
- if (hadFailure) exit(1);
-}
-
-String _getCurrentCommit() {
- var command = "git";
- var args = ["rev-parse", "HEAD"];
-
- // Spawning a process on Windows will not look for the executable in the
- // system path so spawn git through a shell to find it.
- if (Platform.operatingSystem == "windows") {
- command = "cmd";
- args = ["/c", "git"]..addAll(args);
- }
-
- var result = Process.runSync(
- command,
- args,
- workingDirectory: p.join(sourceDir, "../../../../third_party/pkg/async_await"));
- if (result.exitCode != 0) {
- stderr.writeln("Could not get Git revision of async_await compiler.");
- exit(1);
- }
-
- return result.stdout.trim();
-}
-
-void _compile(String sourcePath, String source, String destPath) {
- var destDir = new Directory(p.dirname(destPath));
- destDir.createSync(recursive: true);
-
- source = _translateAsyncAwait(sourcePath, source);
- if (source != null) source = _fixDart2jsImports(sourcePath, source, destPath);
-
- if (source == null) {
- // If the async compile fails, delete the file so that we don't try to
- // run the stale previous output and so that we try to recompile it later.
- _deleteFile(destPath);
- } else {
- _writeFile(destPath, source);
- }
-}
-
-/// Runs the async/await compiler on [source].
-///
-/// Returns the translated Dart code or `null` if the compiler failed.
-String _translateAsyncAwait(String sourcePath, String source) {
- if (p.isWithin(p.join(sourceDir, "asset"), sourcePath)) {
- // Don't run the async compiler on the special "asset" source files. These
- // have preprocessor comments that get discarded by the compiler.
- return source;
- }
-
- try {
- source = async_await.compile(source);
-
- // Reformat the result since the compiler ditches all whitespace.
- // TODO(rnystrom): Remove when this is fixed:
- // https://github.com/dart-lang/async_await/issues/12
- var result = new CodeFormatter().format(CodeKind.COMPILATION_UNIT, source);
- return result.source;
- } catch (ex) {
- stderr.writeln("Async compile failed on $sourcePath:\n$ex");
- hadFailure = true;
- return null;
- }
-}
-
-/// Fix relative imports to dart2js libraries.
-///
-/// Pub imports dart2js using relative imports that reach outside of pub's
-/// source tree. Since the build directory is in a different location, we need
-/// to fix those to be valid relative imports from the build directory.
-String _fixDart2jsImports(String sourcePath, String source, String destPath) {
- var compilerDir = p.url.join(sourceUrl, "../compiler");
- var relative =
- p.url.relative(compilerDir, from: p.url.dirname(p.toUri(destPath).toString()));
- return source.replaceAll(_compilerPattern, "import '$relative");
-}
-
-/// Regenerate the pub snapshot from the async/await-compiled output. We do
-/// this here since the tests need it and it's faster than doing a full SDK
-/// build.
-void _generateSnapshot(String buildDir) {
- buildDir = p.normalize(buildDir);
- new Directory(buildDir).createSync(recursive: true);
-
- var entrypoint = p.join(generatedDir, 'bin/pub.dart');
- var packageRoot = p.join(buildDir, 'packages');
- var snapshot = p.join(buildDir, 'dart-sdk/bin/snapshots/pub.dart.snapshot');
-
- var result = Process.runSync(
- Platform.executable,
- ["--package-root=$packageRoot", "--snapshot=$snapshot", entrypoint]);
-
- if (result.exitCode != 0) {
- stderr.writeln("Failed to generate snapshot:");
- if (result.stderr.trim().isNotEmpty) stderr.writeln(result.stderr);
- if (result.stdout.trim().isNotEmpty) stderr.writeln(result.stdout);
- exit(result.exitCode);
- }
-
- if (verbose) print("Created pub snapshot");
-}
-
-/// Deletes the file at [path], ignoring any IO errors that occur.
-///
-/// This swallows errors to accommodate multiple compilers running concurrently.
-/// Since they will produce the same output anyway, a failure of one is fine.
-void _deleteFile(String path) {
- try {
- new File(path).deleteSync();
- } on IOException catch (ex) {
- // Do nothing.
- }
-}
-
-/// Writes [contents] to [path], ignoring any IO errors that occur.
-///
-/// This swallows errors to accommodate multiple compilers running concurrently.
-/// Since they will produce the same output anyway, a failure of one is fine.
-void _writeFile(String path, String contents) {
- try {
- new File(path).writeAsStringSync(contents);
- } on IOException catch (ex) {
- // Do nothing.
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/bin/pub.dart b/sdk/lib/_internal/pub_generated/bin/pub.dart
deleted file mode 100644
index e781f94..0000000
--- a/sdk/lib/_internal/pub_generated/bin/pub.dart
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright (c) 2013, 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 '../lib/src/command_runner.dart';
-
-void main(List<String> arguments) {
- new PubCommandRunner().run(arguments);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/ascii_tree.dart b/sdk/lib/_internal/pub_generated/lib/src/ascii_tree.dart
deleted file mode 100644
index ca8d510..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/ascii_tree.dart
+++ /dev/null
@@ -1,173 +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.
-
-/// A simple library for rendering tree-like structures in ASCII.
-library pub.ascii_tree;
-
-import 'package:path/path.dart' as path;
-
-import 'log.dart' as log;
-import 'utils.dart';
-
-/// Draws a tree for the given list of files. Given files like:
-///
-/// TODO
-/// example/console_example.dart
-/// example/main.dart
-/// example/web copy/web_example.dart
-/// test/absolute_test.dart
-/// test/basename_test.dart
-/// test/dirname_test.dart
-/// test/extension_test.dart
-/// test/is_absolute_test.dart
-/// test/is_relative_test.dart
-/// test/join_test.dart
-/// test/normalize_test.dart
-/// test/relative_test.dart
-/// test/split_test.dart
-/// .gitignore
-/// README.md
-/// lib/path.dart
-/// pubspec.yaml
-/// test/all_test.dart
-/// test/path_posix_test.dart
-/// test/path_windows_test.dart
-///
-/// this renders:
-///
-/// |-- .gitignore
-/// |-- README.md
-/// |-- TODO
-/// |-- example
-/// | |-- console_example.dart
-/// | |-- main.dart
-/// | '-- web copy
-/// | '-- web_example.dart
-/// |-- lib
-/// | '-- path.dart
-/// |-- pubspec.yaml
-/// '-- test
-/// |-- absolute_test.dart
-/// |-- all_test.dart
-/// |-- basename_test.dart
-/// | (7 more...)
-/// |-- path_windows_test.dart
-/// |-- relative_test.dart
-/// '-- split_test.dart
-///
-/// If [baseDir] is passed, it will be used as the root of the tree.
-///
-/// If [showAllChildren] is `false`, then directories with more than ten items
-/// will have their contents truncated. Defaults to `false`.
-String fromFiles(List<String> files, {String baseDir, bool showAllChildren}) {
- // Parse out the files into a tree of nested maps.
- var root = {};
- for (var file in files) {
- if (baseDir != null) file = path.relative(file, from: baseDir);
- var parts = path.split(file);
- var directory = root;
- for (var part in path.split(file)) {
- directory = directory.putIfAbsent(part, () => {});
- }
- }
-
- // Walk the map recursively and render to a string.
- return fromMap(root, showAllChildren: showAllChildren);
-}
-
-/// Draws a tree from a nested map. Given a map like:
-///
-/// {
-/// "analyzer": {
-/// "args": {
-/// "collection": ""
-/// },
-/// "logging": {}
-/// },
-/// "barback": {}
-/// }
-///
-/// this renders:
-///
-/// analyzer
-/// |-- args
-/// | '-- collection
-/// '---logging
-/// barback
-///
-/// Items with no children should have an empty map as the value.
-///
-/// If [showAllChildren] is `false`, then directories with more than ten items
-/// will have their contents truncated. Defaults to `false`.
-String fromMap(Map map, {bool showAllChildren}) {
- var buffer = new StringBuffer();
- _draw(buffer, "", null, map, showAllChildren: showAllChildren);
- return buffer.toString();
-}
-
-void _drawLine(StringBuffer buffer, String prefix, bool isLastChild,
- String name) {
- // Print lines.
- buffer.write(prefix);
- if (name != null) {
- if (isLastChild) {
- buffer.write(log.gray("'-- "));
- } else {
- buffer.write(log.gray("|-- "));
- }
- }
-
- // Print name.
- buffer.writeln(name);
-}
-
-String _getPrefix(bool isRoot, bool isLast) {
- if (isRoot) return "";
- if (isLast) return " ";
- return log.gray("| ");
-}
-
-void _draw(StringBuffer buffer, String prefix, String name, Map children,
- {bool showAllChildren, bool isLast: false}) {
- if (showAllChildren == null) showAllChildren = false;
-
- // Don't draw a line for the root node.
- if (name != null) _drawLine(buffer, prefix, isLast, name);
-
- // Recurse to the children.
- var childNames = ordered(children.keys);
-
- drawChild(bool isLastChild, String child) {
- var childPrefix = _getPrefix(name == null, isLast);
- _draw(
- buffer,
- '$prefix$childPrefix',
- child,
- children[child],
- showAllChildren: showAllChildren,
- isLast: isLastChild);
- }
-
- if (name == null || showAllChildren || childNames.length <= 10) {
- // Not too many, so show all the children.
- for (var i = 0; i < childNames.length; i++) {
- drawChild(i == childNames.length - 1, childNames[i]);
- }
- } else {
- // Show the first few.
- drawChild(false, childNames[0]);
- drawChild(false, childNames[1]);
- drawChild(false, childNames[2]);
-
- // Elide the middle ones.
- buffer.write(prefix);
- buffer.write(_getPrefix(name == null, isLast));
- buffer.writeln(log.gray('| (${childNames.length - 6} more...)'));
-
- // Show the last few.
- drawChild(false, childNames[childNames.length - 3]);
- drawChild(false, childNames[childNames.length - 2]);
- drawChild(true, childNames[childNames.length - 1]);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback.dart b/sdk/lib/_internal/pub_generated/lib/src/barback.dart
deleted file mode 100644
index ea7e650..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback.dart
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright (c) 2013, 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 pub.barback;
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-import 'package:pub_semver/pub_semver.dart';
-
-/// The currently supported versions of packages that this version of pub works
-/// with.
-///
-/// Pub implicitly constrains these packages to these versions as long as
-/// barback is a dependency.
-///
-/// Users' transformers are loaded in an isolate that uses the entrypoint
-/// package's dependency versions. However, that isolate also loads code
-/// provided by pub (`asset/dart/transformer_isolate.dart` and associated
-/// files). This code uses these packages as well, so these constraints exist to
-/// ensure that its usage of the packages remains valid.
-///
-/// Most constraints here are like normal version constraints in that their
-/// upper bound is the next major version of the package (or minor version for
-/// pre-1.0.0 packages). If a new major version of the package is released,
-/// these *must* be incremented to synchronize with that.
-///
-/// The constraint on barback is different. Its upper bound is the next *patch*
-/// version of barback—that is, the next version with new features. This is
-/// because most barback features need additional serialization code to be fully
-/// supported in pub, even if they're otherwise backwards-compatible.
-///
-/// Whenever a new minor or patch version of barback is published, this *must*
-/// be incremented to synchronize with that. See the barback [compatibility
-/// documentation][compat] for details on the relationship between this
-/// constraint and barback's version.
-///
-/// [compat]: https://gist.github.com/nex3/10942218
-final pubConstraints = {
- "barback": new VersionConstraint.parse(">=0.13.0 <0.15.3"),
- "source_span": new VersionConstraint.parse(">=1.0.0 <2.0.0"),
- "stack_trace": new VersionConstraint.parse(">=0.9.1 <2.0.0")
-};
-
-/// Converts [id] to a "package:" URI.
-///
-/// This will throw an [ArgumentError] if [id] doesn't represent a library in
-/// `lib/`.
-Uri idToPackageUri(AssetId id) {
- if (!id.path.startsWith('lib/')) {
- throw new ArgumentError("Asset id $id doesn't identify a library.");
- }
-
- return new Uri(
- scheme: 'package',
- path: p.url.join(id.package, id.path.replaceFirst('lib/', '')));
-}
-
-/// Converts [uri] into an [AssetId] if its path is within "packages".
-///
-/// If the URL contains a special directory, but lacks a following package name,
-/// throws a [FormatException].
-///
-/// If the URI doesn't contain one of those special directories, returns null.
-AssetId packagesUrlToId(Uri url) {
- var parts = p.url.split(url.path);
-
- // Strip the leading "/" from the URL.
- if (parts.isNotEmpty && parts.first == "/") parts = parts.skip(1).toList();
-
- if (parts.isEmpty) return null;
-
- // Check for "packages" in the URL.
- // TODO(rnystrom): If we rewrite "package:" imports to relative imports that
- // point to a canonical "packages" directory, we can limit "packages" to the
- // root of the URL as well. See: #16649.
- var index = parts.indexOf("packages");
- if (index == -1) return null;
-
- // There should be a package name after "packages".
- if (parts.length <= index + 1) {
- throw new FormatException(
- 'Invalid URL path "${url.path}". Expected package name ' 'after "packages".');
- }
-
- var package = parts[index + 1];
- var assetPath = p.url.join("lib", p.url.joinAll(parts.skip(index + 2)));
- return new AssetId(package, assetPath);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/admin_server.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/admin_server.dart
deleted file mode 100644
index 36bb621..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/admin_server.dart
+++ /dev/null
@@ -1,70 +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.
-
-library pub.barback.admin_server;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:http_parser/http_parser.dart';
-import 'package:shelf/shelf.dart' as shelf;
-import 'package:shelf_web_socket/shelf_web_socket.dart';
-
-import '../io.dart';
-import '../log.dart' as log;
-import 'asset_environment.dart';
-import 'base_server.dart';
-import 'web_socket_api.dart';
-
-/// The web admin interface to pub serve.
-// TODO(rnystrom): Currently this just provides access to the Web Socket API.
-// See #16954.
-class AdminServer extends BaseServer {
- /// All currently open [WebSocket] connections.
- final _webSockets = new Set<CompatibleWebSocket>();
-
- shelf.Handler _handler;
-
- /// Creates a new server and binds it to [port] of [host].
- static Future<AdminServer> bind(AssetEnvironment environment, String host,
- int port) {
- return bindServer(host, port).then((server) {
- log.fine('Bound admin server to $host:$port.');
- return new AdminServer._(environment, server);
- });
- }
-
- AdminServer._(AssetEnvironment environment, HttpServer server)
- : super(environment, server) {
- _handler = new shelf.Cascade().add(
- webSocketHandler(_handleWebSocket)).add(_handleHttp).handler;
- }
-
- /// Closes the server and all Web Socket connections.
- Future close() {
- var futures = [super.close()];
- futures.addAll(_webSockets.map((socket) => socket.close()));
- return Future.wait(futures);
- }
-
- handleRequest(shelf.Request request) => _handler(request);
-
- /// Handles an HTTP request.
- _handleHttp(shelf.Request request) {
- // TODO(rnystrom): Actually respond to requests once there is an admin
- // interface. See #16954.
- logRequest(request, "501 Not Implemented");
- return new shelf.Response(
- 501,
- body: "Currently this server only accepts Web Socket connections.");
- }
-
- /// Creates a web socket for [request] which should be an upgrade request.
- void _handleWebSocket(CompatibleWebSocket socket) {
- _webSockets.add(socket);
- var api = new WebSocketApi(socket, environment);
- api.listen().whenComplete(
- () => _webSockets.remove(api)).catchError(addError);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/asset_environment.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/asset_environment.dart
deleted file mode 100644
index 8316d4e..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/asset_environment.dart
+++ /dev/null
@@ -1,960 +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.
-
-library pub.barback.asset_environment;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as path;
-import 'package:watcher/watcher.dart';
-
-import '../cached_package.dart';
-import '../entrypoint.dart';
-import '../exceptions.dart';
-import '../io.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../package_graph.dart';
-import '../sdk.dart' as sdk;
-import '../source/cached.dart';
-import '../utils.dart';
-import 'admin_server.dart';
-import 'barback_server.dart';
-import 'dart_forwarding_transformer.dart';
-import 'dart2js_transformer.dart';
-import 'load_all_transformers.dart';
-import 'pub_package_provider.dart';
-import 'source_directory.dart';
-
-/// The entire "visible" state of the assets of a package and all of its
-/// dependencies, taking into account the user's configuration when running pub.
-///
-/// Where [PackageGraph] just describes the entrypoint's dependencies as
-/// specified by pubspecs, this includes "transient" information like the mode
-/// that the user is running pub in, or which directories they want to
-/// transform.
-class AssetEnvironment {
- /// Creates a new build environment for working with the assets used by
- /// [entrypoint] and its dependencies.
- ///
- /// HTTP servers that serve directories from this environment will be bound
- /// to [hostname] and have ports based on [basePort]. If omitted, they
- /// default to "localhost" and "0" (use ephemeral ports), respectively.
- ///
- /// Loads all used transformers using [mode] (including dart2js if
- /// [useDart2JS] is true).
- ///
- /// This will only add the root package's "lib" directory to the environment.
- /// Other directories can be added to the environment using [serveDirectory].
- ///
- /// If [watcherType] is not [WatcherType.NONE] (the default), watches source
- /// assets for modification.
- ///
- /// If [packages] is passed, only those packages' assets are loaded and
- /// served.
- ///
- /// If [entrypoints] is passed, only transformers necessary to run those
- /// entrypoints are loaded. Each entrypoint is expected to refer to a Dart
- /// library.
- ///
- /// Returns a [Future] that completes to the environment once the inputs,
- /// transformers, and server are loaded and ready.
- static Future<AssetEnvironment> create(Entrypoint entrypoint,
- BarbackMode mode, {WatcherType watcherType, String hostname, int basePort,
- Iterable<String> packages, Iterable<AssetId> entrypoints, bool useDart2JS:
- true}) {
- if (watcherType == null) watcherType = WatcherType.NONE;
- if (hostname == null) hostname = "localhost";
- if (basePort == null) basePort = 0;
-
- return log.progress("Loading asset environment", () {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(entrypoint.loadPackageGraph()).then((x0) {
- try {
- var graph = x0;
- graph = _adjustPackageGraph(graph, mode, packages);
- var barback = new Barback(new PubPackageProvider(graph));
- barback.log.listen(_log);
- var environment =
- new AssetEnvironment._(graph, barback, mode, watcherType, hostname, basePort);
- new Future.value(
- environment._load(entrypoints: entrypoints, useDart2JS: useDart2JS)).then((x1) {
- try {
- x1;
- completer0.complete(environment);
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }, fine: true);
- }
-
- /// Return a version of [graph] that's restricted to [packages] (if passed)
- /// and loads cached packages (if [mode] is [BarbackMode.DEBUG]).
- static PackageGraph _adjustPackageGraph(PackageGraph graph, BarbackMode mode,
- Iterable<String> packages) {
- if (mode != BarbackMode.DEBUG && packages == null) return graph;
- packages = (packages == null ? graph.packages.keys : packages).toSet();
-
- return new PackageGraph(
- graph.entrypoint,
- graph.lockFile,
- new Map.fromIterable(packages, value: (packageName) {
- var package = graph.packages[packageName];
- if (mode != BarbackMode.DEBUG) return package;
- var cache = path.join('.pub/deps/debug', packageName);
- if (!dirExists(cache)) return package;
- return new CachedPackage(package, cache);
- }));
- }
-
- /// The server for the Web Socket API and admin interface.
- AdminServer _adminServer;
-
- /// The public directories in the root package that are included in the asset
- /// environment, keyed by their root directory.
- final _directories = new Map<String, SourceDirectory>();
-
- /// The [Barback] instance used to process assets in this environment.
- final Barback barback;
-
- /// The root package being built.
- Package get rootPackage => graph.entrypoint.root;
-
- /// The graph of packages whose assets and transformers are loaded in this
- /// environment.
- ///
- /// This isn't necessarily identical to the graph that's passed in to the
- /// environment. It may expose fewer packages if some packages' assets don't
- /// need to be loaded, and it may expose some [CachedPackage]s.
- final PackageGraph graph;
-
- /// The mode to run the transformers in.
- final BarbackMode mode;
-
- /// The [Transformer]s that should be appended by default to the root
- /// package's transformer cascade. Will be empty if there are none.
- final _builtInTransformers = <Transformer>[];
-
- /// How source files should be watched.
- final WatcherType _watcherType;
-
- /// The hostname that servers are bound to.
- final String _hostname;
-
- /// The starting number for ports that servers will be bound to.
- ///
- /// Servers will be bound to ports starting at this number and then
- /// incrementing from there. However, if this is zero, then ephemeral port
- /// numbers will be selected for each server.
- final int _basePort;
-
- /// The modified source assets that have not been sent to barback yet.
- ///
- /// The build environment can be paused (by calling [pauseUpdates]) and
- /// resumed ([resumeUpdates]). While paused, all source asset updates that
- /// come from watching or adding new directories are not sent to barback.
- /// When resumed, all pending source updates are sent to barback.
- ///
- /// This lets pub serve and pub build create an environment and bind several
- /// servers before barback starts building and producing results
- /// asynchronously.
- ///
- /// If this is `null`, then the environment is "live" and all updates will
- /// go to barback immediately.
- Set<AssetId> _modifiedSources;
-
- AssetEnvironment._(this.graph, this.barback, this.mode, this._watcherType,
- this._hostname, this._basePort);
-
- /// Gets the built-in [Transformer]s that should be added to [package].
- ///
- /// Returns `null` if there are none.
- Iterable<Transformer> getBuiltInTransformers(Package package) {
- // Built-in transformers only apply to the root package.
- if (package.name != rootPackage.name) return null;
-
- // The built-in transformers are for dart2js and forwarding assets around
- // dart2js.
- if (_builtInTransformers.isEmpty) return null;
-
- return _builtInTransformers;
- }
-
- /// Starts up the admin server on an appropriate port and returns it.
- ///
- /// This may only be called once on the build environment.
- Future<AdminServer> startAdminServer([int port]) {
- // Can only start once.
- assert(_adminServer == null);
-
- // The admin server is bound to one before the base port by default, unless
- // it's ephemeral in which case the admin port is too.
- if (port == null) port = _basePort == 0 ? 0 : _basePort - 1;
-
- return AdminServer.bind(this, _hostname, port).then((server) => _adminServer =
- server);
- }
-
- /// Binds a new port to serve assets from within [rootDirectory] in the
- /// entrypoint package.
- ///
- /// Adds and watches the sources within that directory. Returns a [Future]
- /// that completes to the bound server.
- ///
- /// If [rootDirectory] is already being served, returns that existing server.
- Future<BarbackServer> serveDirectory(String rootDirectory) {
- // See if there is already a server bound to the directory.
- var directory = _directories[rootDirectory];
- if (directory != null) {
- return directory.server.then((server) {
- log.fine('Already serving $rootDirectory on ${server.url}.');
- return server;
- });
- }
-
- // See if the new directory overlaps any existing servers.
- var overlapping = _directories.keys.where(
- (directory) =>
- path.isWithin(directory, rootDirectory) ||
- path.isWithin(rootDirectory, directory)).toList();
-
- if (overlapping.isNotEmpty) {
- return new Future.error(
- new OverlappingSourceDirectoryException(overlapping));
- }
-
- var port = _basePort;
-
- // If not using an ephemeral port, find the lowest-numbered available one.
- if (port != 0) {
- var boundPorts =
- _directories.values.map((directory) => directory.port).toSet();
- while (boundPorts.contains(port)) {
- port++;
- }
- }
-
- var sourceDirectory =
- new SourceDirectory(this, rootDirectory, _hostname, port);
- _directories[rootDirectory] = sourceDirectory;
-
- return _provideDirectorySources(
- rootPackage,
- rootDirectory).then((subscription) {
- sourceDirectory.watchSubscription = subscription;
- return sourceDirectory.serve();
- });
- }
-
- /// Binds a new port to serve assets from within the "bin" directory of
- /// [package].
- ///
- /// Adds the sources within that directory and then binds a server to it.
- /// Unlike [serveDirectory], this works with packages that are not the
- /// entrypoint.
- ///
- /// Returns a [Future] that completes to the bound server.
- Future<BarbackServer> servePackageBinDirectory(String package) {
- return _provideDirectorySources(
- graph.packages[package],
- "bin").then(
- (_) =>
- BarbackServer.bind(this, _hostname, 0, package: package, rootDirectory: "bin"));
- }
-
- /// Precompiles all of [packageName]'s executables to snapshots in
- /// [directory].
- ///
- /// If [executableIds] is passed, only those executables are precompiled.
- ///
- /// Returns a map from executable name to path for the snapshots that were
- /// successfully precompiled.
- Future<Map<String, String>> precompileExecutables(String packageName,
- String directory, {Iterable<AssetId> executableIds}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- log.fine("Executables for ${packageName}: ${executableIds}");
- join1() {
- var package = graph.packages[packageName];
- new Future.value(servePackageBinDirectory(packageName)).then((x0) {
- try {
- var server = x0;
- join2() {
- completer0.complete();
- }
- finally0(cont0) {
- server.close();
- cont0();
- }
- catch0(e1, s1) {
- finally0(() => completer0.completeError(e1, s1));
- }
- try {
- var precompiled = {};
- new Future.value(waitAndPrintErrors(executableIds.map(((id) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var basename = path.url.basename(id.path);
- var snapshotPath =
- path.join(directory, "${basename}.snapshot");
- new Future.value(
- runProcess(
- Platform.executable,
- [
- '--snapshot=${snapshotPath}',
- server.url.resolve(basename).toString()])).then((x0) {
- try {
- var result = x0;
- join0() {
- completer0.complete();
- }
- if (result.success) {
- log.message(
- "Precompiled ${_formatExecutable(id)}.");
- precompiled[path.withoutExtension(basename)] =
- snapshotPath;
- join0();
- } else {
- throw new ApplicationException(
- log.yellow("Failed to precompile ${_formatExecutable(id)}:\n") +
- result.stderr.join('\n'));
- join0();
- }
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x1) {
- try {
- x1;
- final v0 = precompiled;
- finally0(() {
- completer0.complete(v0);
- });
- } catch (e2, s2) {
- catch0(e2, s2);
- }
- }, onError: catch0);
- } catch (e3, s3) {
- catch0(e3, s3);
- }
- } catch (e4, s4) {
- completer0.completeError(e4, s4);
- }
- }, onError: completer0.completeError);
- }
- if (executableIds.isEmpty) {
- completer0.complete([]);
- } else {
- join1();
- }
- }
- if (executableIds == null) {
- executableIds = graph.packages[packageName].executableIds;
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Returns the executable name for [id].
- ///
- /// [id] is assumed to be an executable in a bin directory. The return value
- /// is intended for log output and may contain formatting.
- String _formatExecutable(AssetId id) =>
- log.bold("${id.package}:${path.basenameWithoutExtension(id.path)}");
-
- /// Stops the server bound to [rootDirectory].
- ///
- /// Also removes any source files within that directory from barback. Returns
- /// the URL of the unbound server, of `null` if [rootDirectory] was not
- /// bound to a server.
- Future<Uri> unserveDirectory(String rootDirectory) {
- log.fine("Unserving $rootDirectory.");
- var directory = _directories.remove(rootDirectory);
- if (directory == null) return new Future.value();
-
- return directory.server.then((server) {
- var url = server.url;
- return directory.close().then((_) {
- _removeDirectorySources(rootDirectory);
- return url;
- });
- });
- }
-
- /// Gets the source directory that contains [assetPath] within the entrypoint
- /// package.
- ///
- /// If [assetPath] is not contained within a source directory, this throws
- /// an exception.
- String getSourceDirectoryContaining(String assetPath) =>
- _directories.values.firstWhere(
- (dir) => path.isWithin(dir.directory, assetPath)).directory;
-
- /// Return all URLs serving [assetPath] in this environment.
- Future<List<Uri>> getUrlsForAssetPath(String assetPath) {
- // Check the three (mutually-exclusive) places the path could be pointing.
- return _lookUpPathInServerRoot(assetPath).then((urls) {
- if (urls.isNotEmpty) return urls;
- return _lookUpPathInPackagesDirectory(assetPath);
- }).then((urls) {
- if (urls.isNotEmpty) return urls;
- return _lookUpPathInDependency(assetPath);
- });
- }
-
- /// Look up [assetPath] in the root directories of servers running in the
- /// entrypoint package.
- Future<List<Uri>> _lookUpPathInServerRoot(String assetPath) {
- // Find all of the servers whose root directories contain the asset and
- // generate appropriate URLs for each.
- return Future.wait(
- _directories.values.where(
- (dir) => path.isWithin(dir.directory, assetPath)).map((dir) {
- var relativePath = path.relative(assetPath, from: dir.directory);
- return dir.server.then(
- (server) => server.url.resolveUri(path.toUri(relativePath)));
- }));
- }
-
- /// Look up [assetPath] in the "packages" directory in the entrypoint package.
- Future<List<Uri>> _lookUpPathInPackagesDirectory(String assetPath) {
- var components = path.split(path.relative(assetPath));
- if (components.first != "packages") return new Future.value([]);
- if (!graph.packages.containsKey(components[1])) return new Future.value([]);
- return Future.wait(_directories.values.map((dir) {
- return dir.server.then(
- (server) => server.url.resolveUri(path.toUri(assetPath)));
- }));
- }
-
- /// Look up [assetPath] in the "lib" or "asset" directory of a dependency
- /// package.
- Future<List<Uri>> _lookUpPathInDependency(String assetPath) {
- for (var packageName in graph.packages.keys) {
- var package = graph.packages[packageName];
- var libDir = package.path('lib');
- var assetDir = package.path('asset');
-
- var uri;
- if (path.isWithin(libDir, assetPath)) {
- uri = path.toUri(
- path.join('packages', package.name, path.relative(assetPath, from: libDir)));
- } else if (path.isWithin(assetDir, assetPath)) {
- uri = path.toUri(
- path.join('assets', package.name, path.relative(assetPath, from: assetDir)));
- } else {
- continue;
- }
-
- return Future.wait(_directories.values.map((dir) {
- return dir.server.then((server) => server.url.resolveUri(uri));
- }));
- }
-
- return new Future.value([]);
- }
-
- /// Given a URL to an asset served by this environment, returns the ID of the
- /// asset that would be accessed by that URL.
- ///
- /// If no server can serve [url], completes to `null`.
- Future<AssetId> getAssetIdForUrl(Uri url) {
- return Future.wait(
- _directories.values.map((dir) => dir.server)).then((servers) {
- var server = servers.firstWhere((server) {
- if (server.port != url.port) return false;
- return isLoopback(server.address.host) == isLoopback(url.host) ||
- server.address.host == url.host;
- }, orElse: () => null);
- if (server == null) return null;
- return server.urlToId(url);
- });
- }
-
- /// Determines if [sourcePath] is contained within any of the directories in
- /// the root package that are visible to this build environment.
- bool containsPath(String sourcePath) {
- var directories = ["lib"];
- directories.addAll(_directories.keys);
- return directories.any((dir) => path.isWithin(dir, sourcePath));
- }
-
- /// Pauses sending source asset updates to barback.
- void pauseUpdates() {
- // Cannot pause while already paused.
- assert(_modifiedSources == null);
-
- _modifiedSources = new Set<AssetId>();
- }
-
- /// Sends any pending source updates to barback and begins the asynchronous
- /// build process.
- void resumeUpdates() {
- // Cannot resume while not paused.
- assert(_modifiedSources != null);
-
- barback.updateSources(_modifiedSources);
- _modifiedSources = null;
- }
-
- /// Loads the assets and transformers for this environment.
- ///
- /// This transforms and serves all library and asset files in all packages in
- /// the environment's package graph. It loads any transformer plugins defined
- /// in packages in [graph] and re-runs them as necessary when any input files
- /// change.
- ///
- /// If [useDart2JS] is `true`, then the [Dart2JSTransformer] is implicitly
- /// added to end of the root package's transformer phases.
- ///
- /// If [entrypoints] is passed, only transformers necessary to run those
- /// entrypoints will be loaded.
- ///
- /// Returns a [Future] that completes once all inputs and transformers are
- /// loaded.
- Future _load({Iterable<AssetId> entrypoints, bool useDart2JS}) {
- return log.progress("Initializing barback", () {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var containsDart2JS =
- graph.entrypoint.root.pubspec.transformers.any(((transformers) {
- return transformers.any(
- (config) => config.id.package == '\$dart2js');
- }));
- join0() {
- new Future.value(BarbackServer.bind(this, _hostname, 0)).then((x0) {
- try {
- var transformerServer = x0;
- var errorStream = barback.errors.map(((error) {
- if (error is! AssetLoadException) throw error;
- log.error(log.red(error.message));
- log.fine(error.stackTrace.terse);
- }));
- new Future.value(_withStreamErrors((() {
- return log.progress("Loading source assets", _provideSources);
- }), [errorStream, barback.results])).then((x1) {
- try {
- x1;
- log.fine("Provided sources.");
- errorStream = barback.errors.map(((error) {
- if (error is! TransformerException) throw error;
- var message = error.error.toString();
- if (error.stackTrace != null) {
- message += "\n" + error.stackTrace.terse.toString();
- }
- _log(
- new LogEntry(
- error.transform,
- error.transform.primaryId,
- LogLevel.ERROR,
- message,
- null));
- }));
- new Future.value(_withStreamErrors((() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- completer0.complete(
- log.progress("Loading transformers", (() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(
- loadAllTransformers(
- this,
- transformerServer,
- entrypoints: entrypoints)).then((x0) {
- try {
- x0;
- transformerServer.close();
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }), fine: true));
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }),
- [errorStream, barback.results, transformerServer.results])).then((x2) {
- try {
- x2;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } catch (e2, s2) {
- completer0.completeError(e2, s2);
- }
- }, onError: completer0.completeError);
- }
- if (!containsDart2JS && useDart2JS) {
- _builtInTransformers.addAll(
- [new Dart2JSTransformer(this, mode), new DartForwardingTransformer(mode)]);
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }, fine: true);
- }
-
- /// Provides the public source assets in the environment to barback.
- ///
- /// If [watcherType] is not [WatcherType.NONE], enables watching on them.
- Future _provideSources() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(Future.wait(graph.packages.values.map(((package) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- new Future.value(
- _provideDirectorySources(package, "lib")).then((x0) {
- try {
- x0;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (graph.isPackageStatic(package.name)) {
- completer0.complete(null);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x0) {
- try {
- x0;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Provides all of the source assets within [dir] in [package] to barback.
- ///
- /// If [watcherType] is not [WatcherType.NONE], enables watching on them.
- /// Returns the subscription to the watcher, or `null` if none was created.
- Future<StreamSubscription<WatchEvent>>
- _provideDirectorySources(Package package, String dir) {
- log.fine("Providing sources for ${package.name}|$dir.");
- // TODO(rnystrom): Handle overlapping directories. If two served
- // directories overlap like so:
- //
- // $ pub serve example example/subdir
- //
- // Then the sources of the subdirectory will be updated and watched twice.
- // See: #17454
- if (_watcherType == WatcherType.NONE) {
- _updateDirectorySources(package, dir);
- return new Future.value();
- }
-
- // Watch the directory before listing is so we don't miss files that
- // are added between the initial list and registering the watcher.
- return _watchDirectorySources(package, dir).then((_) {
- _updateDirectorySources(package, dir);
- });
- }
-
- /// Updates barback with all of the files in [dir] inside [package].
- void _updateDirectorySources(Package package, String dir) {
- var ids = _listDirectorySources(package, dir);
- if (_modifiedSources == null) {
- barback.updateSources(ids);
- } else {
- _modifiedSources.addAll(ids);
- }
- }
-
- /// Removes all of the files in [dir] in the root package from barback.
- void _removeDirectorySources(String dir) {
- var ids = _listDirectorySources(rootPackage, dir);
- if (_modifiedSources == null) {
- barback.removeSources(ids);
- } else {
- _modifiedSources.removeAll(ids);
- }
- }
-
- /// Lists all of the source assets in [dir] inside [package].
- ///
- /// For large packages, listing the contents is a performance bottleneck, so
- /// this is optimized for our needs in here instead of using the more general
- /// but slower [listDir].
- Iterable<AssetId> _listDirectorySources(Package package, String dir) {
- // This is used in some performance-sensitive paths and can list many, many
- // files. As such, it leans more havily towards optimization as opposed to
- // readability than most code in pub. In particular, it avoids using the
- // path package, since re-parsing a path is very expensive relative to
- // string operations.
- return package.listFiles(beneath: dir).map((file) {
- // From profiling, path.relative here is just as fast as a raw substring
- // and is correct in the case where package.dir has a trailing slash.
- var relative = package.relative(file);
-
- if (Platform.operatingSystem == 'windows') {
- relative = relative.replaceAll("\\", "/");
- }
-
- var uri = new Uri(pathSegments: relative.split("/"));
- return new AssetId(package.name, uri.toString());
- });
- }
-
- /// Adds a file watcher for [dir] within [package], if the directory exists
- /// and the package needs watching.
- Future<StreamSubscription<WatchEvent>> _watchDirectorySources(Package package,
- String dir) {
- // If this package comes from a cached source, its contents won't change so
- // we don't need to monitor it. `packageId` will be null for the
- // application package, since that's not locked.
- var packageId = graph.lockFile.packages[package.name];
- if (packageId != null &&
- graph.entrypoint.cache.sources[packageId.source] is CachedSource) {
- return new Future.value();
- }
-
- var subdirectory = package.path(dir);
- if (!dirExists(subdirectory)) return new Future.value();
-
- // TODO(nweiz): close this watcher when [barback] is closed.
- var watcher = _watcherType.create(subdirectory);
- var subscription = watcher.events.listen((event) {
- // Don't watch files symlinked into these directories.
- // TODO(rnystrom): If pub gets rid of symlinks, remove this.
- var parts = path.split(event.path);
- if (parts.contains("packages")) return;
-
- // Skip files that were (most likely) compiled from nearby ".dart"
- // files. These are created by the Editor's "Run as JavaScript"
- // command and are written directly into the package's directory.
- // When pub's dart2js transformer then tries to create the same file
- // name, we get a build error. To avoid that, just don't consider
- // that file to be a source.
- // TODO(rnystrom): Remove these when the Editor no longer generates
- // .js files and users have had enough time that they no longer have
- // these files laying around. See #15859.
- if (event.path.endsWith(".dart.js")) return;
- if (event.path.endsWith(".dart.js.map")) return;
- if (event.path.endsWith(".dart.precompiled.js")) return;
-
- var idPath = package.relative(event.path);
- var id = new AssetId(package.name, path.toUri(idPath).toString());
- if (event.type == ChangeType.REMOVE) {
- if (_modifiedSources != null) {
- _modifiedSources.remove(id);
- } else {
- barback.removeSources([id]);
- }
- } else if (_modifiedSources != null) {
- _modifiedSources.add(id);
- } else {
- barback.updateSources([id]);
- }
- });
-
- return watcher.ready.then((_) => subscription);
- }
-
- /// Returns the result of [futureCallback] unless any stream in [streams]
- /// emits an error before it's done.
- ///
- /// If a stream does emit an error, that error is thrown instead.
- /// [futureCallback] is a callback rather than a plain future to ensure that
- /// [streams] are listened to before any code that might cause an error starts
- /// running.
- Future _withStreamErrors(Future futureCallback(), List<Stream> streams) {
- var completer = new Completer.sync();
- var subscriptions = streams.map(
- (stream) => stream.listen((_) {}, onError: completer.completeError)).toList();
-
- new Future.sync(futureCallback).then((_) {
- if (!completer.isCompleted) completer.complete();
- }).catchError((error, stackTrace) {
- if (!completer.isCompleted) completer.completeError(error, stackTrace);
- });
-
- return completer.future.whenComplete(() {
- for (var subscription in subscriptions) {
- subscription.cancel();
- }
- });
- }
-}
-
-/// Log [entry] using Pub's logging infrastructure.
-///
-/// Since both [LogEntry] objects and the message itself often redundantly
-/// show the same context like the file where an error occurred, this tries
-/// to avoid showing redundant data in the entry.
-void _log(LogEntry entry) {
- messageMentions(text) =>
- entry.message.toLowerCase().contains(text.toLowerCase());
-
- messageMentionsAsset(id) =>
- messageMentions(id.toString()) ||
- messageMentions(path.fromUri(entry.assetId.path));
-
- var prefixParts = [];
-
- // Show the level (unless the message mentions it).
- if (!messageMentions(entry.level.name)) {
- prefixParts.add("${entry.level} from");
- }
-
- // Show the transformer.
- prefixParts.add(entry.transform.transformer);
-
- // Mention the primary input of the transform unless the message seems to.
- if (!messageMentionsAsset(entry.transform.primaryId)) {
- prefixParts.add("on ${entry.transform.primaryId}");
- }
-
- // If the relevant asset isn't the primary input, mention it unless the
- // message already does.
- if (entry.assetId != entry.transform.primaryId &&
- !messageMentionsAsset(entry.assetId)) {
- prefixParts.add("with input ${entry.assetId}");
- }
-
- var prefix = "[${prefixParts.join(' ')}]:";
- var message = entry.message;
- if (entry.span != null) {
- message = entry.span.message(entry.message);
- }
-
- switch (entry.level) {
- case LogLevel.ERROR:
- log.error("${log.red(prefix)}\n$message");
- break;
-
- case LogLevel.WARNING:
- log.warning("${log.yellow(prefix)}\n$message");
- break;
-
- case LogLevel.INFO:
- log.message("${log.cyan(prefix)}\n$message");
- break;
-
- case LogLevel.FINE:
- log.fine("${log.gray(prefix)}\n$message");
- break;
- }
-}
-
-/// Exception thrown when trying to serve a new directory that overlaps one or
-/// more directories already being served.
-class OverlappingSourceDirectoryException implements Exception {
- /// The relative paths of the directories that overlap the one that could not
- /// be served.
- final List<String> overlappingDirectories;
-
- OverlappingSourceDirectoryException(this.overlappingDirectories);
-}
-
-/// An enum describing different modes of constructing a [DirectoryWatcher].
-abstract class WatcherType {
- /// A watcher that automatically chooses its type based on the operating
- /// system.
- static const AUTO = const _AutoWatcherType();
-
- /// A watcher that always polls the filesystem for changes.
- static const POLLING = const _PollingWatcherType();
-
- /// No directory watcher at all.
- static const NONE = const _NoneWatcherType();
-
- /// Creates a new DirectoryWatcher.
- DirectoryWatcher create(String directory);
-
- String toString();
-}
-
-class _AutoWatcherType implements WatcherType {
- const _AutoWatcherType();
-
- DirectoryWatcher create(String directory) => new DirectoryWatcher(directory);
-
- String toString() => "auto";
-}
-
-class _PollingWatcherType implements WatcherType {
- const _PollingWatcherType();
-
- DirectoryWatcher create(String directory) =>
- new PollingDirectoryWatcher(directory);
-
- String toString() => "polling";
-}
-
-class _NoneWatcherType implements WatcherType {
- const _NoneWatcherType();
-
- DirectoryWatcher create(String directory) => null;
-
- String toString() => "none";
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/barback_server.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/barback_server.dart
deleted file mode 100644
index 24658e2..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/barback_server.dart
+++ /dev/null
@@ -1,211 +0,0 @@
-// Copyright (c) 2013, 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 pub.barback.server;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:barback/barback.dart';
-import 'package:mime/mime.dart';
-import 'package:path/path.dart' as path;
-import 'package:shelf/shelf.dart' as shelf;
-import 'package:stack_trace/stack_trace.dart';
-
-import '../barback.dart';
-import '../io.dart';
-import '../log.dart' as log;
-import '../utils.dart';
-import 'base_server.dart';
-import 'asset_environment.dart';
-
-/// Callback for determining if an asset with [id] should be served or not.
-typedef bool AllowAsset(AssetId id);
-
-/// A server that serves assets transformed by barback.
-class BarbackServer extends BaseServer<BarbackServerResult> {
- /// The package whose assets are being served.
- final String package;
-
- /// The directory in the root which will serve as the root of this server as
- /// a native platform path.
- ///
- /// This may be `null` in which case no files in the root package can be
- /// served and only assets in "lib" directories are available.
- final String rootDirectory;
-
- /// Optional callback to determine if an asset should be served.
- ///
- /// This can be set to allow outside code to filter out assets. Pub serve
- /// uses this after plug-ins are loaded to avoid serving ".dart" files in
- /// release mode.
- ///
- /// If this is `null`, all assets may be served.
- AllowAsset allowAsset;
-
- /// Creates a new server and binds it to [port] of [host].
- ///
- /// This server serves assets from [barback], and uses [rootDirectory]
- /// (which is relative to the root directory of [package]) as the root
- /// directory. If [rootDirectory] is omitted, the bound server can only be
- /// used to serve assets from packages' lib directories (i.e. "packages/..."
- /// URLs). If [package] is omitted, it defaults to the entrypoint package.
- static Future<BarbackServer> bind(AssetEnvironment environment, String host,
- int port, {String package, String rootDirectory}) {
- if (package == null) package = environment.rootPackage.name;
- return bindServer(host, port).then((server) {
- if (rootDirectory == null) {
- log.fine('Serving packages on $host:$port.');
- } else {
- log.fine('Bound "$rootDirectory" to $host:$port.');
- }
- return new BarbackServer._(environment, server, package, rootDirectory);
- });
- }
-
- BarbackServer._(AssetEnvironment environment, HttpServer server, this.package,
- this.rootDirectory)
- : super(environment, server);
-
- /// Converts a [url] served by this server into an [AssetId] that can be
- /// requested from barback.
- AssetId urlToId(Uri url) {
- // See if it's a URL to a public directory in a dependency.
- var id = packagesUrlToId(url);
- if (id != null) return id;
-
- if (rootDirectory == null) {
- throw new FormatException(
- "This server cannot serve out of the root directory. Got $url.");
- }
-
- // Otherwise, it's a path in current package's [rootDirectory].
- var parts = path.url.split(url.path);
-
- // Strip the leading "/" from the URL.
- if (parts.isNotEmpty && parts.first == "/") parts = parts.skip(1);
-
- var relativePath = path.url.join(rootDirectory, path.url.joinAll(parts));
- return new AssetId(package, relativePath);
- }
-
- /// Handles an HTTP request.
- handleRequest(shelf.Request request) {
- if (request.method != "GET" && request.method != "HEAD") {
- return methodNotAllowed(request);
- }
-
- var id;
- try {
- id = urlToId(request.url);
- } on FormatException catch (ex) {
- // If we got here, we had a path like "/packages" which is a special
- // directory, but not a valid path since it lacks a following package
- // name.
- return notFound(request, error: ex.message);
- }
-
- // See if the asset should be blocked.
- if (allowAsset != null && !allowAsset(id)) {
- return notFound(
- request,
- error: "Asset $id is not available in this configuration.",
- asset: id);
- }
-
- return environment.barback.getAssetById(id).then((result) {
- return result;
- }).then((asset) => _serveAsset(request, asset)).catchError((error, trace) {
- if (error is! AssetNotFoundException) throw error;
- return environment.barback.getAssetById(
- id.addExtension("/index.html")).then((asset) {
- if (request.url.path.endsWith('/')) return _serveAsset(request, asset);
-
- // We only want to serve index.html if the URL explicitly ends in a
- // slash. For other URLs, we redirect to one with the slash added to
- // implicitly support that too. This follows Apache's behavior.
- logRequest(request, "302 Redirect to ${request.url}/");
- return new shelf.Response.found('${request.url}/');
- }).catchError((newError, newTrace) {
- // If we find neither the original file or the index, we should report
- // the error about the original to the user.
- throw newError is AssetNotFoundException ? error : newError;
- });
- }).catchError((error, trace) {
- if (error is! AssetNotFoundException) {
- trace = new Chain.forTrace(trace);
- logRequest(request, "$error\n$trace");
-
- addError(error, trace);
- close();
- return new shelf.Response.internalServerError();
- }
-
- addResult(new BarbackServerResult._failure(request.url, id, error));
- return notFound(request, asset: id);
- }).then((response) {
- // Allow requests of any origin to access "pub serve". This is useful for
- // running "pub serve" in parallel with another development server. Since
- // "pub serve" is only used as a development server and doesn't require
- // any sort of credentials anyway, this is secure.
- return response.change(headers: const {
- "Access-Control-Allow-Origin": "*"
- });
- });
- }
-
- /// Returns the body of [asset] as a response to [request].
- Future<shelf.Response> _serveAsset(shelf.Request request, Asset asset) {
- return validateStream(asset.read()).then((stream) {
- addResult(new BarbackServerResult._success(request.url, asset.id));
- var headers = {};
- var mimeType = lookupMimeType(asset.id.path);
- if (mimeType != null) headers['Content-Type'] = mimeType;
- return new shelf.Response.ok(stream, headers: headers);
- }).catchError((error, trace) {
- addResult(new BarbackServerResult._failure(request.url, asset.id, error));
-
- // If we couldn't read the asset, handle the error gracefully.
- if (error is FileSystemException) {
- // Assume this means the asset was a file-backed source asset
- // and we couldn't read it, so treat it like a missing asset.
- return notFound(request, error: error.toString(), asset: asset.id);
- }
-
- trace = new Chain.forTrace(trace);
- logRequest(request, "$error\n$trace");
-
- // Otherwise, it's some internal error.
- return new shelf.Response.internalServerError(body: error.toString());
- });
- }
-}
-
-/// The result of the server handling a URL.
-///
-/// Only requests for which an asset was requested from barback will emit a
-/// result. Malformed requests will be handled internally.
-class BarbackServerResult {
- /// The requested url.
- final Uri url;
-
- /// The id that [url] identifies.
- final AssetId id;
-
- /// The error thrown by barback.
- ///
- /// If the request was served successfully, this will be null.
- final error;
-
- /// Whether the request was served successfully.
- bool get isSuccess => error == null;
-
- /// Whether the request was served unsuccessfully.
- bool get isFailure => !isSuccess;
-
- BarbackServerResult._success(this.url, this.id)
- : error = null;
-
- BarbackServerResult._failure(this.url, this.id, this.error);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/base_server.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/base_server.dart
deleted file mode 100644
index e95c5d3..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/base_server.dart
+++ /dev/null
@@ -1,129 +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.
-
-library pub.barback.base_server;
-
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:barback/barback.dart';
-import 'package:shelf/shelf.dart' as shelf;
-import 'package:shelf/shelf_io.dart' as shelf_io;
-
-import '../log.dart' as log;
-import '../utils.dart';
-import 'asset_environment.dart';
-
-/// Base class for a pub-controlled server.
-abstract class BaseServer<T> {
- /// The [BuildEnvironment] being served.
- final AssetEnvironment environment;
-
- /// The underlying HTTP server.
- final HttpServer _server;
-
- /// The server's port.
- int get port => _server.port;
-
- /// The servers's address.
- InternetAddress get address => _server.address;
-
- /// The server's base URL.
- Uri get url => baseUrlForAddress(_server.address, port);
-
- /// The results of requests handled by the server.
- ///
- /// These can be used to provide visual feedback for the server's processing.
- /// This stream is also used to emit any programmatic errors that occur in the
- /// server.
- Stream<T> get results => _resultsController.stream;
- final _resultsController = new StreamController<T>.broadcast();
-
- BaseServer(this.environment, this._server) {
- shelf_io.serveRequests(
- _server,
- const shelf.Pipeline().addMiddleware(
- shelf.createMiddleware(errorHandler: _handleError)).addHandler(handleRequest));
- }
-
- /// Closes this server.
- Future close() {
- return Future.wait([_server.close(), _resultsController.close()]);
- }
-
- /// Handles an HTTP request.
- handleRequest(shelf.Request request);
-
- /// Returns a 405 response to [request].
- shelf.Response methodNotAllowed(shelf.Request request) {
- logRequest(request, "405 Method Not Allowed");
- return new shelf.Response(
- 405,
- body: "The ${request.method} method is not allowed for ${request.url}.",
- headers: {
- 'Allow': 'GET, HEAD'
- });
- }
-
- /// Returns a 404 response to [request].
- ///
- /// If [asset] is given, it is the ID of the asset that couldn't be found.
- shelf.Response notFound(shelf.Request request, {String error,
- AssetId asset}) {
- logRequest(request, "Not Found");
-
- // TODO(rnystrom): Apply some styling to make it visually clear that this
- // error is coming from pub serve itself.
- var body = new StringBuffer();
- body.writeln("""
- <!DOCTYPE html>
- <head>
- <title>404 Not Found</title>
- </head>
- <body>
- <h1>404 Not Found</h1>""");
-
- if (asset != null) {
- body.writeln(
- "<p>Could not find asset "
- "<code>${HTML_ESCAPE.convert(asset.path)}</code> in package "
- "<code>${HTML_ESCAPE.convert(asset.package)}</code>.</p>");
- }
-
- if (error != null) {
- body.writeln("<p>Error: ${HTML_ESCAPE.convert(error)}</p>");
- }
-
- body.writeln("""
- </body>""");
-
- // Force a UTF-8 encoding so that error messages in non-English locales are
- // sent correctly.
- return new shelf.Response.notFound(body.toString(), headers: {
- 'Content-Type': 'text/html; charset=utf-8'
- });
- }
-
- /// Log [message] at [log.Level.FINE] with metadata about [request].
- void logRequest(shelf.Request request, String message) =>
- log.fine("$this ${request.method} ${request.url}\n$message");
-
- /// Adds [result] to the server's [results] stream.
- void addResult(T result) {
- _resultsController.add(result);
- }
-
- /// Adds [error] as an error to the server's [results] stream.
- void addError(error, [stackTrace]) {
- _resultsController.addError(error, stackTrace);
- }
-
- /// Handles an error thrown by [handleRequest].
- _handleError(error, StackTrace stackTrace) {
- _resultsController.addError(error, stackTrace);
- close();
- return new shelf.Response.internalServerError();
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/cycle_exception.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/cycle_exception.dart
deleted file mode 100644
index 8fdd047..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/cycle_exception.dart
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub.barback.cycle_exception;
-
-import '../exceptions.dart';
-
-/// An exception thrown when a transformer dependency cycle is detected.
-///
-/// A cycle exception is usually produced within a deeply-nested series of
-/// calls. The API is designed to make it easy for each of these calls to add to
-/// the message so that the full reasoning for the cycle is made visible to the
-/// user.
-///
-/// Each call's individual message is called a "step". A [CycleException] is
-/// represented internally as a linked list of steps.
-class CycleException implements ApplicationException {
- /// The step for this exception.
- final String _step;
-
- /// The next exception in the linked list.
- ///
- /// [_next]'s steps come after [_step].
- final CycleException _next;
-
- /// A list of all steps in the cycle.
- List<String> get steps {
- if (_step == null) return [];
-
- var exception = this;
- var steps = [];
- while (exception != null) {
- steps.add(exception._step);
- exception = exception._next;
- }
- return steps;
- }
-
- String get message {
- var steps = this.steps;
- if (steps.isEmpty) return "Transformer cycle detected.";
- return "Transformer cycle detected:\n" +
- steps.map((step) => " $step").join("\n");
- }
-
- /// Creates a new [CycleException] with zero or one steps.
- CycleException([this._step])
- : _next = null;
-
- CycleException._(this._step, this._next);
-
- /// Returns a copy of [this] with [step] added to the beginning of [steps].
- CycleException prependStep(String step) {
- if (_step == null) return new CycleException(step);
- return new CycleException._(step, this);
- }
-
- String toString() => message;
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/dart2js_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/dart2js_transformer.dart
deleted file mode 100644
index b6362eb..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/dart2js_transformer.dart
+++ /dev/null
@@ -1,433 +0,0 @@
-// Copyright (c) 2013, 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 pub.dart2js_transformer;
-
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:analyzer/analyzer.dart';
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as path;
-import 'package:pool/pool.dart';
-
-import '../../../../../../../pkg/compiler/lib/compiler.dart' as compiler;
-import '../../../../../../../pkg/compiler/lib/src/dart2js.dart' show AbortLeg;
-import '../../../../../../../pkg/compiler/lib/src/io/source_file.dart';
-import '../barback.dart';
-import '../dart.dart' as dart;
-import '../utils.dart';
-import 'asset_environment.dart';
-
-/// The set of all valid configuration options for this transformer.
-final _validOptions = new Set<String>.from(
- [
- 'commandLineOptions',
- 'checked',
- 'csp',
- 'minify',
- 'verbose',
- 'environment',
- 'preserveUris',
- 'suppressWarnings',
- 'suppressHints',
- 'suppressPackageWarnings',
- 'terse',
- 'sourceMaps']);
-
-/// A [Transformer] that uses dart2js's library API to transform Dart
-/// entrypoints in "web" to JavaScript.
-class Dart2JSTransformer extends Transformer implements LazyTransformer {
- /// We use this to ensure that only one compilation is in progress at a time.
- ///
- /// Dart2js uses lots of memory, so if we try to actually run compiles in
- /// parallel, it takes down the VM. The tracking bug to do something better
- /// is here: https://code.google.com/p/dart/issues/detail?id=14730.
- static final _pool = new Pool(1);
-
- final AssetEnvironment _environment;
- final BarbackSettings _settings;
-
- /// Whether source maps should be generated for the compiled JS.
- bool get _generateSourceMaps =>
- _configBool('sourceMaps', defaultsTo: _settings.mode != BarbackMode.RELEASE);
-
- Dart2JSTransformer.withSettings(this._environment, this._settings) {
- var invalidOptions =
- _settings.configuration.keys.toSet().difference(_validOptions);
- if (invalidOptions.isEmpty) return;
-
- throw new FormatException(
- "Unrecognized dart2js " "${pluralize('option', invalidOptions.length)} "
- "${toSentence(invalidOptions.map((option) => '"$option"'))}.");
- }
-
- Dart2JSTransformer(AssetEnvironment environment, BarbackMode mode)
- : this.withSettings(environment, new BarbackSettings({}, mode));
-
- /// Only ".dart" entrypoint files within a buildable directory are processed.
- bool isPrimary(AssetId id) {
- if (id.extension != ".dart") return false;
-
- // "lib" should only contain libraries. For efficiency's sake, we don't
- // look for entrypoints in there.
- return !id.path.startsWith("lib/");
- }
-
- Future apply(Transform transform) {
- // TODO(nweiz): If/when barback starts reporting what assets were modified,
- // don't re-run the entrypoint detection logic unless the primary input was
- // actually modified. See issue 16817.
- return _isEntrypoint(transform.primaryInput).then((isEntrypoint) {
- if (!isEntrypoint) return null;
-
- // Wait for any ongoing apply to finish first.
- return _pool.withResource(() {
- transform.logger.info("Compiling ${transform.primaryInput.id}...");
- var stopwatch = new Stopwatch()..start();
- return _doCompilation(transform).then((_) {
- stopwatch.stop();
- transform.logger.info(
- "Took ${stopwatch.elapsed} to compile " "${transform.primaryInput.id}.");
- });
- });
- });
- }
-
- void declareOutputs(DeclaringTransform transform) {
- var primaryId = transform.primaryId;
- transform.declareOutput(primaryId.addExtension(".js"));
- if (_generateSourceMaps) {
- transform.declareOutput(primaryId.addExtension(".js.map"));
- }
- }
-
- /// Returns whether or not [asset] might be an entrypoint.
- Future<bool> _isEntrypoint(Asset asset) {
- return asset.readAsString().then((code) {
- try {
- var name = asset.id.path;
- if (asset.id.package != _environment.rootPackage.name) {
- name += " in ${asset.id.package}";
- }
-
- var parsed = parseCompilationUnit(code, name: name);
- return dart.isEntrypoint(parsed);
- } on AnalyzerErrorGroup catch (e) {
- // If we get a parse error, consider the asset primary so we report
- // dart2js's more detailed error message instead.
- return true;
- }
- });
- }
-
- /// Run the dart2js compiler.
- Future _doCompilation(Transform transform) {
- var provider = new _BarbackCompilerProvider(
- _environment,
- transform,
- generateSourceMaps: _generateSourceMaps);
-
- // Create a "path" to the entrypoint script. The entrypoint may not actually
- // be on disk, but this gives dart2js a root to resolve relative paths
- // against.
- var id = transform.primaryInput.id;
-
- var entrypoint = _environment.graph.packages[id.package].path(id.path);
-
- // TODO(rnystrom): Should have more sophisticated error-handling here. Need
- // to report compile errors to the user in an easily visible way. Need to
- // make sure paths in errors are mapped to the original source path so they
- // can understand them.
- return dart.compile(
- entrypoint,
- provider,
- commandLineOptions: _configCommandLineOptions,
- csp: _configBool('csp'),
- checked: _configBool('checked'),
- minify: _configBool(
- 'minify',
- defaultsTo: _settings.mode == BarbackMode.RELEASE),
- verbose: _configBool('verbose'),
- environment: _configEnvironment,
- packageRoot: _environment.rootPackage.path("packages"),
- analyzeAll: _configBool('analyzeAll'),
- preserveUris: _configBool('preserveUris'),
- suppressWarnings: _configBool('suppressWarnings'),
- suppressHints: _configBool('suppressHints'),
- suppressPackageWarnings: _configBool(
- 'suppressPackageWarnings',
- defaultsTo: true),
- terse: _configBool('terse'),
- includeSourceMapUrls: _generateSourceMaps);
- }
-
- /// Parses and returns the "commandLineOptions" configuration option.
- List<String> get _configCommandLineOptions {
- if (!_settings.configuration.containsKey('commandLineOptions')) return null;
-
- var options = _settings.configuration['commandLineOptions'];
- if (options is List && options.every((option) => option is String)) {
- return options;
- }
-
- throw new FormatException(
- 'Invalid value for '
- '\$dart2js.commandLineOptions: ${JSON.encode(options)} (expected list '
- 'of strings).');
- }
-
- /// Parses and returns the "environment" configuration option.
- Map<String, String> get _configEnvironment {
- if (!_settings.configuration.containsKey('environment')) return null;
-
- var environment = _settings.configuration['environment'];
- if (environment is Map &&
- environment.keys.every((key) => key is String) &&
- environment.values.every((key) => key is String)) {
- return environment;
- }
-
- throw new FormatException(
- 'Invalid value for \$dart2js.environment: '
- '${JSON.encode(environment)} (expected map from strings to strings).');
- }
-
- /// Parses and returns a boolean configuration option.
- ///
- /// [defaultsTo] is the default value of the option.
- bool _configBool(String name, {bool defaultsTo: false}) {
- if (!_settings.configuration.containsKey(name)) return defaultsTo;
- var value = _settings.configuration[name];
- if (value is bool) return value;
- throw new FormatException(
- 'Invalid value for \$dart2js.$name: '
- '${JSON.encode(value)} (expected true or false).');
- }
-}
-
-/// Defines an interface for dart2js to communicate with barback and pub.
-///
-/// Note that most of the implementation of diagnostic handling here was
-/// copied from [FormattingDiagnosticHandler] in dart2js. The primary
-/// difference is that it uses barback's logging code and, more importantly, it
-/// handles missing source files more gracefully.
-class _BarbackCompilerProvider implements dart.CompilerProvider {
- Uri get libraryRoot => Uri.parse("${path.toUri(_libraryRootPath)}/");
-
- final AssetEnvironment _environment;
- final Transform _transform;
- String _libraryRootPath;
-
- /// The map of previously loaded files.
- ///
- /// Used to show where an error occurred in a source file.
- final _sourceFiles = new Map<String, SourceFile>();
-
- // TODO(rnystrom): Make these configurable.
- /// Whether or not warnings should be logged.
- var _showWarnings = true;
-
- /// Whether or not hints should be logged.
- var _showHints = true;
-
- /// Whether or not verbose info messages should be logged.
- var _verbose = false;
-
- /// Whether an exception should be thrown on an error to stop compilation.
- var _throwOnError = false;
-
- /// This gets set after a fatal error is reported to quash any subsequent
- /// errors.
- var _isAborting = false;
-
- final bool generateSourceMaps;
-
- compiler.Diagnostic _lastKind = null;
-
- static final int _FATAL =
- compiler.Diagnostic.CRASH.ordinal |
- compiler.Diagnostic.ERROR.ordinal;
- static final int _INFO =
- compiler.Diagnostic.INFO.ordinal |
- compiler.Diagnostic.VERBOSE_INFO.ordinal;
-
- _BarbackCompilerProvider(this._environment, this._transform,
- {this.generateSourceMaps: true}) {
- // Dart2js outputs source maps that reference the Dart SDK sources. For
- // that to work, those sources need to be inside the build environment. We
- // do that by placing them in a special "$sdk" pseudo-package. In order for
- // dart2js to generate the right URLs to point to that package, we give it
- // a library root that corresponds to where that package can be found
- // relative to the public source directory containing that entrypoint.
- //
- // For example, say the package being compiled is "/dev/myapp", the
- // entrypoint is "web/sub/foo/bar.dart", and the source directory is
- // "web/sub". This means the SDK sources will be (conceptually) at:
- //
- // /dev/myapp/web/sub/packages/$sdk/lib/
- //
- // This implies that the asset path for a file in the SDK is:
- //
- // $sdk|lib/lib/...
- //
- // TODO(rnystrom): Fix this if #17751 is fixed.
- var buildDir =
- _environment.getSourceDirectoryContaining(_transform.primaryInput.id.path);
- _libraryRootPath =
- _environment.rootPackage.path(buildDir, "packages", r"$sdk");
- }
-
- /// A [CompilerInputProvider] for dart2js.
- Future<String> provideInput(Uri resourceUri) {
- // We only expect to get absolute "file:" URLs from dart2js.
- assert(resourceUri.isAbsolute);
- assert(resourceUri.scheme == "file");
-
- var sourcePath = path.fromUri(resourceUri);
- return _readResource(resourceUri).then((source) {
- _sourceFiles[resourceUri.toString()] =
- new StringSourceFile(path.relative(sourcePath), source);
- return source;
- });
- }
-
- /// A [CompilerOutputProvider] for dart2js.
- EventSink<String> provideOutput(String name, String extension) {
- // TODO(rnystrom): Do this more cleanly. See: #17403.
- if (!generateSourceMaps && extension.endsWith(".map")) {
- return new NullSink<String>();
- }
-
- // TODO(nweiz): remove this special case when dart2js stops generating these
- // files.
- if (extension.endsWith(".precompiled.js")) return new NullSink<String>();
-
- var primaryId = _transform.primaryInput.id;
-
- // Dart2js uses an empty string for the name of the entrypoint library.
- // Otherwise, it's the name of a deferred library.
- var outPath;
- if (name == "") {
- outPath = _transform.primaryInput.id.path;
- } else {
- var dirname = path.url.dirname(_transform.primaryInput.id.path);
- outPath = path.url.join(dirname, name);
- }
-
- var id = new AssetId(primaryId.package, "$outPath.$extension");
-
- // Make a sink that dart2js can write to.
- var sink = new StreamController<String>();
-
- // dart2js gives us strings, but stream assets expect byte lists.
- var stream = UTF8.encoder.bind(sink.stream);
-
- // And give it to barback as a stream it can read from.
- _transform.addOutput(new Asset.fromStream(id, stream));
-
- return sink;
- }
-
- /// A [DiagnosticHandler] for dart2js, loosely based on
- /// [FormattingDiagnosticHandler].
- void handleDiagnostic(Uri uri, int begin, int end, String message,
- compiler.Diagnostic kind) {
- // TODO(ahe): Remove this when source map is handled differently.
- if (kind.name == "source map") return;
-
- if (_isAborting) return;
- _isAborting = (kind == compiler.Diagnostic.CRASH);
-
- var isInfo = (kind.ordinal & _INFO) != 0;
- if (isInfo && uri == null && kind != compiler.Diagnostic.INFO) {
- if (!_verbose && kind == compiler.Diagnostic.VERBOSE_INFO) return;
- _transform.logger.info(message);
- return;
- }
-
- // [_lastKind] records the previous non-INFO kind we saw.
- // This is used to suppress info about a warning when warnings are
- // suppressed, and similar for hints.
- if (kind != compiler.Diagnostic.INFO) _lastKind = kind;
-
- var logFn;
- if (kind == compiler.Diagnostic.ERROR) {
- logFn = _transform.logger.error;
- } else if (kind == compiler.Diagnostic.WARNING) {
- if (!_showWarnings) return;
- logFn = _transform.logger.warning;
- } else if (kind == compiler.Diagnostic.HINT) {
- if (!_showHints) return;
- logFn = _transform.logger.warning;
- } else if (kind == compiler.Diagnostic.CRASH) {
- logFn = _transform.logger.error;
- } else if (kind == compiler.Diagnostic.INFO) {
- if (_lastKind == compiler.Diagnostic.WARNING && !_showWarnings) return;
- if (_lastKind == compiler.Diagnostic.HINT && !_showHints) return;
- logFn = _transform.logger.info;
- } else {
- throw new Exception('Unknown kind: $kind (${kind.ordinal})');
- }
-
- var fatal = (kind.ordinal & _FATAL) != 0;
- if (uri == null) {
- logFn(message);
- } else {
- SourceFile file = _sourceFiles[uri.toString()];
- if (file == null) {
- // We got a message before loading the file, so just report the message
- // itself.
- logFn('$uri: $message');
- } else {
- logFn(file.getLocationMessage(message, begin, end));
- }
- }
-
- if (fatal && _throwOnError) {
- _isAborting = true;
- throw new AbortLeg(message);
- }
- }
-
- Future<String> _readResource(Uri url) {
- return new Future.sync(() {
- // Find the corresponding asset in barback.
- var id = _sourceUrlToId(url);
- if (id != null) return _transform.readInputAsString(id);
-
- // Don't allow arbitrary file paths that point to things not in packages.
- // Doing so won't work in Dartium.
- throw new Exception(
- "Cannot read $url because it is outside of the build environment.");
- });
- }
-
- AssetId _sourceUrlToId(Uri url) {
- // See if it's a package path.
- var id = packagesUrlToId(url);
- if (id != null) return id;
-
- // See if it's a path to a "public" asset within the root package. All
- // other files in the root package are not visible to transformers, so
- // should be loaded directly from disk.
- var sourcePath = path.fromUri(url);
- if (_environment.containsPath(sourcePath)) {
- var relative =
- path.toUri(_environment.rootPackage.relative(sourcePath)).toString();
-
- return new AssetId(_environment.rootPackage.name, relative);
- }
-
- return null;
- }
-}
-
-/// An [EventSink] that discards all data. Provided to dart2js when we don't
-/// want an actual output.
-class NullSink<T> implements EventSink<T> {
- void add(T event) {}
- void addError(errorEvent, [StackTrace stackTrace]) {}
- void close() {}
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/dart_forwarding_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/dart_forwarding_transformer.dart
deleted file mode 100644
index d112924..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/dart_forwarding_transformer.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2013, 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 pub.dart_forwarding_transformer;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-import '../utils.dart';
-
-/// A single transformer that just forwards any ".dart" file as an output when
-/// not in release mode.
-///
-/// Since the [Dart2JSTransformer] consumes its inputs, this is used in
-/// parallel to make sure the original Dart file is still available for use by
-/// Dartium.
-class DartForwardingTransformer extends Transformer {
- /// The mode that the transformer is running in.
- final BarbackMode _mode;
-
- DartForwardingTransformer(this._mode);
-
- String get allowedExtensions => ".dart";
-
- Future apply(Transform transform) {
- return newFuture(() {
- transform.addOutput(transform.primaryInput);
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/dependency_computer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/dependency_computer.dart
deleted file mode 100644
index f9aff0b..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/dependency_computer.dart
+++ /dev/null
@@ -1,429 +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.
-
-library pub.barback.dependency_computer;
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-
-import '../dart.dart';
-import '../io.dart';
-import '../package.dart';
-import '../package_graph.dart';
-import '../utils.dart';
-import 'cycle_exception.dart';
-import 'transformer_config.dart';
-import 'transformer_id.dart';
-
-/// A class for determining dependencies between transformers and from Dart
-/// libraries onto transformers.
-class DependencyComputer {
- /// The package graph being analyzed.
- final PackageGraph _graph;
-
- /// The names of packages for which [_PackageDependencyComputer]s are
- /// currently loading.
- ///
- /// This is used to detect transformer cycles. If a package's libraries or
- /// transformers are referenced while the transformers that apply to it are
- /// being processed, that indicates an unresolvable cycle.
- final _loadingPackageComputers = new Set<String>();
-
- /// [_PackageDependencyComputer]s that have been loaded.
- final _packageComputers = new Map<String, _PackageDependencyComputer>();
-
- /// A cache of the results of [transformersNeededByPackage].
- final _transformersNeededByPackages = new Map<String, Set<TransformerId>>();
-
- /// The set of all packages that neither use transformers themselves nor
- /// import packages that use transformers.
- ///
- /// This is precomputed before any package computers are loaded.
- final _untransformedPackages = new Set<String>();
-
- DependencyComputer(this._graph) {
- for (var package in ordered(_graph.packages.keys)) {
- if (_graph.transitiveDependencies(
- package).every((dependency) => dependency.pubspec.transformers.isEmpty)) {
- _untransformedPackages.add(package);
- }
- }
-
- ordered(_graph.packages.keys).forEach(_loadPackageComputer);
- }
-
- /// Returns a dependency graph for [transformers], or for all transformers if
- /// [transformers] is `null`.
- ///
- /// This graph is represented by a map whose keys are the vertices and whose
- /// values are sets representing edges from the given vertex. Each vertex is a
- /// [TransformerId]. If there's an edge from `T1` to `T2`, then `T2` must be
- /// loaded before `T1` can be loaded.
- ///
- /// The returned graph is transitively closed. That is, if there's an edge
- /// from `T1` to `T2` and an edge from `T2` to `T3`, there's also an edge from
- /// `T1` to `T2`.
- Map<TransformerId, Set<TransformerId>>
- transformersNeededByTransformers([Iterable<TransformerId> transformers]) {
- var result = {};
-
- if (transformers == null) {
- transformers = ordered(_graph.packages.keys).expand((packageName) {
- var package = _graph.packages[packageName];
- return package.pubspec.transformers.expand((phase) {
- return phase.expand((config) {
- var id = config.id;
- if (id.isBuiltInTransformer) return [];
- if (id.package != _graph.entrypoint.root.name &&
- !config.canTransformPublicFiles) {
- return [];
- }
- return [id];
- });
- });
- });
- }
-
- for (var id in transformers) {
- result[id] = _transformersNeededByTransformer(id);
- }
- return result;
- }
-
- /// Returns the set of all transformers needed to load the library identified
- /// by [id].
- Set<TransformerId> transformersNeededByLibrary(AssetId id) {
- var library = _graph.packages[id.package].path(p.fromUri(id.path));
- _loadPackageComputer(id.package);
- return _packageComputers[id.package].transformersNeededByLibrary(
- library).where((id) => !id.isBuiltInTransformer).toSet();
- }
-
- /// Returns the set of all transformers that need to be loaded before [id] is
- /// loaded.
- Set<TransformerId> _transformersNeededByTransformer(TransformerId id) {
- if (id.isBuiltInTransformer) return new Set();
- _loadPackageComputer(id.package);
- return _packageComputers[id.package]._transformersNeededByTransformer(id);
- }
-
- /// Returns the set of all transformers that need to be loaded before
- /// [packageUri] (a "package:" URI) can be safely imported from an external
- /// package.
- Set<TransformerId> _transformersNeededByPackageUri(Uri packageUri) {
- var components = p.split(p.fromUri(packageUri.path));
- var packageName = components.first;
- if (_untransformedPackages.contains(packageName)) return new Set();
-
- var package = _graph.packages[packageName];
- if (package == null) {
- // TODO(nweiz): include source range information here.
- fail(
- 'A transformer imported unknown package "$packageName" (in ' '"$packageUri").');
- }
-
- var library = package.path('lib', p.joinAll(components.skip(1)));
-
- _loadPackageComputer(packageName);
- return _packageComputers[packageName].transformersNeededByLibrary(library);
- }
-
- /// Returns the set of all transformers that need to be loaded before
- /// everything in [rootPackage] can be used.
- ///
- /// This is conservative in that it returns all transformers that could
- /// theoretically affect [rootPackage]. It only looks at which transformers
- /// packages use and which packages they depend on; it ignores imports
- /// entirely.
- ///
- /// We fall back on this conservative analysis when a transformer
- /// (transitively) imports a transformed library. The result of the
- /// transformation may import any dependency or hit any transformer, so we
- /// have to assume that it will.
- Set<TransformerId> _transformersNeededByPackage(String rootPackage) {
- if (_untransformedPackages.contains(rootPackage)) return new Set();
-
- if (_transformersNeededByPackages.containsKey(rootPackage)) {
- return _transformersNeededByPackages[rootPackage];
- }
-
- var results = new Set();
- var seen = new Set();
-
- traversePackage(packageName) {
- if (seen.contains(packageName)) return;
- seen.add(packageName);
-
- var package = _graph.packages[packageName];
- for (var phase in package.pubspec.transformers) {
- for (var config in phase) {
- var id = config.id;
- if (id.isBuiltInTransformer) continue;
- if (_loadingPackageComputers.contains(id.package)) {
- throw new CycleException("$packageName is transformed by $id");
- }
- results.add(id);
- }
- }
-
- var dependencies = packageName == _graph.entrypoint.root.name ?
- package.immediateDependencies :
- package.dependencies;
- for (var dep in dependencies) {
- try {
- traversePackage(dep.name);
- } on CycleException catch (error) {
- throw error.prependStep("$packageName depends on ${dep.name}");
- }
- }
- }
-
- traversePackage(rootPackage);
- _transformersNeededByPackages[rootPackage] = results;
- return results;
- }
-
-
- /// Ensure that a [_PackageDependencyComputer] for [packageName] is loaded.
- ///
- /// If the computer has already been loaded, this does nothing. If the
- /// computer is in the process of being loaded, this throws a
- /// [CycleException].
- void _loadPackageComputer(String packageName) {
- if (_loadingPackageComputers.contains(packageName)) {
- throw new CycleException();
- }
- if (_packageComputers.containsKey(packageName)) return;
- _loadingPackageComputers.add(packageName);
- _packageComputers[packageName] =
- new _PackageDependencyComputer(this, packageName);
- _loadingPackageComputers.remove(packageName);
- }
-}
-
-/// A helper class for [computeTransformersNeededByTransformers] that keeps
-/// package-specific state and caches over the course of the computation.
-class _PackageDependencyComputer {
- /// The parent [DependencyComputer].
- final DependencyComputer _dependencyComputer;
-
- /// The package whose dependencies [this] is computing.
- final Package _package;
-
- /// The set of transformers that currently apply to [this].
- ///
- /// This is added to phase-by-phase while [this] is being initialized. This is
- /// necessary to model the dependencies of a transformer that's applied to its
- /// own package.
- final _applicableTransformers = new Set<TransformerConfig>();
-
- /// A cache of imports and exports parsed from libraries in this package.
- final _directives = new Map<Uri, Set<Uri>>();
-
- /// The set of libraries for which there are currently active
- /// [transformersNeededByLibrary] calls.
- ///
- /// This is used to guard against infinite loops caused by libraries in
- /// different packages importing one another circularly.
- /// [transformersNeededByLibrary] will return an empty set for any active
- /// libraries.
- final _activeLibraries = new Set<String>();
-
- /// A cache of the results of [_transformersNeededByTransformer].
- final _transformersNeededByTransformers =
- new Map<TransformerId, Set<TransformerId>>();
-
- /// A cache of the results of [_getTransitiveExternalDirectives].
- ///
- /// This is invalidated whenever [_applicableTransformers] changes.
- final _transitiveExternalDirectives = new Map<String, Set<Uri>>();
-
- _PackageDependencyComputer(DependencyComputer dependencyComputer,
- String packageName)
- : _dependencyComputer = dependencyComputer,
- _package = dependencyComputer._graph.packages[packageName] {
- // If [_package] uses its own transformers, there will be fewer transformers
- // running on [_package] while its own transformers are loading than there
- // will be once all its transformers are finished loading. To handle this,
- // we run [_transformersNeededByTransformer] to pre-populate
- // [_transformersNeededByLibraries] while [_applicableTransformers] is
- // smaller.
- for (var phase in _package.pubspec.transformers) {
- for (var config in phase) {
- var id = config.id;
- try {
- if (id.package != _package.name) {
- // Probe [id]'s transformer dependencies to ensure that it doesn't
- // depend on this package. If it does, a CycleError will be thrown.
- _dependencyComputer._transformersNeededByTransformer(id);
- } else {
- // Store the transformers needed specifically with the current set
- // of [_applicableTransformers]. When reporting this transformer's
- // dependencies, [computeTransformersNeededByTransformers] will use
- // this stored set of dependencies rather than the potentially wider
- // set that would be recomputed if [transformersNeededByLibrary]
- // were called anew.
- _transformersNeededByTransformers[id] =
- transformersNeededByLibrary(_package.transformerPath(id));
- }
- } on CycleException catch (error) {
- throw error.prependStep("$packageName is transformed by $id");
- }
- }
-
- // Clear the cached imports and exports because the new transformers may
- // start transforming a library whose directives were previously
- // statically analyzable.
- _transitiveExternalDirectives.clear();
- _applicableTransformers.addAll(phase);
- }
- }
-
- /// Returns the set of all transformers that need to be loaded before [id] is
- /// loaded.
- ///
- /// [id] must refer to a transformer in [_package].
- Set<TransformerId> _transformersNeededByTransformer(TransformerId id) {
- assert(id.package == _package.name);
- if (_transformersNeededByTransformers.containsKey(id)) {
- return _transformersNeededByTransformers[id];
- }
-
- _transformersNeededByTransformers[id] =
- transformersNeededByLibrary(_package.transformerPath(id));
- return _transformersNeededByTransformers[id];
- }
-
- /// Returns the set of all transformers that need to be loaded before
- /// [library] is imported.
- ///
- /// If [library] or anything it imports/exports within this package is
- /// transformed by [_applicableTransformers], this will return a conservative
- /// set of transformers (see also
- /// [DependencyComputer._transformersNeededByPackage]).
- Set<TransformerId> transformersNeededByLibrary(String library) {
- library = p.normalize(library);
- if (_activeLibraries.contains(library)) return new Set();
- _activeLibraries.add(library);
-
- try {
- var externalDirectives = _getTransitiveExternalDirectives(library);
- if (externalDirectives == null) {
- var rootName = _dependencyComputer._graph.entrypoint.root.name;
- var dependencies = _package.name == rootName ?
- _package.immediateDependencies :
- _package.dependencies;
-
- // If anything transitively imported/exported by [library] within this
- // package is modified by a transformer, we don't know what it will
- // load, so we take the conservative approach and say it depends on
- // everything.
- return _applicableTransformers.map(
- (config) => config.id).toSet().union(unionAll(dependencies.map((dep) {
- try {
- return _dependencyComputer._transformersNeededByPackage(dep.name);
- } on CycleException catch (error) {
- throw error.prependStep("${_package.name} depends on ${dep.name}");
- }
- })));
- } else {
- // If nothing's transformed, then we only depend on the transformers
- // used by the external packages' libraries that we import or export.
- return unionAll(externalDirectives.map((uri) {
- try {
- return _dependencyComputer._transformersNeededByPackageUri(uri);
- } on CycleException catch (error) {
- var packageName = p.url.split(uri.path).first;
- throw error.prependStep("${_package.name} depends on $packageName");
- }
- }));
- }
- } finally {
- _activeLibraries.remove(library);
- }
- }
-
- /// Returns the set of all external package libraries transitively imported or
- /// exported by [rootLibrary].
- ///
- /// All of the returned URIs will have the "package:" scheme. None of them
- /// will be URIs for this package.
- ///
- /// If [rootLibrary] transitively imports or exports a library that's modified
- /// by a transformer, this will return `null`.
- Set<Uri> _getTransitiveExternalDirectives(String rootLibrary) {
- rootLibrary = p.normalize(rootLibrary);
- if (_transitiveExternalDirectives.containsKey(rootLibrary)) {
- return _transitiveExternalDirectives[rootLibrary];
- }
-
- var results = new Set();
- var seen = new Set();
-
- traverseLibrary(library) {
- library = p.normalize(library);
- if (seen.contains(library)) return true;
- seen.add(library);
-
- var directives = _getDirectives(library);
- if (directives == null) return false;
-
- for (var uri in directives) {
- var path;
- if (uri.scheme == 'package') {
- var components = p.split(p.fromUri(uri.path));
- if (components.first != _package.name) {
- results.add(uri);
- continue;
- }
-
- path = _package.path('lib', p.joinAll(components.skip(1)));
- } else if (uri.scheme == '' || uri.scheme == 'file') {
- path = p.join(p.dirname(library), p.fromUri(uri));
- } else {
- // Ignore "dart:" URIs and theoretically-possible "http:" URIs.
- continue;
- }
-
- if (!traverseLibrary(path)) return false;
- }
-
- return true;
- }
-
- _transitiveExternalDirectives[rootLibrary] =
- traverseLibrary(rootLibrary) ? results : null;
- return _transitiveExternalDirectives[rootLibrary];
- }
-
- /// Returns the set of all imports or exports in [library].
- ///
- /// If [library] is modified by a transformer, this will return `null`.
- Set<Uri> _getDirectives(String library) {
- var libraryUri = p.toUri(p.normalize(library));
- var relative = p.toUri(_package.relative(library)).path;
- if (_applicableTransformers.any(
- (config) => config.canTransform(relative))) {
- _directives[libraryUri] = null;
- return null;
- }
-
- // Check the cache *after* checking [_applicableTransformers] because
- // [_applicableTransformers] changes over time so the directives may be
- // invalidated.
- if (_directives.containsKey(libraryUri)) return _directives[libraryUri];
-
- // If a nonexistent library is imported, it will probably be generated by a
- // transformer.
- if (!fileExists(library)) {
- _directives[libraryUri] = null;
- return null;
- }
-
- _directives[libraryUri] = parseImportsAndExports(
- readTextFile(library),
- name: library).map((directive) => Uri.parse(directive.uri.stringValue)).toSet();
- return _directives[libraryUri];
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_aggregate_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_aggregate_transformer.dart
deleted file mode 100644
index a45f824..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_aggregate_transformer.dart
+++ /dev/null
@@ -1,69 +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.
-
-library pub.excluding_aggregate_transformer;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-import 'transformer_config.dart';
-
-/// Decorates an inner [AggregateTransformer] and handles including and
-/// excluding primary inputs.
-class ExcludingAggregateTransformer extends AggregateTransformer {
- /// If [config] defines includes or excludes, wraps [inner] in an
- /// [ExcludingAggregateTransformer] that handles those.
- ///
- /// Otherwise, just returns [inner] unmodified.
- static AggregateTransformer wrap(AggregateTransformer inner,
- TransformerConfig config) {
- if (!config.hasExclusions) return inner;
-
- if (inner is LazyAggregateTransformer) {
- return new _LazyExcludingAggregateTransformer(
- inner as LazyAggregateTransformer,
- config);
- } else if (inner is DeclaringAggregateTransformer) {
- return new _DeclaringExcludingAggregateTransformer(
- inner as DeclaringAggregateTransformer,
- config);
- } else {
- return new ExcludingAggregateTransformer._(inner, config);
- }
- }
-
- final AggregateTransformer _inner;
-
- /// The config containing rules for which assets to include or exclude.
- final TransformerConfig _config;
-
- ExcludingAggregateTransformer._(this._inner, this._config);
-
- classifyPrimary(AssetId id) {
- if (!_config.canTransform(id.path)) return null;
- return _inner.classifyPrimary(id);
- }
-
- Future apply(AggregateTransform transform) => _inner.apply(transform);
-
- String toString() => _inner.toString();
-}
-
-class _DeclaringExcludingAggregateTransformer extends
- ExcludingAggregateTransformer implements DeclaringAggregateTransformer {
- _DeclaringExcludingAggregateTransformer(DeclaringAggregateTransformer inner,
- TransformerConfig config)
- : super._(inner as AggregateTransformer, config);
-
- Future declareOutputs(DeclaringAggregateTransform transform) =>
- (_inner as DeclaringAggregateTransformer).declareOutputs(transform);
-}
-
-class _LazyExcludingAggregateTransformer extends
- _DeclaringExcludingAggregateTransformer implements LazyAggregateTransformer {
- _LazyExcludingAggregateTransformer(DeclaringAggregateTransformer inner,
- TransformerConfig config)
- : super(inner, config);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_transformer.dart
deleted file mode 100644
index 52d90a9..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_transformer.dart
+++ /dev/null
@@ -1,67 +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.
-
-library pub.excluding_transformer;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-import 'transformer_config.dart';
-
-/// Decorates an inner [Transformer] and handles including and excluding
-/// primary inputs.
-class ExcludingTransformer extends Transformer {
- /// If [config] defines includes or excludes, wraps [inner] in an
- /// [ExcludingTransformer] that handles those.
- ///
- /// Otherwise, just returns [inner] unmodified.
- static Transformer wrap(Transformer inner, TransformerConfig config) {
- if (!config.hasExclusions) return inner;
-
- if (inner is LazyTransformer) {
- // TODO(nweiz): Remove these unnecessary "as"es when issue 19046 is fixed.
- return new _LazyExcludingTransformer(inner as LazyTransformer, config);
- } else if (inner is DeclaringTransformer) {
- return new _DeclaringExcludingTransformer(
- inner as DeclaringTransformer,
- config);
- } else {
- return new ExcludingTransformer._(inner, config);
- }
- }
-
- final Transformer _inner;
-
- /// The config containing rules for which assets to include or exclude.
- final TransformerConfig _config;
-
- ExcludingTransformer._(this._inner, this._config);
-
- isPrimary(AssetId id) {
- if (!_config.canTransform(id.path)) return false;
- return _inner.isPrimary(id);
- }
-
- Future apply(Transform transform) => _inner.apply(transform);
-
- String toString() => _inner.toString();
-}
-
-class _DeclaringExcludingTransformer extends ExcludingTransformer implements
- DeclaringTransformer {
- _DeclaringExcludingTransformer(DeclaringTransformer inner,
- TransformerConfig config)
- : super._(inner as Transformer, config);
-
- Future declareOutputs(DeclaringTransform transform) =>
- (_inner as DeclaringTransformer).declareOutputs(transform);
-}
-
-class _LazyExcludingTransformer extends _DeclaringExcludingTransformer
- implements LazyTransformer {
- _LazyExcludingTransformer(DeclaringTransformer inner,
- TransformerConfig config)
- : super(inner, config);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/foreign_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/foreign_transformer.dart
deleted file mode 100644
index 6ab1114..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/foreign_transformer.dart
+++ /dev/null
@@ -1,171 +0,0 @@
-// Copyright (c) 2013, 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 pub.foreign_transformer;
-
-import 'dart:async';
-import 'dart:isolate';
-
-import 'package:barback/barback.dart';
-
-import '../../../asset/dart/serialize.dart';
-import 'excluding_transformer.dart';
-import 'excluding_aggregate_transformer.dart';
-import 'transformer_config.dart';
-
-/// A wrapper for a transformer that's in a different isolate.
-class _ForeignTransformer extends Transformer {
- /// The port with which we communicate with the child isolate.
- ///
- /// This port and all messages sent across it are specific to this
- /// transformer.
- final SendPort _port;
-
- /// The result of calling [toString] on the transformer in the isolate.
- final String _toString;
-
- _ForeignTransformer(Map map)
- : _port = map['port'],
- _toString = map['toString'];
-
- Future<bool> isPrimary(AssetId id) {
- return call(_port, {
- 'type': 'isPrimary',
- 'id': serializeId(id)
- });
- }
-
- Future apply(Transform transform) {
- return call(_port, {
- 'type': 'apply',
- 'transform': serializeTransform(transform)
- });
- }
-
- String toString() => _toString;
-}
-
-class _ForeignDeclaringTransformer extends _ForeignTransformer implements
- DeclaringTransformer {
- _ForeignDeclaringTransformer(Map map)
- : super(map);
-
- Future declareOutputs(DeclaringTransform transform) {
- return call(_port, {
- 'type': 'declareOutputs',
- 'transform': serializeDeclaringTransform(transform)
- });
- }
-}
-
-class _ForeignLazyTransformer extends _ForeignDeclaringTransformer implements
- LazyTransformer {
- _ForeignLazyTransformer(Map map)
- : super(map);
-}
-
-/// A wrapper for an aggregate transformer that's in a different isolate.
-class _ForeignAggregateTransformer extends AggregateTransformer {
- /// The port with which we communicate with the child isolate.
- ///
- /// This port and all messages sent across it are specific to this
- /// transformer.
- final SendPort _port;
-
- /// The result of calling [toString] on the transformer in the isolate.
- final String _toString;
-
- _ForeignAggregateTransformer(Map map)
- : _port = map['port'],
- _toString = map['toString'];
-
- Future<String> classifyPrimary(AssetId id) {
- return call(_port, {
- 'type': 'classifyPrimary',
- 'id': serializeId(id)
- });
- }
-
- Future apply(AggregateTransform transform) {
- return call(_port, {
- 'type': 'apply',
- 'transform': serializeAggregateTransform(transform)
- });
- }
-
- String toString() => _toString;
-}
-
-class _ForeignDeclaringAggregateTransformer extends _ForeignAggregateTransformer
- implements DeclaringAggregateTransformer {
- _ForeignDeclaringAggregateTransformer(Map map)
- : super(map);
-
- Future declareOutputs(DeclaringAggregateTransform transform) {
- return call(_port, {
- 'type': 'declareOutputs',
- 'transform': serializeDeclaringAggregateTransform(transform)
- });
- }
-}
-
-class _ForeignLazyAggregateTransformer extends
- _ForeignDeclaringAggregateTransformer implements LazyAggregateTransformer {
- _ForeignLazyAggregateTransformer(Map map)
- : super(map);
-}
-
-/// A wrapper for a transformer group that's in a different isolate.
-class _ForeignGroup implements TransformerGroup {
- final Iterable<Iterable> phases;
-
- /// The result of calling [toString] on the transformer group in the isolate.
- final String _toString;
-
- _ForeignGroup(TransformerConfig config, Map map)
- : phases = map['phases'].map((phase) {
- return phase.map(
- (transformer) => deserializeTransformerLike(transformer, config)).toList();
- }).toList(),
- _toString = map['toString'];
-
- String toString() => _toString;
-}
-
-/// Converts a serializable map into a [Transformer], an [AggregateTransformer],
-/// or a [TransformerGroup].
-deserializeTransformerLike(Map map, TransformerConfig config) {
- var transformer;
- switch (map['type']) {
- case 'TransformerGroup':
- return new _ForeignGroup(config, map);
- case 'Transformer':
- transformer = new _ForeignTransformer(map);
- break;
- case 'DeclaringTransformer':
- transformer = new _ForeignDeclaringTransformer(map);
- break;
- case 'LazyTransformer':
- transformer = new _ForeignLazyTransformer(map);
- break;
- case 'AggregateTransformer':
- transformer = new _ForeignAggregateTransformer(map);
- break;
- case 'DeclaringAggregateTransformer':
- transformer = new _ForeignDeclaringAggregateTransformer(map);
- break;
- case 'LazyAggregateTransformer':
- transformer = new _ForeignLazyAggregateTransformer(map);
- break;
- default:
- assert(false);
- }
-
- if (transformer is Transformer) {
- return ExcludingTransformer.wrap(transformer, config);
- } else {
- assert(transformer is AggregateTransformer);
- return ExcludingAggregateTransformer.wrap(transformer, config);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/load_all_transformers.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/load_all_transformers.dart
deleted file mode 100644
index fc59377..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/load_all_transformers.dart
+++ /dev/null
@@ -1,276 +0,0 @@
-// Copyright (c) 2013, 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 pub.load_all_transformers;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-import '../log.dart' as log;
-import '../package_graph.dart';
-import '../utils.dart';
-import 'asset_environment.dart';
-import 'barback_server.dart';
-import 'dependency_computer.dart';
-import 'transformer_id.dart';
-import 'transformer_loader.dart';
-
-/// Loads all transformers depended on by packages in [environment].
-///
-/// This uses [environment]'s primary server to serve the Dart files from which
-/// transformers are loaded, then adds the transformers to
-/// `environment.barback`.
-///
-/// Any built-in transformers that are provided by the environment will
-/// automatically be added to the end of the root package's cascade.
-///
-/// If [entrypoints] is passed, only transformers necessary to run those
-/// entrypoints will be loaded.
-Future loadAllTransformers(AssetEnvironment environment,
- BarbackServer transformerServer, {Iterable<AssetId> entrypoints}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var dependencyComputer = new DependencyComputer(environment.graph);
- var necessaryTransformers;
- join0() {
- var transformersNeededByTransformers =
- dependencyComputer.transformersNeededByTransformers(necessaryTransformers);
- var buffer = new StringBuffer();
- buffer.writeln("Transformer dependencies:");
- transformersNeededByTransformers.forEach(((id, dependencies) {
- if (dependencies.isEmpty) {
- buffer.writeln("$id: -");
- } else {
- buffer.writeln("$id: ${toSentence(dependencies)}");
- }
- }));
- log.fine(buffer);
- var stagedTransformers =
- _stageTransformers(transformersNeededByTransformers);
- var packagesThatUseTransformers =
- _packagesThatUseTransformers(environment.graph);
- var loader = new TransformerLoader(environment, transformerServer);
- join1(x0) {
- var cache = x0;
- var first = true;
- var it0 = stagedTransformers.iterator;
- break0() {
- join2() {
- new Future.value(
- Future.wait(environment.graph.packages.values.map(((package) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(
- loader.transformersForPhases(package.pubspec.transformers)).then((x0) {
- try {
- var phases = x0;
- var transformers =
- environment.getBuiltInTransformers(package);
- join0() {
- join1() {
- newFuture((() {
- return environment.barback.updateTransformers(
- package.name,
- phases);
- }));
- completer0.complete();
- }
- if (phases.isEmpty) {
- completer0.complete(null);
- } else {
- join1();
- }
- }
- if (transformers != null) {
- phases.add(transformers);
- join0();
- } else {
- join0();
- }
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x1) {
- try {
- x1;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (cache != null) {
- cache.save();
- join2();
- } else {
- join2();
- }
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var stage = it0.current;
- join3(x2) {
- var snapshotPath = x2;
- first = false;
- new Future.value(
- loader.load(stage, snapshot: snapshotPath)).then((x3) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- x3;
- var packagesToUpdate = unionAll(stage.map(((id) {
- return packagesThatUseTransformers[id];
- })));
- new Future.value(
- Future.wait(packagesToUpdate.map(((packageName) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var package =
- environment.graph.packages[packageName];
- new Future.value(
- loader.transformersForPhases(package.pubspec.transformers)).then((x0) {
- try {
- var phases = x0;
- environment.barback.updateTransformers(
- packageName,
- phases);
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x4) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- x4;
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: completer0.completeError);
- } catch (e2, s2) {
- completer0.completeError(e2, s2);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: completer0.completeError);
- }
- if (cache == null || !first) {
- join3(null);
- } else {
- join3(cache.snapshotPath(stage));
- }
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- if (environment.rootPackage.dir == null) {
- join1(null);
- } else {
- join1(environment.graph.loadTransformerCache());
- }
- }
- if (entrypoints != null) {
- join4() {
- necessaryTransformers =
- unionAll(entrypoints.map(dependencyComputer.transformersNeededByLibrary));
- join5() {
- join0();
- }
- if (necessaryTransformers.isEmpty) {
- log.fine(
- "No transformers are needed for ${toSentence(entrypoints)}.");
- completer0.complete(null);
- } else {
- join5();
- }
- }
- if (entrypoints.isEmpty) {
- completer0.complete(null);
- } else {
- join4();
- }
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
-}
-
-/// Given [transformerDependencies], a directed acyclic graph, returns a list of
-/// "stages" (sets of transformers).
-///
-/// Each stage must be fully loaded and passed to barback before the next stage
-/// can be safely loaded. However, transformers within a stage can be safely
-/// loaded in parallel.
-List<Set<TransformerId>> _stageTransformers(Map<TransformerId,
- Set<TransformerId>> transformerDependencies) {
- // A map from transformer ids to the indices of the stages that those
- // transformer ids should end up in. Populated by [stageNumberFor].
- var stageNumbers = {};
- var stages = [];
-
- stageNumberFor(id) {
- // Built-in transformers don't have to be loaded in stages, since they're
- // run from pub's source. Return -1 so that the "next stage" is 0.
- if (id.isBuiltInTransformer) return -1;
-
- if (stageNumbers.containsKey(id)) return stageNumbers[id];
- var dependencies = transformerDependencies[id];
- stageNumbers[id] =
- dependencies.isEmpty ? 0 : maxAll(dependencies.map(stageNumberFor)) + 1;
- return stageNumbers[id];
- }
-
- for (var id in transformerDependencies.keys) {
- var stageNumber = stageNumberFor(id);
- if (stages.length <= stageNumber) stages.length = stageNumber + 1;
- if (stages[stageNumber] == null) stages[stageNumber] = new Set();
- stages[stageNumber].add(id);
- }
-
- return stages;
-}
-
-/// Returns a map from transformer ids to all packages in [graph] that use each
-/// transformer.
-Map<TransformerId, Set<String>> _packagesThatUseTransformers(PackageGraph graph)
- {
- var results = {};
- for (var package in graph.packages.values) {
- for (var phase in package.pubspec.transformers) {
- for (var config in phase) {
- results.putIfAbsent(config.id, () => new Set()).add(package.name);
- }
- }
- }
- return results;
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/pub_package_provider.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/pub_package_provider.dart
deleted file mode 100644
index d82da67..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/pub_package_provider.dart
+++ /dev/null
@@ -1,125 +0,0 @@
-// Copyright (c) 2013, 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 pub.pub_package_provider;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as path;
-
-import '../io.dart';
-import '../package_graph.dart';
-import '../preprocess.dart';
-import '../sdk.dart' as sdk;
-import '../utils.dart';
-
-/// An implementation of barback's [PackageProvider] interface so that barback
-/// can find assets within pub packages.
-class PubPackageProvider implements StaticPackageProvider {
- final PackageGraph _graph;
- final List<String> staticPackages;
-
- Iterable<String> get packages =>
- _graph.packages.keys.toSet().difference(staticPackages.toSet());
-
- PubPackageProvider(PackageGraph graph)
- : _graph = graph,
- staticPackages = [
- r"$pub",
- r"$sdk"]..addAll(graph.packages.keys.where(graph.isPackageStatic));
-
- Future<Asset> getAsset(AssetId id) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- join1() {
- var nativePath = path.fromUri(id.path);
- var file = _graph.packages[id.package].path(nativePath);
- _assertExists(file, id);
- completer0.complete(new Asset.fromPath(id, file));
- }
- if (id.package == r'$sdk') {
- var parts = path.split(path.fromUri(id.path));
- assert(parts.isNotEmpty && parts[0] == 'lib');
- parts = parts.skip(1);
- var file = path.join(sdk.rootDirectory, path.joinAll(parts));
- _assertExists(file, id);
- completer0.complete(new Asset.fromPath(id, file));
- } else {
- join1();
- }
- }
- if (id.package == r'$pub') {
- var components = path.url.split(id.path);
- assert(components.isNotEmpty);
- assert(components.first == 'lib');
- components[0] = 'dart';
- var file = assetPath(path.joinAll(components));
- _assertExists(file, id);
- join2() {
- var versions = mapMap(_graph.packages, value: ((_, package) {
- return package.version;
- }));
- var contents = readTextFile(file);
- contents = preprocess(contents, versions, path.toUri(file));
- completer0.complete(new Asset.fromString(id, contents));
- }
- if (!_graph.packages.containsKey("barback")) {
- completer0.complete(new Asset.fromPath(id, file));
- } else {
- join2();
- }
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Throw an [AssetNotFoundException] for [id] if [path] doesn't exist.
- void _assertExists(String path, AssetId id) {
- if (!fileExists(path)) throw new AssetNotFoundException(id);
- }
-
- Stream<AssetId> getAllAssetIds(String packageName) {
- if (packageName == r'$pub') {
- // "$pub" is a pseudo-package that allows pub's transformer-loading
- // infrastructure to share code with pub proper. We provide it only during
- // the initial transformer loading process.
- var dartPath = assetPath('dart');
- return new Stream.fromIterable(
- listDir(dartPath, recursive: true)// Don't include directories.
- .where((file) => path.extension(file) == ".dart").map((library) {
- var idPath = path.join('lib', path.relative(library, from: dartPath));
- return new AssetId('\$pub', path.toUri(idPath).toString());
- }));
- } else if (packageName == r'$sdk') {
- // "$sdk" is a pseudo-package that allows the dart2js transformer to find
- // the Dart core libraries without hitting the file system directly. This
- // ensures they work with source maps.
- var libPath = path.join(sdk.rootDirectory, "lib");
- return new Stream.fromIterable(
- listDir(
- libPath,
- recursive: true).where((file) => path.extension(file) == ".dart").map((file) {
- var idPath =
- path.join("lib", path.relative(file, from: sdk.rootDirectory));
- return new AssetId('\$sdk', path.toUri(idPath).toString());
- }));
- } else {
- var package = _graph.packages[packageName];
- return new Stream.fromIterable(
- package.listFiles(beneath: 'lib').map((file) {
- return new AssetId(
- packageName,
- path.toUri(package.relative(file)).toString());
- }));
- }
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/source_directory.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/source_directory.dart
deleted file mode 100644
index 9996ab9..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/source_directory.dart
+++ /dev/null
@@ -1,71 +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.
-
-library pub.barback.source_directory;
-
-import 'dart:async';
-
-import 'package:watcher/watcher.dart';
-
-import 'asset_environment.dart';
-import 'barback_server.dart';
-
-/// A directory in the entrypoint package whose contents have been made
-/// available to barback and that are bound to a server.
-class SourceDirectory {
- final AssetEnvironment _environment;
-
- /// The relative directory path within the package.
- final String directory;
-
- /// The hostname to serve this directory on.
- final String hostname;
-
- /// The port to serve this directory on.
- final int port;
-
- /// The server bound to this directory.
- ///
- /// This is a future that will complete once [serve] has been called and the
- /// server has been successfully spun up.
- Future<BarbackServer> get server => _serverCompleter.future;
- final _serverCompleter = new Completer<BarbackServer>();
-
- /// The subscription to the [DirectoryWatcher] used to watch this directory
- /// for changes.
- ///
- /// If the directory is not being watched, this will be `null`.
- StreamSubscription<WatchEvent> watchSubscription;
-
- SourceDirectory(this._environment, this.directory, this.hostname, this.port);
-
- /// Binds a server running on [hostname]:[port] to this directory.
- Future<BarbackServer> serve() {
- return BarbackServer.bind(
- _environment,
- hostname,
- port,
- rootDirectory: directory).then((server) {
- _serverCompleter.complete(server);
- return server;
- });
- }
-
- /// Removes the source directory from the build environment.
- ///
- /// Closes the server, removes the assets from barback, and stops watching it.
- Future close() {
- return server.then((server) {
- var futures = [server.close()];
-
- // Stop watching the directory.
- if (watchSubscription != null) {
- var cancel = watchSubscription.cancel();
- if (cancel != null) futures.add(cancel);
- }
-
- return Future.wait(futures);
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_cache.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_cache.dart
deleted file mode 100644
index 7e8a61d..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_cache.dart
+++ /dev/null
@@ -1,144 +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.
-
-library pub.barback.transformer_cache;
-
-import 'package:path/path.dart' as p;
-
-import '../io.dart';
-import '../log.dart' as log;
-import '../package_graph.dart';
-import '../sdk.dart' as sdk;
-import '../utils.dart';
-import 'transformer_id.dart';
-
-/// A cache for managing a snapshot of the first "stage" of transformers to
-/// load.
-///
-/// This uses the [_stageTransformers] notion of a stage. Transformers are
-/// divided into stages for loading based on which transformers are needed to
-/// load one another. For example, if a transformer T1 produces a file that's
-/// imported by another transformer T2, T2 must be put in a stage after T1.
-///
-/// We only cache the first stage because it's the only stage whose contents are
-/// independent of any configuration. Since most transformers don't import the
-/// output of other transformers, many packages will only have one stage.
-class TransformerCache {
- final PackageGraph _graph;
-
- /// The set of transformer ids that were previously cached.
- ///
- /// If there was no previous cache, this will be empty.
- Set<TransformerId> _oldTransformers;
-
- /// The set of transformer ids that are newly cached or re-used from the
- /// previous cache.
- Set<TransformerId> _newTransformers;
-
- /// The directory in which transformers are cached.
- ///
- /// This may be `null` if there's no physical entrypoint directory.
- String _dir;
-
- /// The directory of the manifest listing which transformers were cached.
- String get _manifestPath => p.join(_dir, "manifest.txt");
-
- /// Loads the transformer cache for [environment].
- ///
- /// This may modify the cache.
- TransformerCache.load(PackageGraph graph)
- : _graph = graph,
- _dir = graph.entrypoint.root.path(".pub/transformers") {
- _oldTransformers = _parseManifest();
- }
-
- /// Clear the cache if it depends on any package in [changedPackages].
- void clearIfOutdated(Set<String> changedPackages) {
- var snapshotDependencies = unionAll(_oldTransformers.map((id) {
- // If the transformer cache contains transformers we don't know about,
- // that's fine; we just won't load them.
- if (!_graph.packages.containsKey(id.package)) return new Set();
-
- return _graph.transitiveDependencies(
- id.package).map((package) => package.name).toSet();
- }));
-
- // If none of the snapshot's dependencies have changed, then we can reuse
- // it.
- if (!overlaps(changedPackages, snapshotDependencies)) return;
-
- // Otherwise, delete it.
- deleteEntry(_dir);
- _oldTransformers = new Set();
- }
-
- /// Returns the path for the transformer snapshot for [transformers], or
- /// `null` if the transformers shouldn't be cached.
- ///
- /// There may or may not exist a file at the returned path. If one does exist,
- /// it can safely be used to load the stage. Otherwise, a snapshot of the
- /// stage should be written there.
- String snapshotPath(Set<TransformerId> transformers) {
- var path = p.join(_dir, "transformers.snapshot");
- if (_newTransformers != null) return path;
-
- if (transformers.any((id) => _graph.isPackageMutable(id.package))) {
- log.fine("Not caching mutable transformers.");
- deleteEntry(_dir);
- return null;
- }
-
- if (!_oldTransformers.containsAll(transformers)) {
- log.fine("Cached transformer snapshot is out-of-date, deleting.");
- deleteEntry(path);
- } else {
- log.fine("Using cached transformer snapshot.");
- }
-
- _newTransformers = transformers;
- return path;
- }
-
- /// Saves the manifest to the transformer cache.
- void save() {
- // If we didn't write any snapshots, there's no need to write a manifest.
- if (_newTransformers == null) {
- if (_dir != null) deleteEntry(_dir);
- return;
- }
-
- // We only need to rewrite the manifest if we created a new snapshot.
- if (_oldTransformers.containsAll(_newTransformers)) return;
-
- ensureDir(_dir);
- writeTextFile(
- _manifestPath,
- "${sdk.version}\n" +
- ordered(_newTransformers.map((id) => id.serialize())).join(","));
- }
-
- /// Parses the cache manifest and returns the set of previously-cached
- /// transformers.
- ///
- /// If the manifest indicates that the SDK version is out-of-date, this
- /// deletes the existing cache. Otherwise,
- Set<TransformerId> _parseManifest() {
- if (!fileExists(_manifestPath)) return new Set();
-
- var manifest = readTextFile(_manifestPath).split("\n");
-
- // The first line of the manifest is the SDK version. We want to clear out
- // the snapshots even if they're VM-compatible, since pub's transformer
- // isolate scaffolding may have changed.
- if (manifest.removeAt(0) != sdk.version.toString()) {
- deleteEntry(_dir);
- return new Set();
- }
-
- /// The second line of the manifest is a list of transformer ids used to
- /// create the existing snapshot.
- return manifest.single.split(
- ",").map((id) => new TransformerId.parse(id, null)).toSet();
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_config.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_config.dart
deleted file mode 100644
index 11d9594..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_config.dart
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright (c) 2013, 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 pub.barback.transformer_config;
-
-import 'package:glob/glob.dart';
-import 'package:path/path.dart' as p;
-import 'package:source_span/source_span.dart';
-import 'package:yaml/yaml.dart';
-
-import 'transformer_id.dart';
-
-/// The configuration for a transformer.
-///
-/// This corresponds to the transformers listed in a pubspec, which have both an
-/// [id] indicating the location of the transformer and configuration specific
-/// to that use of the transformer.
-class TransformerConfig {
- /// The [id] of the transformer [this] is configuring.
- final TransformerId id;
-
- /// The configuration to pass to the transformer.
- ///
- /// Any pub-specific configuration (i.e. keys starting with "$") will have
- /// been stripped out of this and handled separately. This will be an empty
- /// map if no configuration was provided.
- final Map configuration;
-
- /// The source span from which this configuration was parsed.
- final SourceSpan span;
-
- /// The primary input inclusions.
- ///
- /// Each inclusion is an asset path. If this set is non-empty, then *only*
- /// matching assets are allowed as a primary input by this transformer. If
- /// `null`, all assets are included.
- ///
- /// This is processed before [excludes]. If a transformer has both includes
- /// and excludes, then the set of included assets is determined and assets
- /// are excluded from that resulting set.
- final Set<Glob> includes;
-
- /// The primary input exclusions.
- ///
- /// Any asset whose pach is in this is not allowed as a primary input by
- /// this transformer.
- ///
- /// This is processed after [includes]. If a transformer has both includes
- /// and excludes, then the set of included assets is determined and assets
- /// are excluded from that resulting set.
- final Set<Glob> excludes;
-
- /// Returns whether this config excludes certain asset ids from being
- /// processed.
- bool get hasExclusions => includes != null || excludes != null;
-
- /// Returns whether this transformer might transform a file that's visible to
- /// the package's dependers.
- bool get canTransformPublicFiles {
- if (includes == null) return true;
- return includes.any((glob) {
- // Check whether the first path component of the glob is "lib", "bin", or
- // contains wildcards that may cause it to match "lib" or "bin".
- var first = p.posix.split(glob.toString()).first;
- if (first.contains('{') ||
- first.contains('*') ||
- first.contains('[') ||
- first.contains('?')) {
- return true;
- }
-
- return first == 'lib' || first == 'bin';
- });
- }
-
- /// Parses [identifier] as a [TransformerId] with [configuration].
- ///
- /// [identifierSpan] is the source span for [identifier].
- factory TransformerConfig.parse(String identifier, SourceSpan identifierSpan,
- YamlMap configuration) =>
- new TransformerConfig(
- new TransformerId.parse(identifier, identifierSpan),
- configuration);
-
- factory TransformerConfig(TransformerId id, YamlMap configurationNode) {
- parseField(key) {
- if (!configurationNode.containsKey(key)) return null;
- var fieldNode = configurationNode.nodes[key];
- var field = fieldNode.value;
-
- if (field is String) {
- return new Set.from([new Glob(field, context: p.url, recursive: true)]);
- }
-
- if (field is! List) {
- throw new SourceSpanFormatException(
- '"$key" field must be a string or list.',
- fieldNode.span);
- }
-
- return new Set.from(field.nodes.map((node) {
- if (node.value is String) {
- return new Glob(node.value, context: p.url, recursive: true);
- }
-
- throw new SourceSpanFormatException(
- '"$key" field may contain only strings.',
- node.span);
- }));
- }
-
- var includes = null;
- var excludes = null;
-
- var configuration;
- var span;
- if (configurationNode == null) {
- configuration = {};
- span = id.span;
- } else {
- // Don't write to the immutable YAML map.
- configuration = new Map.from(configurationNode);
- span = configurationNode.span;
-
- // Pull out the exclusions/inclusions.
- includes = parseField("\$include");
- configuration.remove("\$include");
- excludes = parseField("\$exclude");
- configuration.remove("\$exclude");
-
- // All other keys starting with "$" are unexpected.
- for (var key in configuration.keys) {
- if (key is! String || !key.startsWith(r'$')) continue;
- throw new SourceSpanFormatException(
- 'Unknown reserved field.',
- configurationNode.nodes[key].span);
- }
- }
-
- return new TransformerConfig._(id, configuration, span, includes, excludes);
- }
-
- TransformerConfig._(this.id, this.configuration, this.span, this.includes,
- this.excludes);
-
- String toString() => id.toString();
-
- /// Returns whether the include/exclude rules allow the transformer to run on
- /// [pathWithinPackage].
- ///
- /// [pathWithinPackage] must be a URL-style path relative to the containing
- /// package's root directory.
- bool canTransform(String pathWithinPackage) {
- if (excludes != null) {
- // If there are any excludes, it must not match any of them.
- for (var exclude in excludes) {
- if (exclude.matches(pathWithinPackage)) return false;
- }
- }
-
- // If there are any includes, it must match one of them.
- return includes == null ||
- includes.any((include) => include.matches(pathWithinPackage));
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_id.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_id.dart
deleted file mode 100644
index 2017d9b..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_id.dart
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright (c) 2013, 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 pub.barback.transformer_id;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:source_span/source_span.dart';
-
-import '../utils.dart';
-
-/// A list of the names of all built-in transformers that pub exposes.
-const _BUILT_IN_TRANSFORMERS = const ['\$dart2js'];
-
-/// An identifier that indicates the library that contains a transformer.
-///
-/// It's possible that the library identified by [this] defines multiple
-/// transformers. If so, they're all always loaded in the same phase.
-class TransformerId {
- /// The package containing the library where the transformer is defined.
- final String package;
-
- /// The `/`-separated path to the library that contains this transformer.
- ///
- /// This is relative to the `lib/` directory in [package], and doesn't end in
- /// `.dart`.
- ///
- /// This can be null; if so, it indicates that the transformer(s) should be
- /// loaded from `lib/transformer.dart` if that exists, and `lib/$package.dart`
- /// otherwise.
- final String path;
-
- /// The source span from which this id was parsed.
- final SourceSpan span;
-
- /// Whether this ID points to a built-in transformer exposed by pub.
- bool get isBuiltInTransformer => package.startsWith('\$');
-
- /// Parses a transformer identifier.
- ///
- /// A transformer identifier is a string of the form "package_name" or
- /// "package_name/path/to/library". It does not have a trailing extension. If
- /// it just has a package name, it expands to lib/transformer.dart if that
- /// exists, or lib/${package}.dart otherwise. Otherwise, it expands to
- /// lib/${path}.dart. In either case it's located in the given package.
- factory TransformerId.parse(String identifier, SourceSpan span) {
- if (identifier.isEmpty) {
- throw new FormatException('Invalid library identifier: "".');
- }
-
- var parts = split1(identifier, "/");
- if (parts.length == 1) {
- return new TransformerId(parts.single, null, span);
- }
-
- return new TransformerId(parts.first, parts.last, span);
- }
-
- TransformerId(this.package, this.path, this.span) {
- if (!package.startsWith('\$')) return;
- if (_BUILT_IN_TRANSFORMERS.contains(package)) return;
- throw new SourceSpanFormatException(
- 'Unsupported built-in transformer $package.',
- span);
- }
-
- bool operator ==(other) =>
- other is TransformerId && other.package == package && other.path == path;
-
- int get hashCode => package.hashCode ^ path.hashCode;
-
- /// Returns a serialized form of [this] that can be passed to
- /// [new TransformerId.parse].
- String serialize() => path == null ? package : '$package/$path';
-
- String toString() => serialize();
-
- /// Returns the asset id for the library identified by this transformer id.
- ///
- /// If `path` is null, this will determine which library to load. Unlike
- /// [getAssetId], this doesn't take generated assets into account; it's used
- /// to determine transformers' dependencies, which requires looking at files
- /// on disk.
- Future<AssetId> getAssetId(Barback barback) {
- if (path != null) {
- return new Future.value(new AssetId(package, 'lib/$path.dart'));
- }
-
- var transformerAsset = new AssetId(package, 'lib/transformer.dart');
- return barback.getAssetById(
- transformerAsset).then(
- (_) =>
- transformerAsset).catchError(
- (e) => new AssetId(package, 'lib/$package.dart'),
- test: (e) => e is AssetNotFoundException);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_isolate.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_isolate.dart
deleted file mode 100644
index 04298d2..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_isolate.dart
+++ /dev/null
@@ -1,141 +0,0 @@
-// Copyright (c) 2013, 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 pub.transformer_isolate;
-
-import 'dart:async';
-import 'dart:convert';
-import 'dart:isolate';
-
-import 'package:barback/barback.dart';
-import 'package:source_span/source_span.dart';
-import 'package:stack_trace/stack_trace.dart';
-
-import '../../../asset/dart/serialize.dart';
-import '../barback.dart';
-import '../exceptions.dart';
-import '../dart.dart' as dart;
-import '../log.dart' as log;
-import '../utils.dart';
-import 'asset_environment.dart';
-import 'barback_server.dart';
-import 'foreign_transformer.dart';
-import 'transformer_config.dart';
-import 'transformer_id.dart';
-
-/// A wrapper for an isolate from which transformer plugins can be instantiated.
-class TransformerIsolate {
- /// The port used to communicate with the wrapped isolate.
- final SendPort _port;
-
- /// A map indicating the barback server URLs for each [TransformerId] that's
- /// loaded in the wrapped isolate.
- ///
- /// A barback server URL is the URL for the library that the given id
- /// identifies. For example, the URL for "polymer/src/mirrors_remover" might
- /// be "http://localhost:56234/packages/polymer/src/mirrors_remover.dart".
- final Map<TransformerId, Uri> _idsToUrls;
-
- /// The barback mode for this run of pub.
- final BarbackMode _mode;
-
- /// Spawns an isolate that loads all transformer libraries defined by [ids].
- ///
- /// This doesn't actually instantiate any transformers, since a
- /// [TransformerId] doesn't define the transformers' configuration. The
- /// transformers can be constructed using [create].
- ///
- /// If [snapshot] is passed, the isolate will be loaded from that path if it
- /// exists. Otherwise, a snapshot of the isolate's code will be saved to that
- /// path once the isolate is loaded.
- static Future<TransformerIsolate> spawn(AssetEnvironment environment,
- BarbackServer transformerServer, List<TransformerId> ids, {String snapshot}) {
- return mapFromIterableAsync(ids, value: (id) {
- return id.getAssetId(environment.barback);
- }).then((idsToAssetIds) {
- var baseUrl = transformerServer.url;
- var idsToUrls = mapMap(idsToAssetIds, value: (id, assetId) {
- var path = assetId.path.replaceFirst('lib/', '');
- return Uri.parse('package:${id.package}/$path');
- });
-
- var code = new StringBuffer();
- code.writeln("import 'dart:isolate';");
-
- for (var url in idsToUrls.values) {
- code.writeln("import '$url';");
- }
-
- code.writeln("import r'package:\$pub/transformer_isolate.dart';");
- code.writeln(
- "void main(_, SendPort replyTo) => loadTransformers(replyTo);");
-
- log.fine("Loading transformers from $ids");
-
- var port = new ReceivePort();
- return dart.runInIsolate(
- code.toString(),
- port.sendPort,
- packageRoot: baseUrl.resolve('packages'),
- snapshot: snapshot).then((_) => port.first).then((sendPort) {
- return new TransformerIsolate._(sendPort, environment.mode, idsToUrls);
- }).catchError((error, stackTrace) {
- if (error is! CrossIsolateException) throw error;
- if (error.type != 'IsolateSpawnException') throw error;
-
- // TODO(nweiz): don't parse this as a string once issues 12617 and 12689
- // are fixed.
- var firstErrorLine = error.message.split('\n')[1];
-
- // The isolate error message contains the fully expanded path, not the
- // "package:" URI, so we have to be liberal in what we look for in the
- // error message.
- var missingTransformer = idsToUrls.keys.firstWhere(
- (id) =>
- firstErrorLine.startsWith("Uncaught Error: Load Error: Failure getting ") &&
- firstErrorLine.contains(idsToUrls[id].path),
- orElse: () => throw error);
- var packageUri = idToPackageUri(idsToAssetIds[missingTransformer]);
-
- // If there was an IsolateSpawnException and the import that actually
- // failed was the one we were loading transformers from, throw an
- // application exception with a more user-friendly message.
- fail('Transformer library "$packageUri" not found.', error, stackTrace);
- });
- });
- }
-
- TransformerIsolate._(this._port, this._mode, this._idsToUrls);
-
- /// Instantiate the transformers in the [config.id] with
- /// [config.configuration].
- ///
- /// If there are no transformers defined in the given library, this will
- /// return an empty set.
- Future<Set<Transformer>> create(TransformerConfig config) {
- return call(_port, {
- 'library': _idsToUrls[config.id].toString(),
- 'mode': _mode.name,
- 'configuration': JSON.encode(config.configuration)
- }).then((transformers) {
- transformers = transformers.map(
- (transformer) => deserializeTransformerLike(transformer, config)).toSet();
- log.fine("Transformers from $config: $transformers");
- return transformers;
- }).catchError((error, stackTrace) {
- throw new TransformerLoadError(error, config.span);
- });
- }
-}
-
-/// An error thrown when a transformer fails to load.
-class TransformerLoadError extends SourceSpanException implements
- WrappedException {
- final CrossIsolateException innerError;
- Chain get innerChain => innerError.stackTrace;
-
- TransformerLoadError(CrossIsolateException error, SourceSpan span)
- : innerError = error,
- super("Error loading transformer: ${error.message}", span);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_loader.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_loader.dart
deleted file mode 100644
index 2333e3c..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_loader.dart
+++ /dev/null
@@ -1,249 +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.
-
-library pub.barback.transformer_loader;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-import '../log.dart' as log;
-import '../utils.dart';
-import 'asset_environment.dart';
-import 'barback_server.dart';
-import 'dart2js_transformer.dart';
-import 'excluding_transformer.dart';
-import 'transformer_config.dart';
-import 'transformer_id.dart';
-import 'transformer_isolate.dart';
-
-/// A class that loads transformers defined in specific files.
-class TransformerLoader {
- final AssetEnvironment _environment;
-
- final BarbackServer _transformerServer;
-
- final _isolates = new Map<TransformerId, TransformerIsolate>();
-
- final _transformers = new Map<TransformerConfig, Set<Transformer>>();
-
- /// The packages that use each transformer id.
- ///
- /// Used for error reporting.
- final _transformerUsers = new Map<TransformerId, Set<String>>();
-
- TransformerLoader(this._environment, this._transformerServer) {
- for (var package in _environment.graph.packages.values) {
- for (var config in unionAll(package.pubspec.transformers)) {
- _transformerUsers.putIfAbsent(
- config.id,
- () => new Set<String>()).add(package.name);
- }
- }
- }
-
- /// Loads a transformer plugin isolate that imports the transformer libraries
- /// indicated by [ids].
- ///
- /// Once the returned future completes, transformer instances from this
- /// isolate can be created using [transformersFor] or [transformersForPhase].
- ///
- /// This skips any ids that have already been loaded.
- Future load(Iterable<TransformerId> ids, {String snapshot}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- ids = ids.where(((id) {
- return !_isolates.containsKey(id);
- })).toList();
- join0() {
- new Future.value(
- log.progress("Loading ${toSentence(ids)} transformers", (() {
- return TransformerIsolate.spawn(
- _environment,
- _transformerServer,
- ids,
- snapshot: snapshot);
- }))).then((x0) {
- try {
- var isolate = x0;
- var it0 = ids.iterator;
- break0() {
- completer0.complete();
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var id = it0.current;
- _isolates[id] = isolate;
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (ids.isEmpty) {
- completer0.complete(null);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Instantiates and returns all transformers in the library indicated by
- /// [config] with the given configuration.
- ///
- /// If this is called before the library has been loaded into an isolate via
- /// [load], it will return an empty set.
- Future<Set<Transformer>> transformersFor(TransformerConfig config) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- join1() {
- var transformer;
- join2() {
- _transformers[config] =
- new Set.from([ExcludingTransformer.wrap(transformer, config)]);
- completer0.complete(_transformers[config]);
- }
- catch0(error, stackTrace) {
- try {
- if (error is FormatException) {
- fail(error.message, error, stackTrace);
- join2();
- } else {
- throw error;
- }
- } catch (error, stackTrace) {
- completer0.completeError(error, stackTrace);
- }
- }
- try {
- transformer = new Dart2JSTransformer.withSettings(
- _environment,
- new BarbackSettings(config.configuration, _environment.mode));
- join2();
- } catch (e0, s0) {
- catch0(e0, s0);
- }
- }
- if (_isolates.containsKey(config.id)) {
- new Future.value(_isolates[config.id].create(config)).then((x0) {
- try {
- var transformers = x0;
- join3() {
- var message = "No transformers";
- join4() {
- var location;
- join5() {
- var users =
- toSentence(ordered(_transformerUsers[config.id]));
- fail(
- "${message} were defined in ${location},\n" "required by ${users}.");
- join1();
- }
- if (config.id.path == null) {
- location =
- 'package:${config.id.package}/transformer.dart or '
- 'package:${config.id.package}/${config.id.package}.dart';
- join5();
- } else {
- location = 'package:${config}.dart';
- join5();
- }
- }
- if (config.configuration.isNotEmpty) {
- message += " that accept configuration";
- join4();
- } else {
- join4();
- }
- }
- if (transformers.isNotEmpty) {
- _transformers[config] = transformers;
- completer0.complete(transformers);
- } else {
- join3();
- }
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } else {
- join6() {
- join1();
- }
- if (config.id.package != '\$dart2js') {
- completer0.complete(new Future.value(new Set()));
- } else {
- join6();
- }
- }
- }
- if (_transformers.containsKey(config)) {
- completer0.complete(_transformers[config]);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Loads all transformers defined in each phase of [phases].
- ///
- /// If any library hasn't yet been loaded via [load], it will be ignored.
- Future<List<Set<Transformer>>>
- transformersForPhases(Iterable<Set<TransformerConfig>> phases) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(Future.wait(phases.map(((phase) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(
- waitAndPrintErrors(phase.map(transformersFor))).then((x0) {
- try {
- var transformers = x0;
- completer0.complete(unionAll(transformers));
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x0) {
- try {
- var result = x0;
- completer0.complete(result.toList());
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/web_socket_api.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/web_socket_api.dart
deleted file mode 100644
index 3d5d4e1..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/barback/web_socket_api.dart
+++ /dev/null
@@ -1,321 +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.
-
-library pub.barback.web_socket_api;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:http_parser/http_parser.dart';
-import 'package:path/path.dart' as path;
-import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc;
-
-import '../exit_codes.dart' as exit_codes;
-import '../io.dart';
-import '../log.dart' as log;
-import '../utils.dart';
-import 'asset_environment.dart';
-
-/// Implements the [WebSocket] API for communicating with a running pub serve
-/// process, mainly for use by the Editor.
-///
-/// This is a [JSON-RPC 2.0](http://www.jsonrpc.org/specification) server. Its
-/// methods are described in the method-level documentation below.
-class WebSocketApi {
- final AssetEnvironment _environment;
- final json_rpc.Server _server;
-
- /// Whether the application should exit when this connection closes.
- bool _exitOnClose = false;
-
- WebSocketApi(CompatibleWebSocket socket, this._environment)
- : _server = new json_rpc.Server(socket) {
- _server.registerMethod("urlToAssetId", _urlToAssetId);
- _server.registerMethod("pathToUrls", _pathToUrls);
- _server.registerMethod("serveDirectory", _serveDirectory);
- _server.registerMethod("unserveDirectory", _unserveDirectory);
-
- /// Tells the server to exit as soon as this WebSocket connection is closed.
- ///
- /// This takes no arguments and returns no results. It can safely be called
- /// as a JSON-RPC notification.
- _server.registerMethod("exitOnClose", () {
- _exitOnClose = true;
- });
- }
-
- /// Listens on the socket.
- ///
- /// Returns a future that completes when the socket has closed. It will
- /// complete with an error if the socket had an error, otherwise it will
- /// complete to `null`.
- Future listen() {
- return _server.listen().then((_) {
- if (!_exitOnClose) return;
- log.message("WebSocket connection closed, terminating.");
- flushThenExit(exit_codes.SUCCESS);
- });
- }
-
- /// Given a URL to an asset that is served by pub, returns the ID of the
- /// asset that would be accessed by that URL.
- ///
- /// The method name is "urlToAssetId" and it takes a "url" parameter for the
- /// URL being mapped:
- ///
- /// "params": {
- /// "url": "http://localhost:8080/index.html"
- /// }
- ///
- /// If successful, it returns a map containing the asset ID's package and
- /// path:
- ///
- /// "result": {
- /// "package": "myapp",
- /// "path": "web/index.html"
- /// }
- ///
- /// The "path" key in the result is a URL path that's relative to the root
- /// directory of the package identified by "package". The location of this
- /// package may vary depending on which source it was installed from.
- ///
- /// An optional "line" key may be provided whose value must be an integer. If
- /// given, the result will also include a "line" key that maps the line in
- /// the served final file back to the corresponding source line in the asset
- /// that was used to generate that file.
- ///
- /// Examples (where "myapp" is the root package and pub serve is being run
- /// normally with "web" bound to port 8080 and "test" to 8081):
- ///
- /// http://localhost:8080/index.html -> myapp|web/index.html
- /// http://localhost:8081/sub/main.dart -> myapp|test/sub/main.dart
- ///
- /// If the URL is not a domain being served by pub, this returns an error:
- ///
- /// http://localhost:1234/index.html -> NOT_SERVED error
- ///
- /// This does *not* currently support the implicit index.html behavior that
- /// pub serve provides for user-friendliness:
- ///
- /// http://localhost:1234 -> NOT_SERVED error
- ///
- /// This does *not* currently check to ensure the asset actually exists. It
- /// only maps what the corresponding asset *should* be for that URL.
- Future<Map> _urlToAssetId(json_rpc.Parameters params) {
- var url = params["url"].asUri;
-
- // If a line number was given, map it to the output line.
- var line = params["line"].asIntOr(null);
-
- return _environment.getAssetIdForUrl(url).then((id) {
- if (id == null) {
- throw new json_rpc.RpcException(
- _Error.NOT_SERVED,
- '"${url.host}:${url.port}" is not being served by pub.');
- }
-
- // TODO(rnystrom): When this is hooked up to actually talk to barback to
- // see if assets exist, consider supporting implicit index.html at that
- // point.
-
- var result = {
- "package": id.package,
- "path": id.path
- };
-
- // Map the line.
- // TODO(rnystrom): Right now, source maps are not supported and it just
- // passes through the original line. This lets the editor start using
- // this API before we've fully implemented it. See #12339 and #16061.
- if (line != null) result["line"] = line;
-
- return result;
- });
- }
-
- /// Given a path on the filesystem, returns the URLs served by pub that can be
- /// used to access asset found at that path.
- ///
- /// The method name is "pathToUrls" and it takes a "path" key (a native OS
- /// path which may be absolute or relative to the root directory of the
- /// entrypoint package) for the path being mapped:
- ///
- /// "params": {
- /// "path": "web/index.html"
- /// }
- ///
- /// If successful, it returns a map containing the list of URLs that can be
- /// used to access that asset.
- ///
- /// "result": {
- /// "urls": ["http://localhost:8080/index.html"]
- /// }
- ///
- /// The "path" key may refer to a path in another package, either by referring
- /// to its location within the top-level "packages" directory or by referring
- /// to its location on disk. Only the "lib" directory is visible in other
- /// packages:
- ///
- /// "params": {
- /// "path": "packages/http/http.dart"
- /// }
- ///
- /// Assets in the "lib" directory will usually have one URL for each server:
- ///
- /// "result": {
- /// "urls": [
- /// "http://localhost:8080/packages/http/http.dart",
- /// "http://localhost:8081/packages/http/http.dart"
- /// ]
- /// }
- ///
- /// An optional "line" key may be provided whose value must be an integer. If
- /// given, the result will also include a "line" key that maps the line in
- /// the source file to the corresponding output line in the resulting asset
- /// served at the URL.
- ///
- /// Examples (where "myapp" is the root package and pub serve is being run
- /// normally with "web" bound to port 8080 and "test" to 8081):
- ///
- /// web/index.html -> http://localhost:8080/index.html
- /// test/sub/main.dart -> http://localhost:8081/sub/main.dart
- ///
- /// If the asset is not in a directory being served by pub, returns an error:
- ///
- /// example/index.html -> NOT_SERVED error
- Future<Map> _pathToUrls(json_rpc.Parameters params) {
- var assetPath = params["path"].asString;
- var line = params["line"].asIntOr(null);
-
- return _environment.getUrlsForAssetPath(assetPath).then((urls) {
- if (urls.isEmpty) {
- throw new json_rpc.RpcException(
- _Error.NOT_SERVED,
- 'Asset path "$assetPath" is not currently being served.');
- }
-
- var result = {
- "urls": urls.map((url) => url.toString()).toList()
- };
-
- // Map the line.
- // TODO(rnystrom): Right now, source maps are not supported and it just
- // passes through the original line. This lets the editor start using
- // this API before we've fully implemented it. See #12339 and #16061.
- if (line != null) result["line"] = line;
-
- return result;
- });
- }
-
- /// Given a relative directory path within the entrypoint package, binds a
- /// new port to serve from that path and returns its URL.
- ///
- /// The method name is "serveDirectory" and it takes a "path" key (a native
- /// OS path relative to the root of the entrypoint package) for the directory
- /// being served:
- ///
- /// "params": {
- /// "path": "example/awesome"
- /// }
- ///
- /// If successful, it returns a map containing the URL that can be used to
- /// access the directory.
- ///
- /// "result": {
- /// "url": "http://localhost:8083"
- /// }
- ///
- /// If the directory is already being served, returns the previous URL.
- Future<Map> _serveDirectory(json_rpc.Parameters params) {
- var rootDirectory = _validateRelativePath(params, "path");
- return _environment.serveDirectory(rootDirectory).then((server) {
- return {
- "url": server.url.toString()
- };
- }).catchError((error) {
- if (error is! OverlappingSourceDirectoryException) throw error;
-
- var dir = pluralize(
- "directory",
- error.overlappingDirectories.length,
- plural: "directories");
- var overlapping =
- toSentence(error.overlappingDirectories.map((dir) => '"$dir"'));
- print("data: ${error.overlappingDirectories}");
- throw new json_rpc.RpcException(
- _Error.OVERLAPPING,
- 'Path "$rootDirectory" overlaps already served $dir $overlapping.',
- data: {
- "directories": error.overlappingDirectories
- });
- });
- }
-
- /// Given a relative directory path within the entrypoint package, unbinds
- /// the server previously bound to that directory and returns its (now
- /// unreachable) URL.
- ///
- /// The method name is "unserveDirectory" and it takes a "path" key (a
- /// native OS path relative to the root of the entrypoint package) for the
- /// directory being unserved:
- ///
- /// "params": {
- /// "path": "example/awesome"
- /// }
- ///
- /// If successful, it returns a map containing the URL that used to be used
- /// to access the directory.
- ///
- /// "result": {
- /// "url": "http://localhost:8083"
- /// }
- ///
- /// If no server is bound to that directory, it returns a `NOT_SERVED` error.
- Future<Map> _unserveDirectory(json_rpc.Parameters params) {
- var rootDirectory = _validateRelativePath(params, "path");
- return _environment.unserveDirectory(rootDirectory).then((url) {
- if (url == null) {
- throw new json_rpc.RpcException(
- _Error.NOT_SERVED,
- 'Directory "$rootDirectory" is not bound to a server.');
- }
-
- return {
- "url": url.toString()
- };
- });
- }
-
- /// Validates that [command] has a field named [key] whose value is a string
- /// containing a relative path that doesn't reach out of the entrypoint
- /// package's root directory.
- ///
- /// Returns the path if found, or throws a [_WebSocketException] if
- /// validation failed.
- String _validateRelativePath(json_rpc.Parameters params, String key) {
- var pathString = params[key].asString;
-
- if (!path.isRelative(pathString)) {
- throw new json_rpc.RpcException.invalidParams(
- '"$key" must be a relative path. Got "$pathString".');
- }
-
- if (!path.isWithin(".", pathString)) {
- throw new json_rpc.RpcException.invalidParams(
- '"$key" cannot reach out of its containing directory. ' 'Got "$pathString".');
- }
-
- return pathString;
- }
-}
-
-/// The pub-specific JSON RPC error codes.
-class _Error {
- /// The specified directory is not being served.
- static const NOT_SERVED = 1;
-
- /// The specified directory overlaps one or more ones already being served.
- static const OVERLAPPING = 2;
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/cached_package.dart b/sdk/lib/_internal/pub_generated/lib/src/cached_package.dart
deleted file mode 100644
index 1e1c595..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/cached_package.dart
+++ /dev/null
@@ -1,88 +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.
-
-library pub.cached_package;
-
-import 'package:path/path.dart' as p;
-import 'package:pub_semver/pub_semver.dart';
-import 'package:yaml/yaml.dart';
-
-import 'barback/transformer_config.dart';
-import 'io.dart';
-import 'package.dart';
-import 'pubspec.dart';
-
-/// A [Package] whose `lib` directory has been precompiled and cached.
-///
-/// When users of this class request path information about files that are
-/// cached, this returns the cached information. It also wraps the package's
-/// pubspec to report no transformers, since the transformations have all been
-/// applied already.
-class CachedPackage extends Package {
- /// The directory contianing the cached assets from this package.
- ///
- /// Although only `lib` is cached, this directory corresponds to the root of
- /// the package. The actual cached assets exist in `$_cacheDir/lib`.
- final String _cacheDir;
-
- /// Creates a new cached package wrapping [inner] with the cache at
- /// [_cacheDir].
- CachedPackage(Package inner, this._cacheDir)
- : super(new _CachedPubspec(inner.pubspec), inner.dir);
-
- String path(String part1, [String part2, String part3, String part4,
- String part5, String part6, String part7]) {
- if (_pathInCache(part1)) {
- return p.join(_cacheDir, part1, part2, part3, part4, part5, part6, part7);
- } else {
- return super.path(part1, part2, part3, part4, part5, part6, part7);
- }
- }
-
- String relative(String path) {
- if (p.isWithin(path, _cacheDir)) return p.relative(path, from: _cacheDir);
- return super.relative(path);
- }
-
- /// This will include the cached, transformed versions of files if [beneath]
- /// is within a cached directory, but not otherwise.
- List<String> listFiles({String beneath, recursive: true, bool useGitIgnore:
- false}) {
- if (beneath == null) {
- return super.listFiles(recursive: recursive, useGitIgnore: useGitIgnore);
- }
-
- if (_pathInCache(beneath)) return listDir(p.join(_cacheDir, beneath));
- return super.listFiles(
- beneath: beneath,
- recursive: recursive,
- useGitIgnore: useGitIgnore);
- }
-
- /// Returns whether [relativePath], a path relative to the package's root,
- /// is in a cached directory.
- bool _pathInCache(String relativePath) => p.isWithin('lib', relativePath);
-}
-
-/// A pubspec wrapper that reports no transformers.
-class _CachedPubspec implements Pubspec {
- final Pubspec _inner;
-
- YamlMap get fields => _inner.fields;
- String get name => _inner.name;
- Version get version => _inner.version;
- List<PackageDep> get dependencies => _inner.dependencies;
- List<PackageDep> get devDependencies => _inner.devDependencies;
- List<PackageDep> get dependencyOverrides => _inner.dependencyOverrides;
- PubspecEnvironment get environment => _inner.environment;
- String get publishTo => _inner.publishTo;
- Map<String, String> get executables => _inner.executables;
- bool get isPrivate => _inner.isPrivate;
- bool get isEmpty => _inner.isEmpty;
- List<PubspecException> get allErrors => _inner.allErrors;
-
- List<Set<TransformerConfig>> get transformers => const [];
-
- _CachedPubspec(this._inner);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command.dart b/sdk/lib/_internal/pub_generated/lib/src/command.dart
deleted file mode 100644
index 3724b40..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command.dart
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright (c) 2013, 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 pub.command;
-
-import 'package:args/args.dart';
-import 'package:args/command_runner.dart';
-import 'package:path/path.dart' as path;
-
-import 'entrypoint.dart';
-import 'log.dart' as log;
-import 'global_packages.dart';
-import 'system_cache.dart';
-
-/// The base class for commands for the pub executable.
-///
-/// A command may either be a "leaf" command or it may be a parent for a set
-/// of subcommands. Only leaf commands are ever actually invoked. If a command
-/// has subcommands, then one of those must always be chosen.
-abstract class PubCommand extends Command {
- SystemCache get cache {
- if (_cache == null) {
- _cache = new SystemCache.withSources(isOffline: isOffline);
- }
- return _cache;
- }
- SystemCache _cache;
-
- GlobalPackages get globals {
- if (_globals == null) {
- _globals = new GlobalPackages(cache);
- }
- return _globals;
- }
- GlobalPackages _globals;
-
- /// Gets the [Entrypoint] package for the current working directory.
- ///
- /// This will load the pubspec and fail with an error if the current directory
- /// is not a package.
- Entrypoint get entrypoint {
- // Lazy load it.
- if (_entrypoint == null) {
- _entrypoint = new Entrypoint(
- path.current,
- cache,
- packageSymlinks: globalResults['package-symlinks']);
- }
- return _entrypoint;
- }
- Entrypoint _entrypoint;
-
- /// The URL for web documentation for this command.
- String get docUrl => null;
-
- /// Override this and return `false` to disallow trailing options from being
- /// parsed after a non-option argument is parsed.
- bool get allowTrailingOptions => true;
-
- ArgParser get argParser {
- // Lazily initialize the parser because the superclass constructor requires
- // it but we want to initialize it based on [allowTrailingOptions].
- if (_argParser == null) {
- _argParser = new ArgParser(allowTrailingOptions: allowTrailingOptions);
- }
- return _argParser;
- }
- ArgParser _argParser;
-
- /// Override this to use offline-only sources instead of hitting the network.
- ///
- /// This will only be called before the [SystemCache] is created. After that,
- /// it has no effect. This only needs to be set in leaf commands.
- bool get isOffline => false;
-
- String get usageFooter {
- if (docUrl == null) return null;
- return "See $docUrl for detailed documentation.";
- }
-
- void printUsage() {
- log.message(usage);
- }
-
- /// Parses a user-supplied integer [intString] named [name].
- ///
- /// If the parsing fails, prints a usage message and exits.
- int parseInt(String intString, String name) {
- try {
- return int.parse(intString);
- } on FormatException catch (_) {
- usageException('Could not parse $name "$intString".');
- }
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/barback.dart b/sdk/lib/_internal/pub_generated/lib/src/command/barback.dart
deleted file mode 100644
index 5fdc519..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/barback.dart
+++ /dev/null
@@ -1,204 +0,0 @@
-// Copyright (c) 2013, 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 pub.command.barback;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as path;
-
-import '../command.dart';
-import '../io.dart';
-import '../log.dart' as log;
-import '../utils.dart';
-
-final _arrow = getSpecial('\u2192', '=>');
-
-/// The set of top level directories in the entrypoint package that are built
-/// when the user does "--all".
-final _allSourceDirectories =
- new Set<String>.from(["benchmark", "bin", "example", "test", "web"]);
-
-/// Shared base class for [BuildCommand] and [ServeCommand].
-abstract class BarbackCommand extends PubCommand {
- /// The build mode.
- BarbackMode get mode => new BarbackMode(argResults["mode"]);
-
- /// The directories in the entrypoint package that should be added to the
- /// build environment.
- final sourceDirectories = new Set<String>();
-
- /// The default build mode.
- BarbackMode get defaultMode => BarbackMode.RELEASE;
-
- /// Override this to specify the default source directories if none are
- /// provided on the command line.
- List<String> get defaultSourceDirectories;
-
- BarbackCommand() {
- argParser.addOption(
- "mode",
- defaultsTo: defaultMode.toString(),
- help: "Mode to run transformers in.");
-
- argParser.addFlag(
- "all",
- help: "Use all default source directories.",
- defaultsTo: false,
- negatable: false);
- }
-
- Future run() {
- // Switch to JSON output if specified. We need to do this before parsing
- // the source directories so an error will be correctly reported in JSON
- // format.
- log.json.enabled =
- argResults.options.contains("format") && argResults["format"] == "json";
-
- _parseSourceDirectories();
- return onRunTransformerCommand();
- }
-
- /// Override this to run the actual command.
- Future onRunTransformerCommand();
-
- /// Parses the command-line arguments to determine the set of source
- /// directories to add to the build environment.
- ///
- /// If there are no arguments, this will just be [defaultSourceDirectories].
- ///
- /// If the `--all` flag is set, then it will be all default directories
- /// that exist.
- ///
- /// Otherwise, all arguments should be the paths of directories to include.
- ///
- /// Throws an exception if the arguments are invalid.
- void _parseSourceDirectories() {
- if (argResults["all"]) {
- _addAllDefaultSources();
- return;
- }
-
- // If no directories were specified, use the defaults.
- if (argResults.rest.isEmpty) {
- _addDefaultSources();
- return;
- }
-
- sourceDirectories.addAll(argResults.rest);
-
- // Prohibit "lib".
- var disallowed = sourceDirectories.where((dir) {
- var parts = path.split(path.normalize(dir));
- return parts.isNotEmpty && parts.first == "lib";
- });
-
- if (disallowed.isNotEmpty) {
- usageException(
- _directorySentence(disallowed, "is", "are", "not allowed"));
- }
-
- // Make sure the source directories don't reach out of the package.
- var invalid = sourceDirectories.where((dir) => !path.isWithin('.', dir));
- if (invalid.isNotEmpty) {
- usageException(
- _directorySentence(invalid, "isn't", "aren't", "in this package"));
- }
-
- // Make sure all of the source directories exist.
- var missing =
- sourceDirectories.where((dir) => !dirExists(entrypoint.root.path(dir)));
-
- if (missing.isNotEmpty) {
- dataError(_directorySentence(missing, "does", "do", "not exist"));
- }
-
- // Make sure the directories don't overlap.
- var sources = sourceDirectories.toList();
- var overlapping = new Set();
- for (var i = 0; i < sources.length; i++) {
- for (var j = i + 1; j < sources.length; j++) {
- if (path.isWithin(sources[i], sources[j]) ||
- path.isWithin(sources[j], sources[i])) {
- overlapping.add(sources[i]);
- overlapping.add(sources[j]);
- }
- }
- }
-
- if (overlapping.isNotEmpty) {
- usageException(
- _directorySentence(overlapping, "cannot", "cannot", "overlap"));
- }
- }
-
- /// Handles "--all" by adding all default source directories that are
- /// present.
- void _addAllDefaultSources() {
- if (argResults.rest.isNotEmpty) {
- usageException('Directory names are not allowed if "--all" is passed.');
- }
-
- // Include every build directory that exists in the package.
- var dirs =
- _allSourceDirectories.where((dir) => dirExists(entrypoint.root.path(dir)));
-
- if (dirs.isEmpty) {
- var defaultDirs =
- toSentence(_allSourceDirectories.map((name) => '"$name"'));
- dataError(
- 'There are no source directories present.\n'
- 'The default directories are $defaultDirs.');
- }
-
- sourceDirectories.addAll(dirs);
- }
-
- /// Adds the default sources that should be used if no directories are passed
- /// on the command line.
- void _addDefaultSources() {
- sourceDirectories.addAll(
- defaultSourceDirectories.where((dir) => dirExists(entrypoint.root.path(dir))));
-
- // TODO(rnystrom): Hackish. Assumes there will only be one or two
- // default sources. That's true for pub build and serve, but isn't as
- // general as it could be.
- if (sourceDirectories.isEmpty) {
- var defaults;
- if (defaultSourceDirectories.length == 1) {
- defaults = 'a "${defaultSourceDirectories.first}" directory';
- } else {
- defaults =
- '"${defaultSourceDirectories[0]}" and/or '
- '"${defaultSourceDirectories[1]}" directories';
- }
-
- dataError(
- "Your package must have $defaults,\n"
- "or you must specify the source directories.");
- }
- }
-
- /// Converts a list of [directoryNames] to a sentence.
- ///
- /// After the list of directories, [singularVerb] will be used if there is
- /// only one directory and [pluralVerb] will be used if there are more than
- /// one. Then [suffix] is added to the end of the sentence, and, finally, a
- /// period is added.
- String _directorySentence(Iterable<String> directoryNames,
- String singularVerb, String pluralVerb, String suffix) {
- var directories =
- pluralize('Directory', directoryNames.length, plural: 'Directories');
- var names = toSentence(directoryNames.map((dir) => '"$dir"'));
- var verb =
- pluralize(singularVerb, directoryNames.length, plural: pluralVerb);
-
- var result = "$directories $names $verb";
- if (suffix != null) result += " $suffix";
- result += ".";
-
- return result;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/build.dart b/sdk/lib/_internal/pub_generated/lib/src/command/build.dart
deleted file mode 100644
index 80060c8..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/build.dart
+++ /dev/null
@@ -1,275 +0,0 @@
-// Copyright (c) 2013, 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 pub.command.build;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as path;
-
-import '../barback/asset_environment.dart';
-import '../exit_codes.dart' as exit_codes;
-import '../io.dart';
-import '../log.dart' as log;
-import '../utils.dart';
-import 'barback.dart';
-
-final _arrow = getSpecial('\u2192', '=>');
-
-/// Handles the `build` pub command.
-class BuildCommand extends BarbackCommand {
- String get name => "build";
- String get description => "Apply transformers to build a package.";
- String get invocation => "pub build [options] [directories...]";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-build.html";
- List<String> get aliases => const ["deploy", "settle-up"];
-
- /// The path to the application's build output directory.
- String get outputDirectory => argResults["output"];
-
- List<String> get defaultSourceDirectories => ["web"];
-
- /// The number of files that have been built and written to disc so far.
- int builtFiles = 0;
-
- BuildCommand() {
- argParser.addOption(
- "format",
- help: "How output should be displayed.",
- allowed: ["text", "json"],
- defaultsTo: "text");
-
- argParser.addOption(
- "output",
- abbr: "o",
- help: "Directory to write build outputs to.",
- defaultsTo: "build");
- }
-
- Future onRunTransformerCommand() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- cleanDir(outputDirectory);
- var errorsJson = [];
- var logJson = [];
- completer0.complete(
- AssetEnvironment.create(
- entrypoint,
- mode,
- useDart2JS: true).then(((environment) {
- environment.barback.errors.listen((error) {
- log.error(log.red("Build error:\n$error"));
- if (log.json.enabled) {
- errorsJson.add({
- "error": error.toString()
- });
- }
- });
- if (log.json.enabled) {
- environment.barback.log.listen(
- (entry) => logJson.add(_logEntryToJson(entry)));
- }
- return log.progress("Building ${entrypoint.root.name}", () {
- return Future.wait(
- sourceDirectories.map((dir) => environment.serveDirectory(dir))).then((_) {
- return environment.barback.getAllAssets();
- });
- }).then((assets) {
- var dart2JSEntrypoints = assets.where(
- (asset) => asset.id.path.endsWith(".dart.js")).map((asset) => asset.id);
- return Future.wait(assets.map(_writeAsset)).then((_) {
- builtFiles += _copyBrowserJsFiles(dart2JSEntrypoints);
- log.message(
- 'Built $builtFiles ${pluralize('file', builtFiles)} ' 'to "$outputDirectory".');
- log.json.message({
- "buildResult": "success",
- "outputDirectory": outputDirectory,
- "numFiles": builtFiles,
- "log": logJson
- });
- });
- });
- })).catchError(((error) {
- if (error is! BarbackException) throw error;
- log.error(log.red("Build failed."));
- log.json.message({
- "buildResult": "failure",
- "errors": errorsJson,
- "log": logJson
- });
- return flushThenExit(exit_codes.DATA);
- })));
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Writes [asset] to the appropriate build directory.
- ///
- /// If [asset] is in the special "packages" directory, writes it to every
- /// build directory.
- Future _writeAsset(Asset asset) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- var destPath = _idToPath(asset.id);
- join1() {
- completer0.complete(_writeOutputFile(asset, destPath));
- }
- if (path.isWithin("packages", destPath)) {
- completer0.complete(Future.wait(sourceDirectories.map(((buildDir) {
- return _writeOutputFile(asset, path.join(buildDir, destPath));
- }))));
- } else {
- join1();
- }
- }
- if (mode == BarbackMode.RELEASE && asset.id.extension == ".dart") {
- completer0.complete(null);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Converts [id] to a relative path in the output directory for that asset.
- ///
- /// This corresponds to the URL that could be used to request that asset from
- /// pub serve.
- ///
- /// Examples (where entrypoint is "myapp"):
- ///
- /// myapp|web/index.html -> web/index.html
- /// myapp|lib/lib.dart -> packages/myapp/lib.dart
- /// foo|lib/foo.dart -> packages/foo/foo.dart
- /// myapp|test/main.dart -> test/main.dart
- /// foo|test/main.dart -> ERROR
- ///
- /// Throws a [FormatException] if [id] is not a valid public asset.
- String _idToPath(AssetId id) {
- var parts = path.split(path.fromUri(id.path));
-
- if (parts.length < 2) {
- throw new FormatException(
- "Can not build assets from top-level directory.");
- }
-
- // Map "lib" to the "packages" directory.
- if (parts[0] == "lib") {
- return path.join("packages", id.package, path.joinAll(parts.skip(1)));
- }
-
- // Shouldn't be trying to access non-public directories of other packages.
- assert(id.package == entrypoint.root.name);
-
- // Allow any path in the entrypoint package.
- return path.joinAll(parts);
- }
-
- /// Writes the contents of [asset] to [relativePath] within the build
- /// directory.
- Future _writeOutputFile(Asset asset, String relativePath) {
- builtFiles++;
- var destPath = path.join(outputDirectory, relativePath);
- ensureDir(path.dirname(destPath));
- return createFileFromStream(asset.read(), destPath);
- }
-
- /// If this package depends directly on the `browser` package, this ensures
- /// that the JavaScript bootstrap files are copied into `packages/browser/`
- /// directories next to each entrypoint in [entrypoints].
- ///
- /// Returns the number of files it copied.
- int _copyBrowserJsFiles(Iterable<AssetId> entrypoints) {
- // Must depend on the browser package.
- if (!entrypoint.root.immediateDependencies.any(
- (dep) => dep.name == 'browser' && dep.source == 'hosted')) {
- return 0;
- }
-
- // Get all of the subdirectories that contain Dart entrypoints.
- var entrypointDirs =
- entrypoints// Convert the asset path to a native-separated one and get the
- // directory containing the entrypoint.
- .map(
- (id) =>
- path.dirname(
- path.fromUri(
- id.path)))// Don't copy files to the top levels of the build directories since
- // the normal lib asset copying will take care of that.
- .where((dir) => path.split(dir).length > 1).toSet();
-
- for (var dir in entrypointDirs) {
- // TODO(nweiz): we should put browser JS files next to any HTML file
- // rather than any entrypoint. An HTML file could import an entrypoint
- // that's not adjacent.
- _addBrowserJs(dir, "dart");
- _addBrowserJs(dir, "interop");
- }
-
- return entrypointDirs.length * 2;
- }
-
- // TODO(nweiz): do something more principled when issue 6101 is fixed.
- /// Ensures that the [name].js file is copied into [directory] in [target],
- /// under `packages/browser/`.
- void _addBrowserJs(String directory, String name) {
- var jsPath = entrypoint.root.path(
- outputDirectory,
- directory,
- 'packages',
- 'browser',
- '$name.js');
- ensureDir(path.dirname(jsPath));
-
- // TODO(rnystrom): This won't work if we get rid of symlinks and the top
- // level "packages" directory. Will need to copy from the browser
- // directory.
- copyFile(path.join(entrypoint.packagesDir, 'browser', '$name.js'), jsPath);
- }
-
- /// Converts [entry] to a JSON object for use with JSON-formatted output.
- Map _logEntryToJson(LogEntry entry) {
- var data = {
- "level": entry.level.name,
- "transformer": {
- "name": entry.transform.transformer.toString(),
- "primaryInput": {
- "package": entry.transform.primaryId.package,
- "path": entry.transform.primaryId.path
- },
- },
- "assetId": {
- "package": entry.assetId.package,
- "path": entry.assetId.path
- },
- "message": entry.message
- };
-
- if (entry.span != null) {
- data["span"] = {
- "url": entry.span.sourceUrl,
- "start": {
- "line": entry.span.start.line,
- "column": entry.span.start.column
- },
- "end": {
- "line": entry.span.end.line,
- "column": entry.span.end.column
- },
- };
- }
-
- return data;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/cache.dart b/sdk/lib/_internal/pub_generated/lib/src/command/cache.dart
deleted file mode 100644
index 432f096..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/cache.dart
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2013, 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 pub.command.cache;
-
-import '../command.dart';
-import 'cache_add.dart';
-import 'cache_list.dart';
-import 'cache_repair.dart';
-
-/// Handles the `cache` pub command.
-class CacheCommand extends PubCommand {
- String get name => "cache";
- String get description => "Work with the system cache.";
- String get invocation => "pub cache <subcommand>";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-cache.html";
-
- CacheCommand() {
- addSubcommand(new CacheAddCommand());
- addSubcommand(new CacheListCommand());
- addSubcommand(new CacheRepairCommand());
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/cache_add.dart b/sdk/lib/_internal/pub_generated/lib/src/command/cache_add.dart
deleted file mode 100644
index 1ad2646..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/cache_add.dart
+++ /dev/null
@@ -1,96 +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.
-
-library pub.command.cache_add;
-
-import 'dart:async';
-
-import 'package:pub_semver/pub_semver.dart';
-
-import '../command.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../utils.dart';
-
-/// Handles the `cache add` pub command.
-class CacheAddCommand extends PubCommand {
- String get name => "add";
- String get description => "Install a package.";
- String get invocation =>
- "pub cache add <package> [--version <constraint>] [--all]";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-cache.html";
-
- CacheAddCommand() {
- argParser.addFlag(
- "all",
- help: "Install all matching versions.",
- negatable: false);
-
- argParser.addOption("version", abbr: "v", help: "Version constraint.");
- }
-
- Future run() {
- // Make sure there is a package.
- if (argResults.rest.isEmpty) {
- usageException("No package to add given.");
- }
-
- // Don't allow extra arguments.
- if (argResults.rest.length > 1) {
- var unexpected = argResults.rest.skip(1).map((arg) => '"$arg"');
- var arguments = pluralize("argument", unexpected.length);
- usageException("Unexpected $arguments ${toSentence(unexpected)}.");
- }
-
- var package = argResults.rest.single;
-
- // Parse the version constraint, if there is one.
- var constraint = VersionConstraint.any;
- if (argResults["version"] != null) {
- try {
- constraint = new VersionConstraint.parse(argResults["version"]);
- } on FormatException catch (error) {
- usageException(error.message);
- }
- }
-
- // TODO(rnystrom): Support installing from git too.
- var source = cache.sources["hosted"];
-
- // TODO(rnystrom): Allow specifying the server.
- return source.getVersions(package, package).then((versions) {
- versions = versions.where(constraint.allows).toList();
-
- if (versions.isEmpty) {
- // TODO(rnystrom): Show most recent unmatching version?
- fail("Package $package has no versions that match $constraint.");
- }
-
- downloadVersion(Version version) {
- var id = new PackageId(package, source.name, version, package);
- return cache.contains(id).then((contained) {
- if (contained) {
- // TODO(rnystrom): Include source and description if not hosted.
- // See solve_report.dart for code to harvest.
- log.message("Already cached ${id.name} ${id.version}.");
- return null;
- }
-
- // Download it.
- return source.downloadToSystemCache(id);
- });
- }
-
- if (argResults["all"]) {
- // Install them in ascending order.
- versions.sort();
- return Future.forEach(versions, downloadVersion);
- } else {
- // Pick the best matching version.
- versions.sort(Version.prioritize);
- return downloadVersion(versions.last);
- }
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/cache_list.dart b/sdk/lib/_internal/pub_generated/lib/src/command/cache_list.dart
deleted file mode 100644
index 78f7e8a..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/cache_list.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, 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 pub.command.cache_list;
-
-import 'dart:convert';
-
-import '../command.dart';
-import '../log.dart' as log;
-import '../source/cached.dart';
-
-/// Handles the `cache list` pub command.
-class CacheListCommand extends PubCommand {
- String get name => "list";
- String get description => "List packages in the system cache.";
- String get invocation => "pub cache list";
- bool get hidden => true;
- bool get takesArguments => false;
-
- void run() {
- // TODO(keertip): Add flag to list packages from non default sources.
- var packagesObj = <String, Map>{};
-
- var source = cache.sources.defaultSource as CachedSource;
- for (var package in source.getCachedPackages()) {
- var packageInfo = packagesObj.putIfAbsent(package.name, () => {});
- packageInfo[package.version.toString()] = {
- 'location': package.dir
- };
- }
-
- // TODO(keertip): Add support for non-JSON format and check for --format
- // flag.
- log.message(JSON.encode({
- 'packages': packagesObj
- }));
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/cache_repair.dart b/sdk/lib/_internal/pub_generated/lib/src/command/cache_repair.dart
deleted file mode 100644
index 5b1e13c..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/cache_repair.dart
+++ /dev/null
@@ -1,143 +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.
-
-library pub.command.cache_repair;
-
-import 'dart:async';
-
-import '../command.dart';
-import '../exit_codes.dart' as exit_codes;
-import '../io.dart';
-import '../log.dart' as log;
-import '../source/cached.dart';
-import '../utils.dart';
-
-/// Handles the `cache repair` pub command.
-class CacheRepairCommand extends PubCommand {
- String get name => "repair";
- String get description => "Reinstall cached packages.";
- String get invocation => "pub cache repair";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-cache.html";
- bool get takesArguments => false;
-
- Future run() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var successes = 0;
- var failures = 0;
- var it0 = cache.sources.iterator;
- break0() {
- join0() {
- join1() {
- new Future.value(globals.repairActivatedPackages()).then((x0) {
- try {
- var results = x0;
- join2() {
- join3() {
- join4() {
- join5() {
- completer0.complete();
- }
- if (failures > 0) {
- new Future.value(
- flushThenExit(exit_codes.UNAVAILABLE)).then((x1) {
- try {
- x1;
- join5();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } else {
- join5();
- }
- }
- if (successes == 0 && failures == 0) {
- log.message(
- "No packages in cache, so nothing to repair.");
- join4();
- } else {
- join4();
- }
- }
- if (results.last > 0) {
- var packages = pluralize("package", results.last);
- log.message(
- "Failed to reactivate ${log.red(results.last)} ${packages}.");
- join3();
- } else {
- join3();
- }
- }
- if (results.first > 0) {
- var packages = pluralize("package", results.first);
- log.message(
- "Reactivated ${log.green(results.first)} ${packages}.");
- join2();
- } else {
- join2();
- }
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- }
- if (failures > 0) {
- var packages = pluralize("package", failures);
- log.message(
- "Failed to reinstall ${log.red(failures)} ${packages}.");
- join1();
- } else {
- join1();
- }
- }
- if (successes > 0) {
- var packages = pluralize("package", successes);
- log.message("Reinstalled ${log.green(successes)} ${packages}.");
- join0();
- } else {
- join0();
- }
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var source = it0.current;
- join6() {
- new Future.value(source.repairCachedPackages()).then((x2) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- var results = x2;
- successes += results.first;
- failures += results.last;
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } catch (e2, s2) {
- completer0.completeError(e2, s2);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: completer0.completeError);
- }
- if (source is! CachedSource) {
- continue0();
- } else {
- join6();
- }
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/deps.dart b/sdk/lib/_internal/pub_generated/lib/src/command/deps.dart
deleted file mode 100644
index ce5bcdd..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/deps.dart
+++ /dev/null
@@ -1,204 +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.
-
-library pub.command.list;
-
-import 'dart:async';
-import 'dart:collection';
-
-import '../ascii_tree.dart' as tree;
-import '../command.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../package_graph.dart';
-import '../utils.dart';
-
-/// Handles the `deps` pub command.
-class DepsCommand extends PubCommand {
- String get name => "deps";
- String get description => "Print package dependencies.";
- List<String> get aliases => const ["dependencies", "tab"];
- String get invocation => "pub deps";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-deps.html";
- bool get takesArguments => false;
-
- /// The loaded package graph.
- PackageGraph _graph;
-
- /// The [StringBuffer] used to accumulate the output.
- StringBuffer _buffer;
-
- DepsCommand() {
- argParser.addOption(
- "style",
- abbr: "s",
- help: "How output should be displayed.",
- allowed: ["compact", "tree", "list"],
- defaultsTo: "tree");
- }
-
- Future run() {
- return entrypoint.loadPackageGraph().then((graph) {
- _graph = graph;
- _buffer = new StringBuffer();
-
- _buffer.writeln(_labelPackage(entrypoint.root));
-
- switch (argResults["style"]) {
- case "compact":
- _outputCompact();
- break;
- case "list":
- _outputList();
- break;
- case "tree":
- _outputTree();
- break;
- }
-
- log.message(_buffer);
- });
- }
-
- /// Outputs a list of all of the package's immediate, dev, override, and
- /// transitive dependencies.
- ///
- /// For each dependency listed, *that* package's immediate dependencies are
- /// shown. Unlike [_outputList], this prints all of these dependencies on one
- /// line.
- void _outputCompact() {
- var root = entrypoint.root;
- _outputCompactPackages(
- "dependencies",
- root.dependencies.map((dep) => dep.name));
- _outputCompactPackages(
- "dev dependencies",
- root.devDependencies.map((dep) => dep.name));
- _outputCompactPackages(
- "dependency overrides",
- root.dependencyOverrides.map((dep) => dep.name));
-
- var transitive = _getTransitiveDependencies();
- _outputCompactPackages("transitive dependencies", transitive);
- }
-
- /// Outputs one section of packages in the compact output.
- _outputCompactPackages(String section, Iterable<String> names) {
- if (names.isEmpty) return;
-
- _buffer.writeln();
- _buffer.writeln("$section:");
- for (var name in ordered(names)) {
- var package = _graph.packages[name];
-
- _buffer.write("- ${_labelPackage(package)}");
- if (package.dependencies.isEmpty) {
- _buffer.writeln();
- } else {
- var depNames = package.dependencies.map((dep) => dep.name);
- var depsList = "[${depNames.join(' ')}]";
- _buffer.writeln(" ${log.gray(depsList)}");
- }
- }
- }
-
- /// Outputs a list of all of the package's immediate, dev, override, and
- /// transitive dependencies.
- ///
- /// For each dependency listed, *that* package's immediate dependencies are
- /// shown.
- void _outputList() {
- var root = entrypoint.root;
- _outputListSection(
- "dependencies",
- root.dependencies.map((dep) => dep.name));
- _outputListSection(
- "dev dependencies",
- root.devDependencies.map((dep) => dep.name));
- _outputListSection(
- "dependency overrides",
- root.dependencyOverrides.map((dep) => dep.name));
-
- var transitive = _getTransitiveDependencies();
- if (transitive.isEmpty) return;
-
- _outputListSection("transitive dependencies", ordered(transitive));
- }
-
- /// Outputs one section of packages in the list output.
- _outputListSection(String name, Iterable<String> deps) {
- if (deps.isEmpty) return;
-
- _buffer.writeln();
- _buffer.writeln("$name:");
-
- for (var name in deps) {
- var package = _graph.packages[name];
- _buffer.writeln("- ${_labelPackage(package)}");
-
- for (var dep in package.dependencies) {
- _buffer.writeln(
- " - ${log.bold(dep.name)} ${log.gray(dep.constraint)}");
- }
- }
- }
-
- /// Generates a dependency tree for the root package.
- ///
- /// If a package is encountered more than once (i.e. a shared or circular
- /// dependency), later ones are not traversed. This is done in breadth-first
- /// fashion so that a package will always be expanded at the shallowest
- /// depth that it appears at.
- void _outputTree() {
- // The work list for the breadth-first traversal. It contains the package
- // being added to the tree, and the parent map that will receive that
- // package.
- var toWalk = new Queue<Pair<Package, Map>>();
- var visited = new Set<String>();
-
- // Start with the root dependencies.
- var packageTree = {};
- for (var dep in entrypoint.root.immediateDependencies) {
- toWalk.add(new Pair(_graph.packages[dep.name], packageTree));
- }
-
- // Do a breadth-first walk to the dependency graph.
- while (toWalk.isNotEmpty) {
- var pair = toWalk.removeFirst();
- var package = pair.first;
- var map = pair.last;
-
- if (visited.contains(package.name)) {
- map[log.gray('${package.name}...')] = {};
- continue;
- }
-
- visited.add(package.name);
-
- // Populate the map with this package's dependencies.
- var childMap = {};
- map[_labelPackage(package)] = childMap;
-
- for (var dep in package.dependencies) {
- toWalk.add(new Pair(_graph.packages[dep.name], childMap));
- }
- }
-
- _buffer.write(tree.fromMap(packageTree, showAllChildren: true));
- }
-
- String _labelPackage(Package package) =>
- "${log.bold(package.name)} ${package.version}";
-
- /// Gets the names of the non-immediate dependencies of the root package.
- Set<String> _getTransitiveDependencies() {
- var transitive = _graph.packages.keys.toSet();
- var root = entrypoint.root;
- transitive.remove(root.name);
- transitive.removeAll(root.dependencies.map((dep) => dep.name));
- transitive.removeAll(root.devDependencies.map((dep) => dep.name));
- transitive.removeAll(root.dependencyOverrides.map((dep) => dep.name));
- return transitive;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/downgrade.dart b/sdk/lib/_internal/pub_generated/lib/src/command/downgrade.dart
deleted file mode 100644
index 8736402..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/downgrade.dart
+++ /dev/null
@@ -1,68 +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 pub.command.downgrade;
-
-import 'dart:async';
-
-import '../command.dart';
-import '../log.dart' as log;
-import '../solver/version_solver.dart';
-
-/// Handles the `downgrade` pub command.
-class DowngradeCommand extends PubCommand {
- String get name => "downgrade";
- String get description =>
- "Downgrade the current package's dependencies to oldest versions.\n\n"
- "This doesn't modify the lockfile, so it can be reset with \"pub get\".";
- String get invocation => "pub downgrade [dependencies...]";
-
- bool get isOffline => argResults['offline'];
-
- DowngradeCommand() {
- argParser.addFlag(
- 'offline',
- help: 'Use cached packages instead of accessing the network.');
-
- argParser.addFlag(
- 'dry-run',
- abbr: 'n',
- negatable: false,
- help: "Report what dependencies would change but don't change any.");
- }
-
- Future run() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var dryRun = argResults['dry-run'];
- new Future.value(
- entrypoint.acquireDependencies(
- SolveType.DOWNGRADE,
- useLatest: argResults.rest,
- dryRun: dryRun)).then((x0) {
- try {
- x0;
- join0() {
- completer0.complete();
- }
- if (isOffline) {
- log.warning(
- "Warning: Downgrading when offline may not update you to "
- "the oldest versions of your dependencies.");
- join0();
- } else {
- join0();
- }
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/get.dart b/sdk/lib/_internal/pub_generated/lib/src/command/get.dart
deleted file mode 100644
index 70f7518..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/get.dart
+++ /dev/null
@@ -1,38 +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 pub.command.get;
-
-import 'dart:async';
-
-import '../command.dart';
-import '../solver/version_solver.dart';
-
-/// Handles the `get` pub command.
-class GetCommand extends PubCommand {
- String get name => "get";
- String get description => "Get the current package's dependencies.";
- String get invocation => "pub get";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-get.html";
- List<String> get aliases => const ["install"];
- bool get isOffline => argResults["offline"];
-
- GetCommand() {
- argParser.addFlag(
- 'offline',
- help: 'Use cached packages instead of accessing the network.');
-
- argParser.addFlag(
- 'dry-run',
- abbr: 'n',
- negatable: false,
- help: "Report what dependencies would change but don't change any.");
- }
-
- Future run() {
- return entrypoint.acquireDependencies(
- SolveType.GET,
- dryRun: argResults['dry-run']);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global.dart
deleted file mode 100644
index c2ddfd8..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/global.dart
+++ /dev/null
@@ -1,25 +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.
-
-library pub.command.global;
-
-import '../command.dart';
-import 'global_activate.dart';
-import 'global_deactivate.dart';
-import 'global_list.dart';
-import 'global_run.dart';
-
-/// Handles the `global` pub command.
-class GlobalCommand extends PubCommand {
- String get name => "global";
- String get description => "Work with global packages.";
- String get invocation => "pub global <subcommand>";
-
- GlobalCommand() {
- addSubcommand(new GlobalActivateCommand());
- addSubcommand(new GlobalDeactivateCommand());
- addSubcommand(new GlobalListCommand());
- addSubcommand(new GlobalRunCommand());
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global_activate.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global_activate.dart
deleted file mode 100644
index f567f4b..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/global_activate.dart
+++ /dev/null
@@ -1,117 +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.
-
-library pub.command.global_activate;
-
-import 'dart:async';
-
-import 'package:pub_semver/pub_semver.dart';
-
-import '../command.dart';
-import '../utils.dart';
-
-/// Handles the `global activate` pub command.
-class GlobalActivateCommand extends PubCommand {
- String get name => "activate";
- String get description => "Make a package's executables globally available.";
- String get invocation => "pub global activate <package...>";
-
- GlobalActivateCommand() {
- argParser.addOption(
- "source",
- abbr: "s",
- help: "The source used to find the package.",
- allowed: ["git", "hosted", "path"],
- defaultsTo: "hosted");
-
- argParser.addFlag(
- "no-executables",
- negatable: false,
- help: "Do not put executables on PATH.");
-
- argParser.addOption(
- "executable",
- abbr: "x",
- help: "Executable(s) to place on PATH.",
- allowMultiple: true);
-
- argParser.addFlag(
- "overwrite",
- negatable: false,
- help: "Overwrite executables from other packages with the same name.");
- }
-
- Future run() {
- // Default to `null`, which means all executables.
- var executables;
- if (argResults.wasParsed("executable")) {
- if (argResults.wasParsed("no-executables")) {
- usageException("Cannot pass both --no-executables and --executable.");
- }
-
- executables = argResults["executable"];
- } else if (argResults["no-executables"]) {
- // An empty list means no executables.
- executables = [];
- }
-
- var overwrite = argResults["overwrite"];
- var args = argResults.rest;
-
- readArg([String error]) {
- if (args.isEmpty) usageException(error);
- var arg = args.first;
- args = args.skip(1);
- return arg;
- }
-
- validateNoExtraArgs() {
- if (args.isEmpty) return;
- var unexpected = args.map((arg) => '"$arg"');
- var arguments = pluralize("argument", unexpected.length);
- usageException("Unexpected $arguments ${toSentence(unexpected)}.");
- }
-
- switch (argResults["source"]) {
- case "git":
- var repo = readArg("No Git repository given.");
- // TODO(rnystrom): Allow passing in a Git ref too.
- validateNoExtraArgs();
- return globals.activateGit(
- repo,
- executables,
- overwriteBinStubs: overwrite);
-
- case "hosted":
- var package = readArg("No package to activate given.");
-
- // Parse the version constraint, if there is one.
- var constraint = VersionConstraint.any;
- if (args.isNotEmpty) {
- try {
- constraint = new VersionConstraint.parse(readArg());
- } on FormatException catch (error) {
- usageException(error.message);
- }
- }
-
- validateNoExtraArgs();
- return globals.activateHosted(
- package,
- constraint,
- executables,
- overwriteBinStubs: overwrite);
-
- case "path":
- var path = readArg("No package to activate given.");
- validateNoExtraArgs();
- return globals.activatePath(
- path,
- executables,
- overwriteBinStubs: overwrite);
- }
-
- throw "unreachable";
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global_deactivate.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global_deactivate.dart
deleted file mode 100644
index 595f6ff..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/global_deactivate.dart
+++ /dev/null
@@ -1,36 +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.
-
-library pub.command.global_deactivate;
-
-import 'dart:async';
-
-import '../command.dart';
-import '../log.dart' as log;
-import '../utils.dart';
-
-/// Handles the `global deactivate` pub command.
-class GlobalDeactivateCommand extends PubCommand {
- String get name => "deactivate";
- String get description => "Remove a previously activated package.";
- String get invocation => "pub global deactivate <package>";
-
- void run() {
- // Make sure there is a package.
- if (argResults.rest.isEmpty) {
- usageException("No package to deactivate given.");
- }
-
- // Don't allow extra arguments.
- if (argResults.rest.length > 1) {
- var unexpected = argResults.rest.skip(1).map((arg) => '"$arg"');
- var arguments = pluralize("argument", unexpected.length);
- usageException("Unexpected $arguments ${toSentence(unexpected)}.");
- }
-
- if (!globals.deactivate(argResults.rest.first)) {
- dataError("No active package ${log.bold(argResults.rest.first)}.");
- }
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global_list.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global_list.dart
deleted file mode 100644
index 1de1073..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/global_list.dart
+++ /dev/null
@@ -1,22 +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.
-
-library pub.command.global_list;
-
-import 'dart:async';
-
-import '../command.dart';
-
-/// Handles the `global list` pub command.
-class GlobalListCommand extends PubCommand {
- String get name => "list";
- String get description => 'List globally activated packages.';
- String get invocation => 'pub global list';
- bool get allowTrailingOptions => false;
- bool get takesArguments => false;
-
- void run() {
- globals.listActivePackages();
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global_run.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global_run.dart
deleted file mode 100644
index 54874c1..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/global_run.dart
+++ /dev/null
@@ -1,92 +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.
-
-library pub.command.global_run;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-
-import '../command.dart';
-import '../io.dart';
-import '../utils.dart';
-
-/// Handles the `global run` pub command.
-class GlobalRunCommand extends PubCommand {
- String get name => "run";
- String get description =>
- "Run an executable from a globally activated package.\n"
- "NOTE: We are currently optimizing this command's startup time.";
- String get invocation => "pub global run <package>:<executable> [args...]";
- bool get allowTrailingOptions => false;
-
- /// The mode for barback transformers.
- BarbackMode get mode => new BarbackMode(argResults["mode"]);
-
- GlobalRunCommand() {
- argParser.addOption(
- "mode",
- defaultsTo: "release",
- help: 'Mode to run transformers in.');
- }
-
- Future run() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- var package;
- var executable = argResults.rest[0];
- join1() {
- var args = argResults.rest.skip(1).toList();
- join2() {
- new Future.value(
- globals.runExecutable(package, executable, args, mode: mode)).then((x0) {
- try {
- var exitCode = x0;
- new Future.value(flushThenExit(exitCode)).then((x1) {
- try {
- x1;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- }
- if (p.split(executable).length > 1) {
- usageException(
- 'Cannot run an executable in a subdirectory of a global ' + 'package.');
- join2();
- } else {
- join2();
- }
- }
- if (executable.contains(":")) {
- var parts = split1(executable, ":");
- package = parts[0];
- executable = parts[1];
- join1();
- } else {
- package = executable;
- join1();
- }
- }
- if (argResults.rest.isEmpty) {
- usageException("Must specify an executable to run.");
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/lish.dart b/sdk/lib/_internal/pub_generated/lib/src/command/lish.dart
deleted file mode 100644
index ef5840e..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/lish.dart
+++ /dev/null
@@ -1,200 +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 pub.command.lish;
-
-import 'dart:async';
-
-import 'package:http/http.dart' as http;
-
-import '../command.dart';
-import '../ascii_tree.dart' as tree;
-import '../http.dart';
-import '../io.dart';
-import '../log.dart' as log;
-import '../oauth2.dart' as oauth2;
-import '../source/hosted.dart';
-import '../utils.dart';
-import '../validator.dart';
-
-/// Handles the `lish` and `publish` pub commands.
-class LishCommand extends PubCommand {
- String get name => "publish";
- String get description => "Publish the current package to pub.dartlang.org.";
- String get invocation => "pub publish [options]";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-lish.html";
- List<String> get aliases => const ["lish", "lush"];
- bool get takesArguments => false;
-
- /// The URL of the server to which to upload the package.
- Uri get server {
- // An explicit argument takes precedence.
- if (argResults.wasParsed('server')) {
- return Uri.parse(argResults['server']);
- }
-
- // Otherwise, use the one specified in the pubspec.
- if (entrypoint.root.pubspec.publishTo != null) {
- return Uri.parse(entrypoint.root.pubspec.publishTo);
- }
-
- // Otherwise, use the default.
- return Uri.parse(HostedSource.defaultUrl);
- }
-
- /// Whether the publish is just a preview.
- bool get dryRun => argResults['dry-run'];
-
- /// Whether the publish requires confirmation.
- bool get force => argResults['force'];
-
- LishCommand() {
- argParser.addFlag(
- 'dry-run',
- abbr: 'n',
- negatable: false,
- help: 'Validate but do not publish the package.');
- argParser.addFlag(
- 'force',
- abbr: 'f',
- negatable: false,
- help: 'Publish without confirmation if there are no errors.');
- argParser.addOption(
- 'server',
- defaultsTo: HostedSource.defaultUrl,
- help: 'The package server to which to upload this package.');
- }
-
- Future _publish(packageBytes) {
- var cloudStorageUrl;
- return oauth2.withClient(cache, (client) {
- return log.progress('Uploading', () {
- // TODO(nweiz): Cloud Storage can provide an XML-formatted error. We
- // should report that error and exit.
- var newUri = server.resolve("/api/packages/versions/new");
- return client.get(newUri, headers: PUB_API_HEADERS).then((response) {
- var parameters = parseJsonResponse(response);
-
- var url = _expectField(parameters, 'url', response);
- if (url is! String) invalidServerResponse(response);
- cloudStorageUrl = Uri.parse(url);
- var request = new http.MultipartRequest('POST', cloudStorageUrl);
- request.headers['Pub-Request-Timeout'] = 'None';
-
- var fields = _expectField(parameters, 'fields', response);
- if (fields is! Map) invalidServerResponse(response);
- fields.forEach((key, value) {
- if (value is! String) invalidServerResponse(response);
- request.fields[key] = value;
- });
-
- request.followRedirects = false;
- request.files.add(
- new http.MultipartFile.fromBytes(
- 'file',
- packageBytes,
- filename: 'package.tar.gz'));
- return client.send(request);
- }).then(http.Response.fromStream).then((response) {
- var location = response.headers['location'];
- if (location == null) throw new PubHttpException(response);
- return location;
- }).then(
- (location) =>
- client.get(location, headers: PUB_API_HEADERS)).then(handleJsonSuccess);
- });
- }).catchError((error) {
- if (error is! PubHttpException) throw error;
- var url = error.response.request.url;
- if (urisEqual(url, cloudStorageUrl)) {
- // TODO(nweiz): the response may have XML-formatted information about
- // the error. Try to parse that out once we have an easily-accessible
- // XML parser.
- fail('Failed to upload the package.');
- } else if (urisEqual(Uri.parse(url.origin), Uri.parse(server.origin))) {
- handleJsonError(error.response);
- } else {
- throw error;
- }
- });
- }
-
- Future run() {
- if (force && dryRun) {
- usageException('Cannot use both --force and --dry-run.');
- }
-
- if (entrypoint.root.pubspec.isPrivate) {
- dataError(
- 'A private package cannot be published.\n'
- 'You can enable this by changing the "publish_to" field in your ' 'pubspec.');
- }
-
- var files = entrypoint.root.listFiles(useGitIgnore: true);
- log.fine('Archiving and publishing ${entrypoint.root}.');
-
- // Show the package contents so the user can verify they look OK.
- var package = entrypoint.root;
- log.message(
- 'Publishing ${package.name} ${package.version} to $server:\n'
- '${tree.fromFiles(files, baseDir: entrypoint.root.dir)}');
-
- var packageBytesFuture =
- createTarGz(files, baseDir: entrypoint.root.dir).toBytes();
-
- // Validate the package.
- return _validate(
- packageBytesFuture.then((bytes) => bytes.length)).then((isValid) {
- if (isValid) return packageBytesFuture.then(_publish);
- });
- }
-
- /// Returns the value associated with [key] in [map]. Throws a user-friendly
- /// error if [map] doens't contain [key].
- _expectField(Map map, String key, http.Response response) {
- if (map.containsKey(key)) return map[key];
- invalidServerResponse(response);
- }
-
- /// Validates the package. Completes to false if the upload should not
- /// proceed.
- Future<bool> _validate(Future<int> packageSize) {
- return Validator.runAll(entrypoint, packageSize).then((pair) {
- var errors = pair.first;
- var warnings = pair.last;
-
- if (!errors.isEmpty) {
- log.error(
- "Sorry, your package is missing "
- "${(errors.length > 1) ? 'some requirements' : 'a requirement'} "
- "and can't be published yet.\nFor more information, see: "
- "http://pub.dartlang.org/doc/pub-lish.html.\n");
- return false;
- }
-
- if (force) return true;
-
- if (dryRun) {
- var s = warnings.length == 1 ? '' : 's';
- log.warning("\nPackage has ${warnings.length} warning$s.");
- return false;
- }
-
- var message = '\nLooks great! Are you ready to upload your package';
-
- if (!warnings.isEmpty) {
- var s = warnings.length == 1 ? '' : 's';
- message = "\nPackage has ${warnings.length} warning$s. Upload anyway";
- }
-
- return confirm(message).then((confirmed) {
- if (!confirmed) {
- log.error("Package upload canceled.");
- return false;
- }
- return true;
- });
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/list_package_dirs.dart b/sdk/lib/_internal/pub_generated/lib/src/command/list_package_dirs.dart
deleted file mode 100644
index c68d8e0..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/list_package_dirs.dart
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright (c) 2013, 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 pub.command.list_package_dirs;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-import '../command.dart';
-import '../log.dart' as log;
-import '../utils.dart';
-
-/// Handles the `list-package-dirs` pub command.
-class ListPackageDirsCommand extends PubCommand {
- String get name => "list-package-dirs";
- String get description => "Print local paths to dependencies.";
- String get invocation => "pub list-package-dirs";
- bool get takesArguments => false;
- bool get hidden => true;
-
- ListPackageDirsCommand() {
- argParser.addOption(
- "format",
- help: "How output should be displayed.",
- allowed: ["json"]);
- }
-
- Future run() {
- log.json.enabled = true;
-
- if (!entrypoint.lockFileExists) {
- dataError('Package "myapp" has no lockfile. Please run "pub get" first.');
- }
-
- var output = {};
-
- // Include the local paths to all locked packages.
- var packages = {};
- var futures = [];
- entrypoint.lockFile.packages.forEach((name, package) {
- var source = entrypoint.cache.sources[package.source];
- futures.add(source.getDirectory(package).then((packageDir) {
- packages[name] = path.join(packageDir, "lib");
- }));
- });
-
- output["packages"] = packages;
-
- // Include the self link.
- packages[entrypoint.root.name] = entrypoint.root.path("lib");
-
- // Include the file(s) which when modified will affect the results. For pub,
- // that's just the pubspec and lockfile.
- output["input_files"] = [entrypoint.lockFilePath, entrypoint.pubspecPath];
-
- return Future.wait(futures).then((_) {
- log.json.message(output);
- });
- }
-}
-
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/run.dart b/sdk/lib/_internal/pub_generated/lib/src/command/run.dart
deleted file mode 100644
index 0d63daf..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/run.dart
+++ /dev/null
@@ -1,107 +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.
-
-library pub.command.run;
-
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-
-import '../command.dart';
-import '../executable.dart';
-import '../io.dart';
-import '../utils.dart';
-
-/// Handles the `run` pub command.
-class RunCommand extends PubCommand {
- String get name => "run";
- String get description =>
- "Run an executable from a package.\n"
- "NOTE: We are currently optimizing this command's startup time.";
- String get invocation => "pub run <executable> [args...]";
- bool get allowTrailingOptions => false;
-
- RunCommand() {
- argParser.addOption(
- "mode",
- help: 'Mode to run transformers in.\n'
- '(defaults to "release" for dependencies, "debug" for ' 'entrypoint)');
- }
-
- Future run() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- var package = entrypoint.root.name;
- var executable = argResults.rest[0];
- var args = argResults.rest.skip(1).toList();
- join1() {
- var mode;
- join2() {
- new Future.value(
- runExecutable(entrypoint, package, executable, args, mode: mode)).then((x0) {
- try {
- var exitCode = x0;
- new Future.value(flushThenExit(exitCode)).then((x1) {
- try {
- x1;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- }
- if (argResults['mode'] != null) {
- mode = new BarbackMode(argResults['mode']);
- join2();
- } else {
- join3() {
- join2();
- }
- if (package == entrypoint.root.name) {
- mode = BarbackMode.DEBUG;
- join3();
- } else {
- mode = BarbackMode.RELEASE;
- join3();
- }
- }
- }
- if (executable.contains(":")) {
- var components = split1(executable, ":");
- package = components[0];
- executable = components[1];
- join4() {
- join1();
- }
- if (p.split(executable).length > 1) {
- usageException(
- "Cannot run an executable in a subdirectory of a " + "dependency.");
- join4();
- } else {
- join4();
- }
- } else {
- join1();
- }
- }
- if (argResults.rest.isEmpty) {
- usageException("Must specify an executable to run.");
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/serve.dart b/sdk/lib/_internal/pub_generated/lib/src/command/serve.dart
deleted file mode 100644
index 5c5062b..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/serve.dart
+++ /dev/null
@@ -1,264 +0,0 @@
-// Copyright (c) 2013, 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 pub.command.serve;
-
-import 'dart:async';
-import 'dart:math' as math;
-
-import 'package:barback/barback.dart';
-
-import '../barback/asset_environment.dart';
-import '../barback/pub_package_provider.dart';
-import '../log.dart' as log;
-import '../utils.dart';
-import 'barback.dart';
-
-final _arrow = getSpecial('\u2192', '=>');
-
-/// Handles the `serve` pub command.
-class ServeCommand extends BarbackCommand {
- String get name => "serve";
- String get description =>
- 'Run a local web development server.\n\n'
- 'By default, this serves "web/" and "test/", but an explicit list of \n'
- 'directories to serve can be provided as well.';
- String get invocation => "pub serve [directories...]";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-serve.html";
-
- PubPackageProvider _provider;
-
- String get hostname => argResults['hostname'];
-
- /// The base port for the servers.
- ///
- /// This will print a usage error and exit if the specified port is invalid.
- int get port => parseInt(argResults['port'], 'port');
-
- /// The port for the admin UI.
- ///
- /// This will print a usage error and exit if the specified port is invalid.
- int get adminPort {
- var adminPort = argResults['admin-port'];
- return adminPort == null ? null : parseInt(adminPort, 'admin port');
- }
-
- /// `true` if Dart entrypoints should be compiled to JavaScript.
- bool get useDart2JS => argResults['dart2js'];
-
- /// `true` if the admin server URL should be displayed on startup.
- bool get logAdminUrl => argResults['log-admin-url'];
-
- BarbackMode get defaultMode => BarbackMode.DEBUG;
-
- List<String> get defaultSourceDirectories => ["web", "test"];
-
- /// This completer is used to keep pub running (by not completing) and to
- /// pipe fatal errors to pub's top-level error-handling machinery.
- final _completer = new Completer();
-
- ServeCommand() {
- argParser.addOption(
- 'hostname',
- defaultsTo: 'localhost',
- help: 'The hostname to listen on.');
- argParser.addOption(
- 'port',
- defaultsTo: '8080',
- help: 'The base port to listen on.');
-
- // TODO(rnystrom): A hidden option to print the URL that the admin server
- // is bound to on startup. Since this is currently only used for the Web
- // Socket interface, we don't want to show it to users, but the tests and
- // Editor need this logged to know what port to bind to.
- // Remove this (and always log) when #16954 is fixed.
- argParser.addFlag('log-admin-url', defaultsTo: false, hide: true);
-
- // TODO(nweiz): Make this public when issue 16954 is fixed.
- argParser.addOption('admin-port', hide: true);
-
- argParser.addFlag(
- 'dart2js',
- defaultsTo: true,
- help: 'Compile Dart to JavaScript.');
- argParser.addFlag(
- 'force-poll',
- defaultsTo: false,
- help: 'Force the use of a polling filesystem watcher.');
- }
-
- Future onRunTransformerCommand() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var port = parseInt(argResults['port'], 'port');
- join0(x0) {
- var adminPort = x0;
- join1(x1) {
- var watcherType = x1;
- new Future.value(
- AssetEnvironment.create(
- entrypoint,
- mode,
- watcherType: watcherType,
- hostname: hostname,
- basePort: port,
- useDart2JS: useDart2JS)).then((x2) {
- try {
- var environment = x2;
- var directoryLength = sourceDirectories.map(((dir) {
- return dir.length;
- })).reduce(math.max);
- new Future.value(
- environment.startAdminServer(adminPort)).then((x3) {
- try {
- var server = x3;
- server.results.listen(((_) {
- assert(false);
- }), onError: _fatalError);
- join2() {
- environment.pauseUpdates();
- var it0 = sourceDirectories.iterator;
- break0() {
- environment.barback.errors.listen(((error) {
- log.error(log.red("Build error:\n$error"));
- }));
- environment.barback.results.listen(((result) {
- if (result.succeeded) {
- log.message(
- "Build completed ${log.green('successfully')}");
- } else {
- log.message(
- "Build completed with " "${log.red(result.errors.length)} errors.");
- }
- }), onError: _fatalError);
- environment.resumeUpdates();
- new Future.value(_completer.future).then((x4) {
- try {
- x4;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var directory = it0.current;
- new Future.value(
- _startServer(environment, directory, directoryLength)).then((x5) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- x5;
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: completer0.completeError);
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- if (logAdminUrl) {
- log.message(
- "Running admin server on " "${log.bold('http://${hostname}:${server.port}')}");
- join2();
- } else {
- join2();
- }
- } catch (e2, s2) {
- completer0.completeError(e2, s2);
- }
- }, onError: completer0.completeError);
- } catch (e3, s3) {
- completer0.completeError(e3, s3);
- }
- }, onError: completer0.completeError);
- }
- if (argResults['force-poll']) {
- join1(WatcherType.POLLING);
- } else {
- join1(WatcherType.AUTO);
- }
- }
- if (argResults['admin-port'] == null) {
- join0(null);
- } else {
- join0(parseInt(argResults['admin-port'], 'admin port'));
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- Future _startServer(AssetEnvironment environment, String rootDirectory,
- int directoryLength) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(environment.serveDirectory(rootDirectory)).then((x0) {
- try {
- var server = x0;
- join0() {
- var prefix =
- log.gray(padRight("[${server.rootDirectory}]", directoryLength + 2));
- server.results.listen(((result) {
- var buffer = new StringBuffer();
- buffer.write("$prefix ");
- if (result.isSuccess) {
- buffer.write(
- "${log.green('GET')} ${result.url.path} $_arrow ${result.id}");
- } else {
- buffer.write("${log.red('GET')} ${result.url.path} $_arrow");
- var error = result.error.toString();
- if (error.contains("\n")) {
- buffer.write("\n${prefixLines(error)}");
- } else {
- buffer.write(" $error");
- }
- }
- log.message(buffer);
- }), onError: _fatalError);
- log.message(
- "Serving ${entrypoint.root.name} "
- "${padRight(server.rootDirectory, directoryLength)} "
- "on ${log.bold('http://${hostname}:${server.port}')}");
- completer0.complete();
- }
- if (mode == BarbackMode.RELEASE) {
- server.allowAsset = ((url) {
- return !url.path.endsWith(".dart");
- });
- join0();
- } else {
- join0();
- }
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Reports [error] and exits the server.
- void _fatalError(error, [stackTrace]) {
- if (_completer.isCompleted) return;
- _completer.completeError(error, stackTrace);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/upgrade.dart b/sdk/lib/_internal/pub_generated/lib/src/command/upgrade.dart
deleted file mode 100644
index e7f2159..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/upgrade.dart
+++ /dev/null
@@ -1,69 +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 pub.command.upgrade;
-
-import 'dart:async';
-
-import '../command.dart';
-import '../log.dart' as log;
-import '../solver/version_solver.dart';
-
-/// Handles the `upgrade` pub command.
-class UpgradeCommand extends PubCommand {
- String get name => "upgrade";
- String get description =>
- "Upgrade the current package's dependencies to latest versions.";
- String get invocation => "pub upgrade [dependencies...]";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-upgrade.html";
- List<String> get aliases => const ["update"];
-
- bool get isOffline => argResults['offline'];
-
- UpgradeCommand() {
- argParser.addFlag(
- 'offline',
- help: 'Use cached packages instead of accessing the network.');
-
- argParser.addFlag(
- 'dry-run',
- abbr: 'n',
- negatable: false,
- help: "Report what dependencies would change but don't change any.");
- }
-
- Future run() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var dryRun = argResults['dry-run'];
- new Future.value(
- entrypoint.acquireDependencies(
- SolveType.UPGRADE,
- useLatest: argResults.rest,
- dryRun: dryRun)).then((x0) {
- try {
- x0;
- join0() {
- completer0.complete();
- }
- if (isOffline) {
- log.warning(
- "Warning: Upgrading when offline may not update you to the "
- "latest versions of your dependencies.");
- join0();
- } else {
- join0();
- }
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/uploader.dart b/sdk/lib/_internal/pub_generated/lib/src/command/uploader.dart
deleted file mode 100644
index e43bbae..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/uploader.dart
+++ /dev/null
@@ -1,88 +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 pub.command.uploader;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-import '../command.dart';
-import '../entrypoint.dart';
-import '../exit_codes.dart' as exit_codes;
-import '../http.dart';
-import '../io.dart';
-import '../log.dart' as log;
-import '../oauth2.dart' as oauth2;
-import '../source/hosted.dart';
-
-/// Handles the `uploader` pub command.
-class UploaderCommand extends PubCommand {
- String get name => "uploader";
- String get description =>
- "Manage uploaders for a package on pub.dartlang.org.";
- String get invocation => "pub uploader [options] {add/remove} <email>";
- String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-uploader.html";
-
- /// The URL of the package hosting server.
- Uri get server => Uri.parse(argResults['server']);
-
- UploaderCommand() {
- argParser.addOption(
- 'server',
- defaultsTo: HostedSource.defaultUrl,
- help: 'The package server on which the package is hosted.');
- argParser.addOption(
- 'package',
- help: 'The package whose uploaders will be modified.\n'
- '(defaults to the current package)');
- }
-
- Future run() {
- if (argResults.rest.isEmpty) {
- log.error('No uploader command given.');
- this.printUsage();
- return flushThenExit(exit_codes.USAGE);
- }
-
- var rest = argResults.rest.toList();
-
- // TODO(rnystrom): Use subcommands for these.
- var command = rest.removeAt(0);
- if (!['add', 'remove'].contains(command)) {
- log.error('Unknown uploader command "$command".');
- this.printUsage();
- return flushThenExit(exit_codes.USAGE);
- } else if (rest.isEmpty) {
- log.error('No uploader given for "pub uploader $command".');
- this.printUsage();
- return flushThenExit(exit_codes.USAGE);
- }
-
- return new Future.sync(() {
- var package = argResults['package'];
- if (package != null) return package;
- return new Entrypoint(path.current, cache).root.name;
- }).then((package) {
- var uploader = rest[0];
- return oauth2.withClient(cache, (client) {
- if (command == 'add') {
- var url =
- server.resolve("/api/packages/" "${Uri.encodeComponent(package)}/uploaders");
- return client.post(url, headers: PUB_API_HEADERS, body: {
- "email": uploader
- });
- } else { // command == 'remove'
- var url = server.resolve(
- "/api/packages/" "${Uri.encodeComponent(package)}/uploaders/"
- "${Uri.encodeComponent(uploader)}");
- return client.delete(url, headers: PUB_API_HEADERS);
- }
- });
- }).then(
- handleJsonSuccess).catchError(
- (error) => handleJsonError(error.response),
- test: (e) => e is PubHttpException);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/version.dart b/sdk/lib/_internal/pub_generated/lib/src/command/version.dart
deleted file mode 100644
index de40572..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command/version.dart
+++ /dev/null
@@ -1,20 +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 pub.command.version;
-
-import '../command.dart';
-import '../log.dart' as log;
-import '../sdk.dart' as sdk;
-
-/// Handles the `version` pub command.
-class VersionCommand extends PubCommand {
- String get name => "version";
- String get description => "Print pub version.";
- String get invocation => "pub version";
-
- void run() {
- log.message("Pub ${sdk.version}");
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/command_runner.dart b/sdk/lib/_internal/pub_generated/lib/src/command_runner.dart
deleted file mode 100644
index 6bb6153..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/command_runner.dart
+++ /dev/null
@@ -1,339 +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.
-
-library pub.command_runner;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:args/args.dart';
-import 'package:args/command_runner.dart';
-import 'package:http/http.dart' as http;
-import 'package:stack_trace/stack_trace.dart';
-
-import 'command/build.dart';
-import 'command/cache.dart';
-import 'command/deps.dart';
-import 'command/downgrade.dart';
-import 'command/get.dart';
-import 'command/global.dart';
-import 'command/lish.dart';
-import 'command/list_package_dirs.dart';
-import 'command/run.dart';
-import 'command/serve.dart';
-import 'command/upgrade.dart';
-import 'command/uploader.dart';
-import 'command/version.dart';
-import 'exceptions.dart';
-import 'exit_codes.dart' as exit_codes;
-import 'http.dart';
-import 'io.dart';
-import 'log.dart' as log;
-import 'sdk.dart' as sdk;
-import 'solver/version_solver.dart';
-import 'utils.dart';
-
-class PubCommandRunner extends CommandRunner {
- String get usageFooter =>
- "See http://dartlang.org/tools/pub for detailed " "documentation.";
-
- PubCommandRunner()
- : super("pub", "Pub is a package manager for Dart.") {
- argParser.addFlag('version', negatable: false, help: 'Print pub version.');
- argParser.addFlag(
- 'trace',
- help: 'Print debugging information when an error occurs.');
- argParser.addOption(
- 'verbosity',
- help: 'Control output verbosity.',
- allowed: ['normal', 'io', 'solver', 'all'],
- allowedHelp: {
- 'normal': 'Show errors, warnings, and user messages.',
- 'io': 'Also show IO operations.',
- 'solver': 'Show steps during version resolution.',
- 'all': 'Show all output including internal tracing messages.'
- });
- argParser.addFlag(
- 'verbose',
- abbr: 'v',
- negatable: false,
- help: 'Shortcut for "--verbosity=all".');
- argParser.addFlag(
- 'with-prejudice',
- hide: !isAprilFools,
- negatable: false,
- help: 'Execute commands with prejudice.');
- argParser.addFlag(
- 'package-symlinks',
- hide: true,
- negatable: true,
- defaultsTo: true);
-
- addCommand(new BuildCommand());
- addCommand(new CacheCommand());
- addCommand(new DepsCommand());
- addCommand(new DowngradeCommand());
- addCommand(new GlobalCommand());
- addCommand(new GetCommand());
- addCommand(new ListPackageDirsCommand());
- addCommand(new LishCommand());
- addCommand(new RunCommand());
- addCommand(new ServeCommand());
- addCommand(new UpgradeCommand());
- addCommand(new UploaderCommand());
- addCommand(new VersionCommand());
- }
-
- Future run(List<String> arguments) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var options;
- join0() {
- new Future.value(runCommand(options)).then((x0) {
- try {
- x0;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- catch0(error, s1) {
- try {
- if (error is UsageException) {
- log.error(error.message);
- new Future.value(flushThenExit(exit_codes.USAGE)).then((x1) {
- try {
- x1;
- join0();
- } catch (e1, s2) {
- completer0.completeError(e1, s2);
- }
- }, onError: completer0.completeError);
- } else {
- throw error;
- }
- } catch (error, s1) {
- completer0.completeError(error, s1);
- }
- }
- try {
- options = super.parse(arguments);
- join0();
- } catch (e2, s3) {
- catch0(e2, s3);
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- Future runCommand(ArgResults options) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- log.withPrejudice = options['with-prejudice'];
- join0() {
- join1() {
- break0() {
- log.fine('Pub ${sdk.version}');
- new Future.value(_validatePlatform()).then((x0) {
- try {
- x0;
- var captureStackChains =
- options['trace'] ||
- options['verbose'] ||
- options['verbosity'] == 'all';
- join2() {
- completer0.complete();
- }
- catch0(error, chain) {
- try {
- log.exception(error, chain);
- join3() {
- new Future.value(
- flushThenExit(_chooseExitCode(error))).then((x1) {
- try {
- x1;
- join2();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (options['trace']) {
- log.dumpTranscript();
- join3();
- } else {
- join4() {
- join3();
- }
- if (!isUserFacingException(error)) {
- log.error("""
-This is an unexpected error. Please run
-
- pub --trace ${options.arguments.map(((arg) {
- return "'$arg'";
- })).join(' ')}
-
-and include the results in a bug report on http://dartbug.com/new.
-""");
- join4();
- } else {
- join4();
- }
- }
- } catch (error, chain) {
- completer0.completeError(error, chain);
- }
- }
- try {
- new Future.value(captureErrors((() {
- return super.runCommand(options);
- }), captureStackChains: captureStackChains)).then((x2) {
- try {
- x2;
- new Future.value(
- flushThenExit(exit_codes.SUCCESS)).then((x3) {
- try {
- x3;
- join2();
- } catch (e1, s1) {
- catch0(e1, s1);
- }
- }, onError: catch0);
- } catch (e2, s2) {
- catch0(e2, s2);
- }
- }, onError: catch0);
- } catch (e3, s3) {
- catch0(e3, s3);
- }
- } catch (e4, s4) {
- completer0.completeError(e4, s4);
- }
- }, onError: completer0.completeError);
- }
- switch (options['verbosity']) {
- case 'normal':
- log.verbosity = log.Verbosity.NORMAL;
- break0();
- break;
- case 'io':
- log.verbosity = log.Verbosity.IO;
- break0();
- break;
- case 'solver':
- log.verbosity = log.Verbosity.SOLVER;
- break0();
- break;
- case 'all':
- log.verbosity = log.Verbosity.ALL;
- break0();
- break;
- default:
- join5() {
- break0();
- }
- if (options['verbose']) {
- log.verbosity = log.Verbosity.ALL;
- join5();
- } else {
- join5();
- }
- break;
- }
- }
- if (options['trace']) {
- log.recordTranscript();
- join1();
- } else {
- join1();
- }
- }
- if (options['version']) {
- log.message('Pub ${sdk.version}');
- completer0.complete(null);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- void printUsage() {
- log.message(usage);
- }
-
- /// Returns the appropriate exit code for [exception], falling back on 1 if no
- /// appropriate exit code could be found.
- int _chooseExitCode(exception) {
- while (exception is WrappedException) exception = exception.innerError;
-
- if (exception is HttpException ||
- exception is http.ClientException ||
- exception is SocketException ||
- exception is PubHttpException ||
- exception is DependencyNotFoundException) {
- return exit_codes.UNAVAILABLE;
- } else if (exception is FormatException || exception is DataException) {
- return exit_codes.DATA;
- } else if (exception is UsageException) {
- return exit_codes.USAGE;
- } else {
- return 1;
- }
- }
-
- /// Checks that pub is running on a supported platform.
- ///
- /// If it isn't, it prints an error message and exits. Completes when the
- /// validation is done.
- Future _validatePlatform() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- new Future.value(runProcess('ver', [])).then((x0) {
- try {
- var result = x0;
- join1() {
- completer0.complete();
- }
- if (result.stdout.join('\n').contains('XP')) {
- log.error('Sorry, but pub is not supported on Windows XP.');
- new Future.value(flushThenExit(exit_codes.USAGE)).then((x1) {
- try {
- x1;
- join1();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } else {
- join1();
- }
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- }
- if (Platform.operatingSystem != 'windows') {
- completer0.complete(null);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/dart.dart b/sdk/lib/_internal/pub_generated/lib/src/dart.dart
deleted file mode 100644
index 2f83268..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/dart.dart
+++ /dev/null
@@ -1,323 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// A library for compiling Dart code and manipulating analyzer parse trees.
-library pub.dart;
-
-import 'dart:async';
-import 'dart:io';
-import 'dart:isolate';
-
-import 'package:analyzer/analyzer.dart';
-import 'package:path/path.dart' as path;
-
-import '../../../../../../pkg/compiler/lib/compiler.dart' as compiler;
-import '../../../../../../pkg/compiler/lib/src/filenames.dart' show appendSlash;
-
-import '../../asset/dart/serialize.dart';
-import 'io.dart';
-import 'log.dart' as log;
-
-/// Interface to communicate with dart2js.
-///
-/// This is basically an amalgamation of dart2js's
-/// [compiler.CompilerInputProvider], [compiler.CompilerOutputProvider], and
-/// [compiler.DiagnosticHandler] function types so that we can provide them
-/// as a single unit.
-abstract class CompilerProvider {
- /// The URI to the root directory where "dart:" libraries can be found.
- ///
- /// This is used as the base URL to generate library URLs that are then sent
- /// back to [provideInput].
- Uri get libraryRoot;
-
- /// Given [uri], responds with a future that completes to the contents of
- /// the input file at that URI.
- ///
- /// The future can complete to a string or a list of bytes.
- Future /*<String | List<int>>*/ provideInput(Uri uri);
-
- /// Reports a diagnostic message from dart2js to the user.
- void handleDiagnostic(Uri uri, int begin, int end, String message,
- compiler.Diagnostic kind);
-
- /// Given a [name] (which will be "" for the entrypoint) and a file extension,
- /// returns an [EventSink] that dart2js can write to to emit an output file.
- EventSink<String> provideOutput(String name, String extension);
-}
-
-/// Compiles [entrypoint] to JavaScript (or to Dart if [toDart] is true) as
-/// well as any ancillary outputs dart2js creates.
-///
-/// Uses [provider] to communcate between dart2js and the caller. Returns a
-/// future that completes when compilation is done.
-///
-/// By default, the package root is assumed to be adjacent to [entrypoint], but
-/// if [packageRoot] is passed that will be used instead.
-Future compile(String entrypoint, CompilerProvider provider,
- {Iterable<String> commandLineOptions, bool checked: false, bool csp: false,
- bool minify: true, bool verbose: false, Map<String, String> environment,
- String packageRoot, bool analyzeAll: false, bool preserveUris: false,
- bool suppressWarnings: false, bool suppressHints: false,
- bool suppressPackageWarnings: true, bool terse: false,
- bool includeSourceMapUrls: false, bool toDart: false}) {
- return new Future.sync(() {
- var options = <String>['--categories=Client,Server'];
- if (checked) options.add('--enable-checked-mode');
- if (csp) options.add('--csp');
- if (minify) options.add('--minify');
- if (verbose) options.add('--verbose');
- if (analyzeAll) options.add('--analyze-all');
- if (preserveUris) options.add('--preserve-uris');
- if (suppressWarnings) options.add('--suppress-warnings');
- if (suppressHints) options.add('--suppress-hints');
- if (!suppressPackageWarnings) options.add('--show-package-warnings');
- if (terse) options.add('--terse');
- if (toDart) options.add('--output-type=dart');
-
- var sourceUrl = path.toUri(entrypoint);
- options.add("--out=$sourceUrl.js");
-
- // Add the source map URLs.
- if (includeSourceMapUrls) {
- options.add("--source-map=$sourceUrl.js.map");
- }
-
- if (environment == null) environment = {};
- if (commandLineOptions != null) options.addAll(commandLineOptions);
-
- if (packageRoot == null) {
- packageRoot = path.join(path.dirname(entrypoint), 'packages');
- }
-
- return compiler.compile(
- path.toUri(entrypoint),
- provider.libraryRoot,
- path.toUri(appendSlash(packageRoot)),
- provider.provideInput,
- provider.handleDiagnostic,
- options,
- provider.provideOutput,
- environment);
- });
-}
-
-/// Returns whether [dart] looks like an entrypoint file.
-bool isEntrypoint(CompilationUnit dart) {
- // Allow two or fewer arguments so that entrypoints intended for use with
- // [spawnUri] get counted.
- //
- // TODO(nweiz): this misses the case where a Dart file doesn't contain main(),
- // but it parts in another file that does.
- return dart.declarations.any((node) {
- return node is FunctionDeclaration &&
- node.name.name == "main" &&
- node.functionExpression.parameters.parameters.length <= 2;
- });
-}
-
-/// Efficiently parses the import and export directives in [contents].
-///
-/// If [name] is passed, it's used as the filename for error reporting.
-List<UriBasedDirective> parseImportsAndExports(String contents, {String name}) {
- var collector = new _DirectiveCollector();
- parseDirectives(contents, name: name).accept(collector);
- return collector.directives;
-}
-
-/// A simple visitor that collects import and export nodes.
-class _DirectiveCollector extends GeneralizingAstVisitor {
- final directives = <UriBasedDirective>[];
-
- visitUriBasedDirective(UriBasedDirective node) => directives.add(node);
-}
-
-/// Runs [code] in an isolate.
-///
-/// [code] should be the contents of a Dart entrypoint. It may contain imports;
-/// they will be resolved in the same context as the host isolate. [message] is
-/// passed to the [main] method of the code being run; the caller is responsible
-/// for using this to establish communication with the isolate.
-///
-/// [packageRoot] controls the package root of the isolate. It may be either a
-/// [String] or a [Uri].
-///
-/// If [snapshot] is passed, the isolate will be loaded from that path if it
-/// exists. Otherwise, a snapshot of the isolate's code will be saved to that
-/// path once the isolate is loaded.
-Future runInIsolate(String code, message, {packageRoot, String snapshot}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- new Future.value(withTempDir(((dir) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var dartPath = path.join(dir, 'runInIsolate.dart');
- writeTextFile(dartPath, code, dontLogContents: true);
- var port = new ReceivePort();
- join0(x0) {
- new Future.value(Isolate.spawn(_isolateBuffer, {
- 'replyTo': port.sendPort,
- 'uri': path.toUri(dartPath).toString(),
- 'packageRoot': x0,
- 'message': message
- })).then((x1) {
- try {
- x1;
- new Future.value(port.first).then((x2) {
- try {
- var response = x2;
- join1() {
- join2() {
- ensureDir(path.dirname(snapshot));
- var snapshotArgs = [];
- join3() {
- snapshotArgs.addAll(
- ['--snapshot=${snapshot}', dartPath]);
- new Future.value(
- runProcess(Platform.executable, snapshotArgs)).then((x3) {
- try {
- var result = x3;
- join4() {
- log.warning(
- "Failed to compile a snapshot to " "${path.relative(snapshot)}:\n" +
- result.stderr.join("\n"));
- completer0.complete();
- }
- if (result.success) {
- completer0.complete(null);
- } else {
- join4();
- }
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (packageRoot != null) {
- snapshotArgs.add('--package-root=${packageRoot}');
- join3();
- } else {
- join3();
- }
- }
- if (snapshot == null) {
- completer0.complete(null);
- } else {
- join2();
- }
- }
- if (response['type'] == 'error') {
- throw new CrossIsolateException.deserialize(
- response['error']);
- join1();
- } else {
- join1();
- }
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } catch (e2, s2) {
- completer0.completeError(e2, s2);
- }
- }, onError: completer0.completeError);
- }
- if (packageRoot == null) {
- join0(null);
- } else {
- join0(packageRoot.toString());
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }))).then((x0) {
- try {
- x0;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (snapshot != null && fileExists(snapshot)) {
- log.fine("Spawning isolate from ${snapshot}.");
- join1() {
- join2() {
- join0();
- }
- catch0(error, s1) {
- try {
- if (error is IsolateSpawnException) {
- log.fine(
- "Couldn't load existing snapshot ${snapshot}:\n${error}");
- join2();
- } else {
- throw error;
- }
- } catch (error, s1) {
- completer0.completeError(error, s1);
- }
- }
- try {
- new Future.value(
- Isolate.spawnUri(
- path.toUri(snapshot),
- [],
- message,
- packageRoot: packageRoot)).then((x1) {
- try {
- x1;
- completer0.complete(null);
- } catch (e1, s2) {
- catch0(e1, s2);
- }
- }, onError: catch0);
- } catch (e2, s3) {
- catch0(e2, s3);
- }
- }
- if (packageRoot != null) {
- packageRoot = packageRoot.toString();
- join1();
- } else {
- join1();
- }
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
-}
-
-// TODO(nweiz): remove this when issue 12617 is fixed.
-/// A function used as a buffer between the host isolate and [spawnUri].
-///
-/// [spawnUri] synchronously loads the file and its imports, which can deadlock
-/// the host isolate if there's an HTTP import pointing at a server in the host.
-/// Adding an additional isolate in the middle works around this.
-void _isolateBuffer(message) {
- var replyTo = message['replyTo'];
- var packageRoot = message['packageRoot'];
- if (packageRoot != null) packageRoot = Uri.parse(packageRoot);
- Isolate.spawnUri(
- Uri.parse(message['uri']),
- [],
- message['message'],
- packageRoot: packageRoot).then((_) => replyTo.send({
- 'type': 'success'
- })).catchError((e, stack) {
- replyTo.send({
- 'type': 'error',
- 'error': CrossIsolateException.serialize(e, stack)
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/entrypoint.dart b/sdk/lib/_internal/pub_generated/lib/src/entrypoint.dart
deleted file mode 100644
index 2ae51dc..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/entrypoint.dart
+++ /dev/null
@@ -1,951 +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 pub.entrypoint;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-import 'package:barback/barback.dart';
-
-import 'barback/asset_environment.dart';
-import 'io.dart';
-import 'lock_file.dart';
-import 'log.dart' as log;
-import 'package.dart';
-import 'package_graph.dart';
-import 'sdk.dart' as sdk;
-import 'solver/version_solver.dart';
-import 'source/cached.dart';
-import 'system_cache.dart';
-import 'utils.dart';
-
-/// The context surrounding the root package pub is operating on.
-///
-/// Pub operates over a directed graph of dependencies that starts at a root
-/// "entrypoint" package. This is typically the package where the current
-/// working directory is located. An entrypoint knows the [root] package it is
-/// associated with and is responsible for managing the "packages" directory
-/// for it.
-///
-/// That directory contains symlinks to all packages used by an app. These links
-/// point either to the [SystemCache] or to some other location on the local
-/// filesystem.
-///
-/// While entrypoints are typically applications, a pure library package may end
-/// up being used as an entrypoint. Also, a single package may be used as an
-/// entrypoint in one context but not in another. For example, a package that
-/// contains a reusable library may not be the entrypoint when used by an app,
-/// but may be the entrypoint when you're running its tests.
-class Entrypoint {
- /// The root package this entrypoint is associated with.
- final Package root;
-
- /// The system-wide cache which caches packages that need to be fetched over
- /// the network.
- final SystemCache cache;
-
- /// Whether to create and symlink a "packages" directory containing links to
- /// the installed packages.
- final bool _packageSymlinks;
-
- /// The lockfile for the entrypoint.
- ///
- /// If not provided to the entrypoint, it will be laoded lazily from disc.
- LockFile _lockFile;
-
- /// The graph of all packages reachable from the entrypoint.
- PackageGraph _packageGraph;
-
- /// Loads the entrypoint from a package at [rootDir].
- ///
- /// If [packageSymlinks] is `true`, this will create a "packages" directory
- /// with symlinks to the installed packages. This directory will be symlinked
- /// into any directory that might contain an entrypoint.
- Entrypoint(String rootDir, SystemCache cache, {bool packageSymlinks: true})
- : root = new Package.load(null, rootDir, cache.sources),
- cache = cache,
- _packageSymlinks = packageSymlinks;
-
- /// Creates an entrypoint given package and lockfile objects.
- Entrypoint.inMemory(this.root, this._lockFile, this.cache)
- : _packageSymlinks = false;
-
- /// The path to the entrypoint's "packages" directory.
- String get packagesDir => root.path('packages');
-
- /// `true` if the entrypoint package currently has a lock file.
- bool get lockFileExists => _lockFile != null || entryExists(lockFilePath);
-
- LockFile get lockFile {
- if (_lockFile != null) return _lockFile;
-
- if (!lockFileExists) {
- _lockFile = new LockFile.empty();
- } else {
- _lockFile = new LockFile.load(lockFilePath, cache.sources);
- }
-
- return _lockFile;
- }
-
- /// The path to the entrypoint package's pubspec.
- String get pubspecPath => root.path('pubspec.yaml');
-
- /// The path to the entrypoint package's lockfile.
- String get lockFilePath => root.path('pubspec.lock');
-
- /// Gets all dependencies of the [root] package.
- ///
- /// Performs version resolution according to [SolveType].
- ///
- /// [useLatest], if provided, defines a list of packages that will be
- /// unlocked and forced to their latest versions. If [upgradeAll] is
- /// true, the previous lockfile is ignored and all packages are re-resolved
- /// from scratch. Otherwise, it will attempt to preserve the versions of all
- /// previously locked packages.
- ///
- /// Shows a report of the changes made relative to the previous lockfile. If
- /// this is an upgrade or downgrade, all transitive dependencies are shown in
- /// the report. Otherwise, only dependencies that were changed are shown. If
- /// [dryRun] is `true`, no physical changes are made.
- Future acquireDependencies(SolveType type, {List<String> useLatest,
- bool dryRun: false}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(
- resolveVersions(
- type,
- cache.sources,
- root,
- lockFile: lockFile,
- useLatest: useLatest)).then((x0) {
- try {
- var result = x0;
- join0() {
- result.showReport(type);
- join1() {
- join2() {
- new Future.value(
- Future.wait(result.packages.map(_get))).then((x1) {
- try {
- var ids = x1;
- _saveLockFile(ids);
- join3() {
- _linkOrDeleteSecondaryPackageDirs();
- result.summarizeChanges(type, dryRun: dryRun);
- new Future.value(loadPackageGraph(result)).then((x2) {
- try {
- var packageGraph = x2;
- packageGraph.loadTransformerCache().clearIfOutdated(
- result.changedPackages);
- join4() {
- completer0.complete();
- }
- catch0(error, stackTrace) {
- try {
- log.exception(error, stackTrace);
- join4();
- } catch (error, stackTrace) {
- completer0.completeError(error, stackTrace);
- }
- }
- try {
- new Future.value(
- precompileDependencies(changed: result.changedPackages)).then((x3) {
- try {
- x3;
- new Future.value(
- precompileExecutables(changed: result.changedPackages)).then((x4) {
- try {
- x4;
- join4();
- } catch (e0, s0) {
- catch0(e0, s0);
- }
- }, onError: catch0);
- } catch (e1, s1) {
- catch0(e1, s1);
- }
- }, onError: catch0);
- } catch (e2, s2) {
- catch0(e2, s2);
- }
- } catch (e3, s3) {
- completer0.completeError(e3, s3);
- }
- }, onError: completer0.completeError);
- }
- if (_packageSymlinks) {
- _linkSelf();
- join3();
- } else {
- join3();
- }
- } catch (e4, s4) {
- completer0.completeError(e4, s4);
- }
- }, onError: completer0.completeError);
- }
- if (_packageSymlinks) {
- cleanDir(packagesDir);
- join2();
- } else {
- deleteEntry(packagesDir);
- join2();
- }
- }
- if (dryRun) {
- result.summarizeChanges(type, dryRun: dryRun);
- completer0.complete(null);
- } else {
- join1();
- }
- }
- if (!result.succeeded) {
- throw result.error;
- join0();
- } else {
- join0();
- }
- } catch (e5, s5) {
- completer0.completeError(e5, s5);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Precompile any transformed dependencies of the entrypoint.
- ///
- /// If [changed] is passed, only dependencies whose contents might be changed
- /// if one of the given packages changes will be recompiled.
- Future precompileDependencies({Iterable<String> changed}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- new Future.value(loadPackageGraph()).then((x0) {
- try {
- var graph = x0;
- var depsDir = path.join('.pub', 'deps', 'debug');
- var dependenciesToPrecompile =
- graph.packages.values.where(((package) {
- if (package.pubspec.transformers.isEmpty) return false;
- if (graph.isPackageMutable(package.name)) return false;
- if (!dirExists(path.join(depsDir, package.name))) return true;
- if (changed == null) return true;
- return overlaps(
- graph.transitiveDependencies(
- package.name).map((package) => package.name).toSet(),
- changed);
- })).map(((package) {
- return package.name;
- })).toSet();
- join1() {
- join2() {
- join3() {
- completer0.complete();
- }
- catch0(_, s0) {
- try {
- var it0 = dependenciesToPrecompile.iterator;
- break0() {
- completer0.completeError(_, s0);
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var package = it0.current;
- deleteEntry(path.join(depsDir, package));
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } catch (_, s0) {
- completer0.completeError(_, s0);
- }
- }
- try {
- new Future.value(
- log.progress("Precompiling dependencies", (() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var packagesToLoad = unionAll(
- dependenciesToPrecompile.map(graph.transitiveDependencies)).map(((package) {
- return package.name;
- })).toSet();
- new Future.value(
- AssetEnvironment.create(
- this,
- BarbackMode.DEBUG,
- packages: packagesToLoad,
- useDart2JS: false)).then((x0) {
- try {
- var environment = x0;
- environment.barback.errors.listen(((_) {
- }));
- new Future.value(
- environment.barback.getAllAssets()).then((x1) {
- try {
- var assets = x1;
- new Future.value(
- waitAndPrintErrors(assets.map(((asset) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- var destPath =
- path.join(depsDir, asset.id.package, path.fromUri(asset.id.path));
- ensureDir(path.dirname(destPath));
- new Future.value(
- createFileFromStream(asset.read(), destPath)).then((x0) {
- try {
- x0;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (!dependenciesToPrecompile.contains(
- asset.id.package)) {
- completer0.complete(null);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x2) {
- try {
- x2;
- log.message(
- "Precompiled " +
- toSentence(ordered(dependenciesToPrecompile).map(log.bold)) +
- ".");
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } catch (e2, s2) {
- completer0.completeError(e2, s2);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }))).then((x1) {
- try {
- x1;
- join3();
- } catch (e0, s1) {
- catch0(e0, s1);
- }
- }, onError: catch0);
- } catch (e1, s2) {
- catch0(e1, s2);
- }
- }
- if (dependenciesToPrecompile.isEmpty) {
- completer0.complete(null);
- } else {
- join2();
- }
- }
- if (dirExists(depsDir)) {
- var it1 = dependenciesToPrecompile.iterator;
- break1() {
- var it2 = listDir(depsDir).iterator;
- break2() {
- join1();
- }
- var trampoline2;
- continue2() {
- trampoline2 = null;
- if (it2.moveNext()) {
- var subdir = it2.current;
- var package = graph.packages[path.basename(subdir)];
- join4() {
- trampoline2 = continue2;
- do trampoline2(); while (trampoline2 != null);
- }
- if (package == null ||
- package.pubspec.transformers.isEmpty ||
- graph.isPackageMutable(package.name)) {
- deleteEntry(subdir);
- join4();
- } else {
- join4();
- }
- } else {
- break2();
- }
- }
- trampoline2 = continue2;
- do trampoline2(); while (trampoline2 != null);
- }
- var trampoline1;
- continue1() {
- trampoline1 = null;
- if (it1.moveNext()) {
- var package = it1.current;
- deleteEntry(path.join(depsDir, package));
- trampoline1 = continue1;
- do trampoline1(); while (trampoline1 != null);
- } else {
- break1();
- }
- }
- trampoline1 = continue1;
- do trampoline1(); while (trampoline1 != null);
- } else {
- join1();
- }
- } catch (e2, s3) {
- completer0.completeError(e2, s3);
- }
- }, onError: completer0.completeError);
- }
- if (changed != null) {
- changed = changed.toSet();
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Precompiles all executables from dependencies that don't transitively
- /// depend on [this] or on a path dependency.
- Future precompileExecutables({Iterable<String> changed}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- var binDir = path.join('.pub', 'bin');
- var sdkVersionPath = path.join(binDir, 'sdk-version');
- var sdkMatches =
- fileExists(sdkVersionPath) &&
- readTextFile(sdkVersionPath) == "${sdk.version}\n";
- join1() {
- new Future.value(loadPackageGraph()).then((x0) {
- try {
- var graph = x0;
- var executables =
- new Map.fromIterable(root.immediateDependencies, key: ((dep) {
- return dep.name;
- }), value: ((dep) {
- return _executablesForPackage(graph, dep.name, changed);
- }));
- var it0 = executables.keys.toList().iterator;
- break0() {
- join2() {
- join3() {
- new Future.value(
- log.progress("Precompiling executables", (() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- ensureDir(binDir);
- writeTextFile(sdkVersionPath, "${sdk.version}\n");
- var packagesToLoad =
- unionAll(executables.keys.map(graph.transitiveDependencies)).map(((package) {
- return package.name;
- })).toSet();
- var executableIds =
- unionAll(executables.values.map(((ids) {
- return ids.toSet();
- })));
- new Future.value(
- AssetEnvironment.create(
- this,
- BarbackMode.RELEASE,
- packages: packagesToLoad,
- entrypoints: executableIds,
- useDart2JS: false)).then((x0) {
- try {
- var environment = x0;
- environment.barback.errors.listen(((error) {
- log.error(log.red("Build error:\n$error"));
- }));
- new Future.value(
- waitAndPrintErrors(executables.keys.map(((package) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var dir = path.join(binDir, package);
- cleanDir(dir);
- new Future.value(
- environment.precompileExecutables(
- package,
- dir,
- executableIds: executables[package])).then((x0) {
- try {
- x0;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x1) {
- try {
- x1;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }))).then((x1) {
- try {
- x1;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (executables.isEmpty) {
- completer0.complete(null);
- } else {
- join3();
- }
- }
- if (!sdkMatches) {
- deleteEntry(binDir);
- join2();
- } else {
- join2();
- }
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var package = it0.current;
- join4() {
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- if (executables[package].isEmpty) {
- executables.remove(package);
- join4();
- } else {
- join4();
- }
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- }
- if (!sdkMatches) {
- changed = null;
- join1();
- } else {
- join1();
- }
- }
- if (changed != null) {
- changed = changed.toSet();
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Returns the list of all executable assets for [packageName] that should be
- /// precompiled.
- ///
- /// If [changed] isn't `null`, executables for [packageName] will only be
- /// compiled if they might depend on a package in [changed].
- List<AssetId> _executablesForPackage(PackageGraph graph, String packageName,
- Set<String> changed) {
- var package = graph.packages[packageName];
- var binDir = package.path('bin');
- if (!dirExists(binDir)) return [];
- if (graph.isPackageMutable(packageName)) return [];
-
- var executables = package.executableIds;
-
- // If we don't know which packages were changed, always precompile the
- // executables.
- if (changed == null) return executables;
-
- // If any of the package's dependencies changed, recompile the executables.
- if (graph.transitiveDependencies(
- packageName).any((package) => changed.contains(package.name))) {
- return executables;
- }
-
- // If any executables doesn't exist, precompile them regardless of what
- // changed. Since we delete the bin directory before recompiling, we need to
- // recompile all executables.
- var executablesExist = executables.every(
- (executable) =>
- fileExists(
- path.join(
- '.pub',
- 'bin',
- packageName,
- "${path.url.basename(executable.path)}.snapshot")));
- if (!executablesExist) return executables;
-
- // Otherwise, we don't need to recompile.
- return [];
- }
-
- /// Makes sure the package at [id] is locally available.
- ///
- /// This automatically downloads the package to the system-wide cache as well
- /// if it requires network access to retrieve (specifically, if the package's
- /// source is a [CachedSource]).
- Future<PackageId> _get(PackageId id) {
- if (id.isRoot) return new Future.value(id);
-
- var source = cache.sources[id.source];
- return new Future.sync(() {
- if (!_packageSymlinks) {
- if (source is! CachedSource) return null;
- return source.downloadToSystemCache(id);
- }
-
- var packageDir = path.join(packagesDir, id.name);
- if (entryExists(packageDir)) deleteEntry(packageDir);
- return source.get(id, packageDir);
- }).then((_) => source.resolveId(id));
- }
-
- /// Determines whether or not the lockfile is out of date with respect to the
- /// pubspec.
- ///
- /// This will be `false` if there is no lockfile at all, or if the pubspec
- /// contains dependencies that are not in the lockfile or that don't match
- /// what's in there.
- bool _isLockFileUpToDate(LockFile lockFile) {
- /// If this is an entrypoint for an in-memory package, trust the in-memory
- /// lockfile provided for it.
- if (root.dir == null) return true;
-
- return root.immediateDependencies.every((package) {
- var locked = lockFile.packages[package.name];
- if (locked == null) return false;
-
- if (package.source != locked.source) return false;
- if (!package.constraint.allows(locked.version)) return false;
-
- var source = cache.sources[package.source];
- if (source == null) return false;
-
- return source.descriptionsEqual(package.description, locked.description);
- });
- }
-
- /// Determines whether all of the packages in the lockfile are already
- /// installed and available.
- ///
- /// Note: this assumes [isLockFileUpToDate] has already been called and
- /// returned `true`.
- Future<bool> _arePackagesAvailable(LockFile lockFile) {
- return Future.wait(lockFile.packages.values.map((package) {
- var source = cache.sources[package.source];
-
- // This should only be called after [_isLockFileUpToDate] has returned
- // `true`, which ensures all of the sources in the lock file are valid.
- assert(source != null);
-
- // We only care about cached sources. Uncached sources aren't "installed".
- // If one of those is missing, we want to show the user the file not
- // found error later since installing won't accomplish anything.
- if (source is! CachedSource) return new Future.value(true);
-
- // Get the directory.
- return source.getDirectory(package).then((dir) {
- // See if the directory is there and looks like a package.
- return dirExists(dir) || fileExists(path.join(dir, "pubspec.yaml"));
- });
- })).then((results) {
- // Make sure they are all true.
- return results.every((result) => result);
- });
- }
-
- /// Gets dependencies if the lockfile is out of date with respect to the
- /// pubspec.
- Future ensureLockFileIsUpToDate() {
- return new Future.sync(() {
- // If we don't have a current lock file, we definitely need to install.
- if (!_isLockFileUpToDate(lockFile)) {
- if (lockFileExists) {
- log.message(
- "Your pubspec has changed, so we need to update your lockfile:");
- } else {
- log.message(
- "You don't have a lockfile, so we need to generate that:");
- }
-
- return false;
- }
-
- // If we do have a lock file, we still need to make sure the packages
- // are actually installed. The user may have just gotten a package that
- // includes a lockfile.
- return _arePackagesAvailable(lockFile).then((available) {
- if (!available) {
- log.message(
- "You are missing some dependencies, so we need to install them " "first:");
- }
-
- return available;
- });
- }).then((upToDate) {
- if (upToDate) return null;
- return acquireDependencies(SolveType.GET);
- });
- }
-
- /// Loads the package graph for the application and all of its transitive
- /// dependencies.
- ///
- /// If [result] is passed, this loads the graph from it without re-parsing the
- /// lockfile or any pubspecs. Otherwise, before loading, this makes sure the
- /// lockfile and dependencies are installed and up to date.
- Future<PackageGraph> loadPackageGraph([SolveResult result]) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- new Future.value(log.progress("Loading package graph", (() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- new Future.value(ensureLockFileIsUpToDate()).then((x0) {
- try {
- x0;
- new Future.value(
- Future.wait(lockFile.packages.values.map(((id) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var source = cache.sources[id.source];
- new Future.value(
- source.getDirectory(id)).then((x0) {
- try {
- var dir = x0;
- completer0.complete(
- new Package.load(id.name, dir, cache.sources));
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x1) {
- try {
- var packages = x1;
- var packageMap =
- new Map.fromIterable(packages, key: ((p) {
- return p.name;
- }));
- packageMap[root.name] = root;
- completer0.complete(
- new PackageGraph(this, lockFile, packageMap));
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- }
- if (result != null) {
- new Future.value(Future.wait(result.packages.map(((id) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(
- cache.sources[id.source].getDirectory(id)).then((x0) {
- try {
- var dir = x0;
- completer0.complete(
- new Package(result.pubspecs[id.name], dir));
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- })))).then((x2) {
- try {
- var packages = x2;
- completer0.complete(
- new PackageGraph(
- this,
- new LockFile(result.packages),
- new Map.fromIterable(packages, key: ((package) {
- return package.name;
- }))));
- } catch (e2, s2) {
- completer0.completeError(e2, s2);
- }
- }, onError: completer0.completeError);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }), fine: true)).then((x0) {
- try {
- var graph = x0;
- _packageGraph = graph;
- completer0.complete(graph);
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (_packageGraph != null) {
- completer0.complete(_packageGraph);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Saves a list of concrete package versions to the `pubspec.lock` file.
- void _saveLockFile(List<PackageId> packageIds) {
- _lockFile = new LockFile(packageIds);
- var lockFilePath = root.path('pubspec.lock');
- writeTextFile(lockFilePath, _lockFile.serialize(root.dir, cache.sources));
- }
-
- /// Creates a self-referential symlink in the `packages` directory that allows
- /// a package to import its own files using `package:`.
- void _linkSelf() {
- var linkPath = path.join(packagesDir, root.name);
- // Create the symlink if it doesn't exist.
- if (entryExists(linkPath)) return;
- ensureDir(packagesDir);
- createPackageSymlink(
- root.name,
- root.dir,
- linkPath,
- isSelfLink: true,
- relative: true);
- }
-
- /// If [packageSymlinks] is true, add "packages" directories to the whitelist
- /// of directories that may contain Dart entrypoints.
- ///
- /// Otherwise, delete any "packages" directories in the whitelist of
- /// directories that may contain Dart entrypoints.
- void _linkOrDeleteSecondaryPackageDirs() {
- // Only the main "bin" directory gets a "packages" directory, not its
- // subdirectories.
- var binDir = root.path('bin');
- if (dirExists(binDir)) _linkOrDeleteSecondaryPackageDir(binDir);
-
- // The others get "packages" directories in subdirectories too.
- for (var dir in ['benchmark', 'example', 'test', 'tool', 'web']) {
- _linkOrDeleteSecondaryPackageDirsRecursively(root.path(dir));
- }
- }
-
- /// If [packageSymlinks] is true, creates a symlink to the "packages"
- /// directory in [dir] and all its subdirectories.
- ///
- /// Otherwise, deletes any "packages" directories in [dir] and all its
- /// subdirectories.
- void _linkOrDeleteSecondaryPackageDirsRecursively(String dir) {
- if (!dirExists(dir)) return;
- _linkOrDeleteSecondaryPackageDir(dir);
- _listDirWithoutPackages(
- dir).where(dirExists).forEach(_linkOrDeleteSecondaryPackageDir);
- }
-
- // TODO(nweiz): roll this into [listDir] in io.dart once issue 4775 is fixed.
- /// Recursively lists the contents of [dir], excluding hidden `.DS_Store`
- /// files and `package` files.
- List<String> _listDirWithoutPackages(dir) {
- return flatten(listDir(dir).map((file) {
- if (path.basename(file) == 'packages') return [];
- if (!dirExists(file)) return [];
- var fileAndSubfiles = [file];
- fileAndSubfiles.addAll(_listDirWithoutPackages(file));
- return fileAndSubfiles;
- }));
- }
-
- /// If [packageSymlinks] is true, creates a symlink to the "packages"
- /// directory in [dir].
- ///
- /// Otherwise, deletes a "packages" directories in [dir] if one exists.
- void _linkOrDeleteSecondaryPackageDir(String dir) {
- var symlink = path.join(dir, 'packages');
- if (entryExists(symlink)) deleteEntry(symlink);
- if (_packageSymlinks) createSymlink(packagesDir, symlink, relative: true);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/error_group.dart b/sdk/lib/_internal/pub_generated/lib/src/error_group.dart
deleted file mode 100644
index 7efebf3..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/error_group.dart
+++ /dev/null
@@ -1,299 +0,0 @@
-// Copyright (c) 2013, 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 pub.error_group;
-
-import 'dart:async';
-
-/// An [ErrorGroup] entangles the errors of multiple [Future]s and [Stream]s
-/// with one another.
-///
-/// This allows APIs to expose multiple [Future]s and [Stream]s that have
-/// identical error conditions without forcing API consumers to attach error
-/// handling to objects they don't care about.
-///
-/// To use an [ErrorGroup], register [Future]s and [Stream]s with it using
-/// [registerFuture] and [registerStream]. These methods return wrapped versions
-/// of the [Future]s and [Stream]s, which should then be used in place of the
-/// originals. For example:
-///
-/// var errorGroup = new ErrorGroup();
-/// future = errorGroup.registerFuture(future);
-/// stream = errorGroup.registerStream(stream);
-///
-/// An [ErrorGroup] has two major effects on its wrapped members:
-///
-/// * An error in any member of the group will be propagated to every member
-/// that hasn't already completed. If those members later complete, their
-/// values will be ignored.
-/// * If any member of this group has a listener, errors on members without
-/// listeners won't get passed to the top-level error handler.
-class ErrorGroup {
- /// The [Future]s that are members of [this].
- final _futures = <_ErrorGroupFuture>[];
-
- /// The [Stream]s that are members of [this].
- final _streams = <_ErrorGroupStream>[];
-
- /// Whether [this] has completed, either successfully or with an error.
- var _isDone = false;
-
- /// The [Completer] for [done].
- final _doneCompleter = new Completer();
-
- /// The underlying [Future] for [done].
- ///
- /// We need to be able to access it internally as an [_ErrorGroupFuture] so
- /// we can check if it has listeners and signal errors on it.
- _ErrorGroupFuture _done;
-
- /// Returns a [Future] that completes successully when all members of [this]
- /// are complete, or with an error if any member receives an error.
- ///
- /// This [Future] is effectively in the group in that an error on it won't be
- /// passed to the top-level error handler unless no members of the group have
- /// listeners attached.
- Future get done => _done;
-
- /// Creates a new group with no members.
- ErrorGroup() {
- this._done = new _ErrorGroupFuture(this, _doneCompleter.future);
- }
-
- /// Registers a [Future] as a member of [this].
- ///
- /// Returns a wrapped version of [future] that should be used in its place.
- ///
- /// If all members of [this] have already completed successfully or with an
- /// error, it's a [StateError] to try to register a new [Future].
- Future registerFuture(Future future) {
- if (_isDone) {
- throw new StateError(
- "Can't register new members on a complete " "ErrorGroup.");
- }
-
- var wrapped = new _ErrorGroupFuture(this, future);
- _futures.add(wrapped);
- return wrapped;
- }
-
- /// Registers a [Stream] as a member of [this].
- ///
- /// Returns a wrapped version of [stream] that should be used in its place.
- /// The returned [Stream] will be multi-subscription if and only if [stream]
- /// is.
- ///
- /// Since all errors in a group are passed to all members, the returned
- /// [Stream] will automatically unsubscribe all its listeners when it
- /// encounters an error.
- ///
- /// If all members of [this] have already completed successfully or with an
- /// error, it's a [StateError] to try to register a new [Stream].
- Stream registerStream(Stream stream) {
- if (_isDone) {
- throw new StateError(
- "Can't register new members on a complete " "ErrorGroup.");
- }
-
- var wrapped = new _ErrorGroupStream(this, stream);
- _streams.add(wrapped);
- return wrapped;
- }
-
- /// Sends [error] to all members of [this].
- ///
- /// Like errors that come from members, this will only be passed to the
- /// top-level error handler if no members have listeners.
- ///
- /// If all members of [this] have already completed successfully or with an
- /// error, it's a [StateError] to try to signal an error.
- void signalError(var error, [StackTrace stackTrace]) {
- if (_isDone) {
- throw new StateError("Can't signal errors on a complete ErrorGroup.");
- }
-
- _signalError(error, stackTrace);
- }
-
- /// Signal an error internally.
- ///
- /// This is just like [signalError], but instead of throwing an error if
- /// [this] is complete, it just does nothing.
- void _signalError(var error, [StackTrace stackTrace]) {
- if (_isDone) return;
-
- var caught = false;
- for (var future in _futures) {
- if (future._isDone || future._hasListeners) caught = true;
- future._signalError(error, stackTrace);
- }
-
- for (var stream in _streams) {
- if (stream._isDone || stream._hasListeners) caught = true;
- stream._signalError(error, stackTrace);
- }
-
- _isDone = true;
- _done._signalError(error, stackTrace);
- if (!caught && !_done._hasListeners) scheduleMicrotask(() {
- throw error;
- });
- }
-
- /// Notifies [this] that one of its member [Future]s is complete.
- void _signalFutureComplete(_ErrorGroupFuture future) {
- if (_isDone) return;
-
- _isDone = _futures.every((future) => future._isDone) &&
- _streams.every((stream) => stream._isDone);
- if (_isDone) _doneCompleter.complete();
- }
-
- /// Notifies [this] that one of its member [Stream]s is complete.
- void _signalStreamComplete(_ErrorGroupStream stream) {
- if (_isDone) return;
-
- _isDone = _futures.every((future) => future._isDone) &&
- _streams.every((stream) => stream._isDone);
- if (_isDone) _doneCompleter.complete();
- }
-}
-
-/// A [Future] wrapper that keeps track of whether it's been completed and
-/// whether it has any listeners.
-///
-/// It also notifies its parent [ErrorGroup] when it completes successfully or
-/// receives an error.
-class _ErrorGroupFuture implements Future {
- /// The parent [ErrorGroup].
- final ErrorGroup _group;
-
- /// Whether [this] has completed, either successfully or with an error.
- var _isDone = false;
-
- /// The underlying [Completer] for [this].
- final _completer = new Completer();
-
- /// Whether [this] has any listeners.
- bool _hasListeners = false;
-
- /// Creates a new [_ErrorGroupFuture] that's a child of [_group] and wraps
- /// [inner].
- _ErrorGroupFuture(this._group, Future inner) {
- inner.then((value) {
- if (!_isDone) _completer.complete(value);
- _isDone = true;
- _group._signalFutureComplete(this);
- }).catchError(_group._signalError);
-
- // Make sure _completer.future doesn't automatically send errors to the
- // top-level.
- _completer.future.catchError((_) {});
- }
-
- Future then(onValue(value), {Function onError}) {
- _hasListeners = true;
- return _completer.future.then(onValue, onError: onError);
- }
-
- Future catchError(Function onError, {bool test(Object error)}) {
- _hasListeners = true;
- return _completer.future.catchError(onError, test: test);
- }
-
- Future whenComplete(void action()) {
- _hasListeners = true;
- return _completer.future.whenComplete(action);
- }
-
- Future timeout(Duration timeLimit, {void onTimeout()}) {
- _hasListeners = true;
- return _completer.future.timeout(timeLimit, onTimeout: onTimeout);
- }
-
- Stream asStream() {
- _hasListeners = true;
- return _completer.future.asStream();
- }
-
- /// Signal that an error from [_group] should be propagated through [this],
- /// unless it's already complete.
- void _signalError(var error, [StackTrace stackTrace]) {
- if (!_isDone) _completer.completeError(error, stackTrace);
- _isDone = true;
- }
-}
-
-// TODO(nweiz): currently streams never top-level unhandled errors (issue 7843).
-// When this is fixed, this class will need to prevent such errors from being
-// top-leveled.
-/// A [Stream] wrapper that keeps track of whether it's been completed and
-/// whether it has any listeners.
-///
-/// It also notifies its parent [ErrorGroup] when it completes successfully or
-/// receives an error.
-class _ErrorGroupStream extends Stream {
- /// The parent [ErrorGroup].
- final ErrorGroup _group;
-
- /// Whether [this] has completed, either successfully or with an error.
- var _isDone = false;
-
- /// The underlying [StreamController] for [this].
- final StreamController _controller;
-
- /// The controller's [Stream].
- ///
- /// May be different than `_controller.stream` if the wrapped stream is a
- /// broadcasting stream.
- Stream _stream;
-
- /// The [StreamSubscription] that connects the wrapped [Stream] to
- /// [_controller].
- StreamSubscription _subscription;
-
- /// Whether [this] has any listeners.
- bool get _hasListeners => _controller.hasListener;
-
- /// Creates a new [_ErrorGroupFuture] that's a child of [_group] and wraps
- /// [inner].
- _ErrorGroupStream(this._group, Stream inner)
- : _controller = new StreamController(sync: true) {
- // Use old-style asBroadcastStream behavior - cancel source _subscription
- // the first time the stream has no listeners.
- _stream = inner.isBroadcast ?
- _controller.stream.asBroadcastStream(onCancel: (sub) => sub.cancel()) :
- _controller.stream;
- _subscription = inner.listen((v) {
- _controller.add(v);
- }, onError: (e, [stackTrace]) {
- _group._signalError(e, stackTrace);
- }, onDone: () {
- _isDone = true;
- _group._signalStreamComplete(this);
- _controller.close();
- });
- }
-
- StreamSubscription listen(void onData(value), {Function onError, void
- onDone(), bool cancelOnError}) {
- return _stream.listen(
- onData,
- onError: onError,
- onDone: onDone,
- cancelOnError: true);
- }
-
- /// Signal that an error from [_group] should be propagated through [this],
- /// unless it's already complete.
- void _signalError(var e, [StackTrace stackTrace]) {
- if (_isDone) return;
- _subscription.cancel();
- // Call these asynchronously to work around issue 7913.
- new Future.value().then((_) {
- _controller.addError(e, stackTrace);
- _controller.close();
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/exceptions.dart b/sdk/lib/_internal/pub_generated/lib/src/exceptions.dart
deleted file mode 100644
index 7d4f5a3..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/exceptions.dart
+++ /dev/null
@@ -1,125 +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.
-
-library pub.exceptions;
-
-import 'dart:io';
-import 'dart:isolate';
-
-import "package:analyzer/analyzer.dart";
-import 'package:args/command_runner.dart';
-import "package:http/http.dart" as http;
-import "package:stack_trace/stack_trace.dart";
-import "package:yaml/yaml.dart";
-
-import '../../asset/dart/serialize.dart';
-
-/// An exception class for exceptions that are intended to be seen by the user.
-///
-/// These exceptions won't have any debugging information printed when they're
-/// thrown.
-class ApplicationException implements Exception {
- final String message;
-
- ApplicationException(this.message);
-
- String toString() => message;
-}
-
-/// An exception class for exceptions that are intended to be seen by the user
-/// and are associated with a problem in a file at some path.
-class FileException implements ApplicationException {
- final String message;
-
- /// The path to the file that was missing or erroneous.
- final String path;
-
- FileException(this.message, this.path);
-
- String toString() => message;
-}
-
-/// A class for exceptions that wrap other exceptions.
-class WrappedException extends ApplicationException {
- /// The underlying exception that [this] is wrapping, if any.
- final innerError;
-
- /// The stack chain for [innerError] if it exists.
- final Chain innerChain;
-
- WrappedException(String message, this.innerError, [StackTrace innerTrace])
- : innerChain = innerTrace == null ? null : new Chain.forTrace(innerTrace),
- super(message);
-}
-
-/// A class for exceptions that shouldn't be printed at the top level.
-///
-/// This is usually used when an exception has already been printed using
-/// [log.exception].
-class SilentException extends WrappedException {
- SilentException(innerError, [StackTrace innerTrace])
- : super(innerError.toString(), innerError, innerTrace);
-}
-
-/// A class for errors in a command's input data.
-///
-/// This corresponds to the [exit_codes.DATA] exit code.
-class DataException extends ApplicationException {
- DataException(String message)
- : super(message);
-}
-
-/// An class for exceptions where a package could not be found in a [Source].
-///
-/// The source is responsible for wrapping its internal exceptions in this so
-/// that other code in pub can use this to show a more detailed explanation of
-/// why the package was being requested.
-class PackageNotFoundException extends WrappedException {
- PackageNotFoundException(String message, [innerError, StackTrace innerTrace])
- : super(message, innerError, innerTrace);
-}
-
-/// All the names of user-facing exceptions.
-final _userFacingExceptions = new Set<String>.from(
- ['ApplicationException', 'GitException', // This refers to http.ClientException.
- 'ClientException',
- // Errors coming from the Dart analyzer are probably caused by syntax errors
- // in user code, so they're user-facing.
- 'AnalyzerError',
- 'AnalyzerErrorGroup',
- // An error spawning an isolate probably indicates a transformer with an
- // invalid import.
- 'IsolateSpawnException', // IOException and subclasses.
- 'CertificateException',
- 'FileSystemException',
- 'HandshakeException',
- 'HttpException',
- 'IOException',
- 'ProcessException',
- 'RedirectException',
- 'SignalException',
- 'SocketException',
- 'StdoutException',
- 'TlsException',
- 'WebSocketException']);
-
-/// Returns whether [error] is a user-facing error object.
-///
-/// This includes both [ApplicationException] and any dart:io errors.
-bool isUserFacingException(error) {
- if (error is CrossIsolateException) {
- return _userFacingExceptions.contains(error.type);
- }
-
- // TODO(nweiz): unify this list with _userFacingExceptions when issue 5897 is
- // fixed.
- return error is ApplicationException ||
- error is AnalyzerError ||
- error is AnalyzerErrorGroup ||
- error is IsolateSpawnException ||
- error is IOException ||
- error is http.ClientException ||
- error is YamlException ||
- error is UsageException;
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/executable.dart b/sdk/lib/_internal/pub_generated/lib/src/executable.dart
deleted file mode 100644
index 6215572..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/executable.dart
+++ /dev/null
@@ -1,320 +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.
-
-library pub.executable;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-import 'package:stack_trace/stack_trace.dart';
-
-import 'barback/asset_environment.dart';
-import 'entrypoint.dart';
-import 'exit_codes.dart' as exit_codes;
-import 'io.dart';
-import 'log.dart' as log;
-import 'utils.dart';
-
-/// Runs [executable] from [package] reachable from [entrypoint].
-///
-/// The executable string is a relative Dart file path using native path
-/// separators with or without a trailing ".dart" extension. It is contained
-/// within [package], which should either be the entrypoint package or an
-/// immediate dependency of it.
-///
-/// Arguments from [args] will be passed to the spawned Dart application.
-///
-/// If [mode] is passed, it's used as the barback mode; it defaults to
-/// [BarbackMode.RELEASE].
-///
-/// Returns the exit code of the spawned app.
-Future<int> runExecutable(Entrypoint entrypoint, String package,
- String executable, Iterable<String> args, {bool isGlobal: false,
- BarbackMode mode}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- join1() {
- join2() {
- join3() {
- var localSnapshotPath =
- p.join(".pub", "bin", package, "${executable}.dart.snapshot");
- join4() {
- var rootDir = "bin";
- var parts = p.split(executable);
- join5() {
- var assetPath = "${p.url.joinAll(p.split(executable))}.dart";
- var id = new AssetId(package, assetPath);
- new Future.value(
- AssetEnvironment.create(
- entrypoint,
- mode,
- useDart2JS: false,
- entrypoints: [id])).then((x0) {
- try {
- var environment = x0;
- environment.barback.errors.listen(((error) {
- log.error(log.red("Build error:\n$error"));
- }));
- var server;
- join6() {
- join7() {
- var vmArgs = [];
- vmArgs.add("--checked");
- var relativePath =
- p.url.relative(assetPath, from: p.url.joinAll(p.split(server.rootDirectory)));
- vmArgs.add(
- server.url.resolve(relativePath).toString());
- vmArgs.addAll(args);
- new Future.value(
- Process.start(Platform.executable, vmArgs)).then((x1) {
- try {
- var process = x1;
- process.stderr.listen(stderr.add);
- process.stdout.listen(stdout.add);
- stdin.listen(process.stdin.add);
- completer0.complete(process.exitCode);
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- catch0(error, stackTrace) {
- try {
- if (error is AssetNotFoundException) {
- var message =
- "Could not find ${log.bold(executable + ".dart")}";
- join8() {
- log.error("${message}.");
- log.fine(new Chain.forTrace(stackTrace));
- completer0.complete(exit_codes.NO_INPUT);
- }
- if (package != entrypoint.root.name) {
- message +=
- " in package ${log.bold(server.package)}";
- join8();
- } else {
- join8();
- }
- } else {
- throw error;
- }
- } catch (error, stackTrace) {
- completer0.completeError(error, stackTrace);
- }
- }
- try {
- new Future.value(
- environment.barback.getAssetById(id)).then((x2) {
- try {
- x2;
- join7();
- } catch (e1, s1) {
- catch0(e1, s1);
- }
- }, onError: catch0);
- } catch (e2, s2) {
- catch0(e2, s2);
- }
- }
- if (package == entrypoint.root.name) {
- new Future.value(
- environment.serveDirectory(rootDir)).then((x3) {
- try {
- server = x3;
- join6();
- } catch (e3, s3) {
- completer0.completeError(e3, s3);
- }
- }, onError: completer0.completeError);
- } else {
- new Future.value(
- environment.servePackageBinDirectory(package)).then((x4) {
- try {
- server = x4;
- join6();
- } catch (e4, s4) {
- completer0.completeError(e4, s4);
- }
- }, onError: completer0.completeError);
- }
- } catch (e5, s5) {
- completer0.completeError(e5, s5);
- }
- }, onError: completer0.completeError);
- }
- if (parts.length > 1) {
- assert(!isGlobal && package == entrypoint.root.name);
- rootDir = parts.first;
- join5();
- } else {
- executable = p.join("bin", executable);
- join5();
- }
- }
- if (!isGlobal &&
- fileExists(localSnapshotPath) &&
- mode == BarbackMode.RELEASE) {
- completer0.complete(
- _runCachedExecutable(entrypoint, localSnapshotPath, args));
- } else {
- join4();
- }
- }
- if (p.extension(executable) == ".dart") {
- executable = p.withoutExtension(executable);
- join3();
- } else {
- join3();
- }
- }
- if (log.verbosity == log.Verbosity.NORMAL) {
- log.verbosity = log.Verbosity.WARNING;
- join2();
- } else {
- join2();
- }
- }
- if (entrypoint.root.name != package &&
- !entrypoint.root.immediateDependencies.any(((dep) {
- return dep.name == package;
- }))) {
- new Future.value(entrypoint.loadPackageGraph()).then((x5) {
- try {
- var graph = x5;
- join9() {
- join1();
- }
- if (graph.packages.containsKey(package)) {
- dataError(
- 'Package "${package}" is not an immediate dependency.\n'
- 'Cannot run executables in transitive dependencies.');
- join9();
- } else {
- dataError(
- 'Could not find package "${package}". Did you forget to add a ' 'dependency?');
- join9();
- }
- } catch (e6, s6) {
- completer0.completeError(e6, s6);
- }
- }, onError: completer0.completeError);
- } else {
- join1();
- }
- }
- if (mode == null) {
- mode = BarbackMode.RELEASE;
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
-}
-
-/// Runs the snapshot at [path] with [args] and hooks its stdout, stderr, and
-/// sdtin to this process's.
-///
-/// If [recompile] is passed, it's called if the snapshot is out-of-date. It's
-/// expected to regenerate a snapshot at [path], after which the snapshot will
-/// be re-run. It may return a Future.
-///
-/// If [checked] is set, runs the snapshot in checked mode.
-///
-/// Returns the snapshot's exit code.
-///
-/// This doesn't do any validation of the snapshot's SDK version.
-Future<int> runSnapshot(String path, Iterable<String> args, {recompile(),
- bool checked: false}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var vmArgs = [path]..addAll(args);
- join0() {
- var stdin1;
- var stdin2;
- join1() {
- runProcess(input) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- new Future.value(
- Process.start(Platform.executable, vmArgs)).then((x0) {
- try {
- var process = x0;
- process.stderr.listen(stderr.add);
- process.stdout.listen(stdout.add);
- input.listen(process.stdin.add);
- completer0.complete(process.exitCode);
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
- new Future.value(runProcess(stdin1)).then((x0) {
- try {
- var exitCode = x0;
- join2() {
- new Future.value(recompile()).then((x1) {
- try {
- x1;
- completer0.complete(runProcess(stdin2));
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (recompile == null || exitCode != 255) {
- completer0.complete(exitCode);
- } else {
- join2();
- }
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- }
- if (recompile == null) {
- stdin1 = stdin;
- join1();
- } else {
- var pair = tee(stdin);
- stdin1 = pair.first;
- stdin2 = pair.last;
- join1();
- }
- }
- if (checked) {
- vmArgs.insert(0, "--checked");
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
-}
-
-/// Runs the executable snapshot at [snapshotPath].
-Future<int> _runCachedExecutable(Entrypoint entrypoint, String snapshotPath,
- List<String> args) {
- return runSnapshot(snapshotPath, args, checked: true, recompile: () {
- log.fine("Precompiled executable is out of date.");
- return entrypoint.precompileExecutables();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/exit_codes.dart b/sdk/lib/_internal/pub_generated/lib/src/exit_codes.dart
deleted file mode 100644
index ebe8e8d..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/exit_codes.dart
+++ /dev/null
@@ -1,60 +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.
-
-/// Exit code constants.
-///
-/// From [the BSD sysexits manpage][manpage]. Not every constant here is used,
-/// even though some of the unused ones may be appropriate for errors
-/// encountered by pub.
-///
-/// [manpage]: http://www.freebsd.org/cgi/man.cgi?query=sysexits
-library pub.exit_codes;
-
-/// The command completely successfully.
-const SUCCESS = 0;
-
-/// The command was used incorrectly.
-const USAGE = 64;
-
-/// The input data was incorrect.
-const DATA = 65;
-
-/// An input file did not exist or was unreadable.
-const NO_INPUT = 66;
-
-/// The user specified did not exist.
-const NO_USER = 67;
-
-/// The host specified did not exist.
-const NO_HOST = 68;
-
-/// A service is unavailable.
-const UNAVAILABLE = 69;
-
-/// An internal software error has been detected.
-const SOFTWARE = 70;
-
-/// An operating system error has been detected.
-const OS = 71;
-
-/// Some system file did not exist or was unreadable.
-const OS_FILE = 72;
-
-/// A user-specified output file cannot be created.
-const CANT_CREATE = 73;
-
-/// An error occurred while doing I/O on some file.
-const IO = 74;
-
-/// Temporary failure, indicating something that is not really an error.
-const TEMP_FAIL = 75;
-
-/// The remote system returned something invalid during a protocol exchange.
-const PROTOCOL = 76;
-
-/// The user did not have sufficient permissions.
-const NO_PERM = 77;
-
-/// Something was unconfigured or mis-configured.
-const CONFIG = 78;
diff --git a/sdk/lib/_internal/pub_generated/lib/src/git.dart b/sdk/lib/_internal/pub_generated/lib/src/git.dart
deleted file mode 100644
index a574e8a..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/git.dart
+++ /dev/null
@@ -1,116 +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.
-
-/// Helper functionality for invoking Git.
-library pub.git;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:stack_trace/stack_trace.dart';
-
-import 'exceptions.dart';
-import 'io.dart';
-import 'log.dart' as log;
-import 'utils.dart';
-
-/// An exception thrown because a git command failed.
-class GitException implements ApplicationException {
- /// The arguments to the git command.
- final List<String> args;
-
- /// The standard error emitted by git.
- final String stderr;
-
- String get message => 'Git error. Command: git ${args.join(" ")}\n$stderr';
-
- GitException(Iterable<String> args, this.stderr)
- : args = args.toList();
-
- String toString() => message;
-}
-
-/// Tests whether or not the git command-line app is available for use.
-bool get isInstalled {
- if (_isInstalledCache != null) return _isInstalledCache;
- _isInstalledCache = _gitCommand != null;
- return _isInstalledCache;
-}
-bool _isInstalledCache;
-
-/// Run a git process with [args] from [workingDir].
-///
-/// Returns the stdout as a list of strings if it succeeded. Completes to an
-/// exception if it failed.
-Future<List<String>> run(List<String> args, {String workingDir, Map<String,
- String> environment}) {
- if (!isInstalled) {
- fail(
- "Cannot find a Git executable.\n" "Please ensure Git is correctly installed.");
- }
-
- log.muteProgress();
- return runProcess(
- _gitCommand,
- args,
- workingDir: workingDir,
- environment: environment).then((result) {
- if (!result.success) throw new GitException(args, result.stderr.join("\n"));
-
- return result.stdout;
- }).whenComplete(() {
- log.unmuteProgress();
- });
-}
-
-/// Like [run], but synchronous.
-List<String> runSync(List<String> args, {String workingDir, Map<String,
- String> environment}) {
- if (!isInstalled) {
- fail(
- "Cannot find a Git executable.\n" "Please ensure Git is correctly installed.");
- }
-
- var result = runProcessSync(
- _gitCommand,
- args,
- workingDir: workingDir,
- environment: environment);
- if (!result.success) throw new GitException(args, result.stderr.join("\n"));
- return result.stdout;
-}
-
-/// Returns the name of the git command-line app, or null if Git could not be
-/// found on the user's PATH.
-String get _gitCommand {
- if (_commandCache != null) return _commandCache;
-
- var command;
- if (_tryGitCommand("git")) {
- _commandCache = "git";
- } else if (_tryGitCommand("git.cmd")) {
- _commandCache = "git.cmd";
- } else {
- return null;
- }
-
- log.fine('Determined git command $command.');
- return _commandCache;
-}
-String _commandCache;
-
-/// Checks whether [command] is the Git command for this computer.
-bool _tryGitCommand(String command) {
- // If "git --version" prints something familiar, git is working.
- try {
- var result = runProcessSync(command, ["--version"]);
- var regexp = new RegExp("^git version");
- return result.stdout.length == 1 && regexp.hasMatch(result.stdout.single);
- } on ProcessException catch (error, stackTrace) {
- var chain = new Chain.forTrace(stackTrace);
- // If the process failed, they probably don't have it.
- log.message('Git command is not "$command": $error\n$chain');
- return false;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/global_packages.dart b/sdk/lib/_internal/pub_generated/lib/src/global_packages.dart
deleted file mode 100644
index 3dfed37..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/global_packages.dart
+++ /dev/null
@@ -1,1109 +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.
-
-library pub.global_packages;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:barback/barback.dart';
-import 'package:pub_semver/pub_semver.dart';
-
-import 'barback/asset_environment.dart';
-import 'entrypoint.dart';
-import 'exceptions.dart';
-import 'executable.dart' as exe;
-import 'io.dart';
-import 'lock_file.dart';
-import 'log.dart' as log;
-import 'package.dart';
-import 'pubspec.dart';
-import 'sdk.dart' as sdk;
-import 'solver/version_solver.dart';
-import 'source/cached.dart';
-import 'source/git.dart';
-import 'source/path.dart';
-import 'system_cache.dart';
-import 'utils.dart';
-
-/// Maintains the set of packages that have been globally activated.
-///
-/// These have been hand-chosen by the user to make their executables in bin/
-/// available to the entire system. This lets them access them even when the
-/// current working directory is not inside another entrypoint package.
-///
-/// Only one version of a given package name can be globally activated at a
-/// time. Activating a different version of a package will deactivate the
-/// previous one.
-///
-/// This handles packages from uncached and cached sources a little differently.
-/// For a cached source, the package is physically in the user's pub cache and
-/// we don't want to mess with it by putting a lockfile in there. Instead, when
-/// we activate the package, we create a full lockfile and put it in the
-/// "global_packages" directory. It's named "<package>.lock". Unlike a normal
-/// lockfile, it also contains an entry for the root package itself, so that we
-/// know the version and description that was activated.
-///
-/// Uncached packages (i.e. "path" packages) are somewhere else on the user's
-/// local file system and can have a lockfile directly in place. (And, in fact,
-/// we want to ensure we honor the user's lockfile there.) To activate it, we
-/// just need to know where that package directory is. For that, we create a
-/// lockfile that *only* contains the root package's [PackageId] -- basically
-/// just the path to the directory where the real lockfile lives.
-class GlobalPackages {
- /// The [SystemCache] containing the global packages.
- final SystemCache cache;
-
- /// The directory where the lockfiles for activated packages are stored.
- String get _directory => p.join(cache.rootDir, "global_packages");
-
- /// The directory where binstubs for global package executables are stored.
- String get _binStubDir => p.join(cache.rootDir, "bin");
-
- /// Creates a new global package registry backed by the given directory on
- /// the user's file system.
- ///
- /// The directory may not physically exist yet. If not, this will create it
- /// when needed.
- GlobalPackages(this.cache);
-
- /// Caches the package located in the Git repository [repo] and makes it the
- /// active global version.
- ///
- /// [executables] is the names of the executables that should have binstubs.
- /// If `null`, all executables in the package will get binstubs. If empty, no
- /// binstubs will be created.
- ///
- /// if [overwriteBinStubs] is `true`, any binstubs that collide with
- /// existing binstubs in other packages will be overwritten by this one's.
- /// Otherwise, the previous ones will be preserved.
- Future activateGit(String repo, List<String> executables,
- {bool overwriteBinStubs}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var source = cache.sources["git"] as GitSource;
- new Future.value(source.getPackageNameFromRepo(repo)).then((x0) {
- try {
- var name = x0;
- _describeActive(name);
- new Future.value(
- _installInCache(
- new PackageDep(name, "git", VersionConstraint.any, repo),
- executables,
- overwriteBinStubs: overwriteBinStubs)).then((x1) {
- try {
- x1;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Finds the latest version of the hosted package with [name] that matches
- /// [constraint] and makes it the active global version.
- ///
- /// [executables] is the names of the executables that should have binstubs.
- /// If `null`, all executables in the package will get binstubs. If empty, no
- /// binstubs will be created.
- ///
- /// if [overwriteBinStubs] is `true`, any binstubs that collide with
- /// existing binstubs in other packages will be overwritten by this one's.
- /// Otherwise, the previous ones will be preserved.
- Future activateHosted(String name, VersionConstraint constraint,
- List<String> executables, {bool overwriteBinStubs}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- _describeActive(name);
- new Future.value(
- _installInCache(
- new PackageDep(name, "hosted", constraint, name),
- executables,
- overwriteBinStubs: overwriteBinStubs)).then((x0) {
- try {
- x0;
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Makes the local package at [path] globally active.
- ///
- /// [executables] is the names of the executables that should have binstubs.
- /// If `null`, all executables in the package will get binstubs. If empty, no
- /// binstubs will be created.
- ///
- /// if [overwriteBinStubs] is `true`, any binstubs that collide with
- /// existing binstubs in other packages will be overwritten by this one's.
- /// Otherwise, the previous ones will be preserved.
- Future activatePath(String path, List<String> executables,
- {bool overwriteBinStubs}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var entrypoint = new Entrypoint(path, cache);
- new Future.value(entrypoint.ensureLockFileIsUpToDate()).then((x0) {
- try {
- x0;
- var name = entrypoint.root.name;
- _describeActive(name);
- var fullPath = canonicalize(entrypoint.root.dir);
- var id = new PackageId(
- name,
- "path",
- entrypoint.root.version,
- PathSource.describePath(fullPath));
- _writeLockFile(name, new LockFile([id]));
- var binDir = p.join(_directory, name, 'bin');
- join0() {
- _updateBinStubs(
- entrypoint.root,
- executables,
- overwriteBinStubs: overwriteBinStubs);
- completer0.complete();
- }
- if (dirExists(binDir)) {
- deleteEntry(binDir);
- join0();
- } else {
- join0();
- }
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Installs the package [dep] and its dependencies into the system cache.
- Future _installInCache(PackageDep dep, List<String> executables,
- {bool overwriteBinStubs}) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var source = cache.sources[dep.source];
- var root = new Package.inMemory(
- new Pubspec(
- "pub global activate",
- dependencies: [dep],
- sources: cache.sources));
- new Future.value(
- resolveVersions(SolveType.GET, cache.sources, root)).then((x0) {
- try {
- var result = x0;
- join0() {
- result.showReport(SolveType.GET);
- new Future.value(
- Future.wait(result.packages.map(_cacheDependency))).then((x1) {
- try {
- var ids = x1;
- var lockFile = new LockFile(ids);
- new Future.value(
- new Entrypoint.inMemory(
- root,
- lockFile,
- cache).loadPackageGraph(result)).then((x2) {
- try {
- var graph = x2;
- new Future.value(
- _precompileExecutables(graph.entrypoint, dep.name)).then((x3) {
- try {
- var snapshots = x3;
- _writeLockFile(dep.name, lockFile);
- _updateBinStubs(
- graph.packages[dep.name],
- executables,
- overwriteBinStubs: overwriteBinStubs,
- snapshots: snapshots);
- completer0.complete();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } catch (e2, s2) {
- completer0.completeError(e2, s2);
- }
- }, onError: completer0.completeError);
- }
- if (!result.succeeded) {
- join1() {
- join2() {
- throw result.error;
- join0();
- }
- if (result.error is NoVersionException) {
- dataError(result.error.message);
- join2();
- } else {
- join2();
- }
- }
- if (result.error.package != dep.name) {
- throw result.error;
- join1();
- } else {
- join1();
- }
- } else {
- join0();
- }
- } catch (e3, s3) {
- completer0.completeError(e3, s3);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Precompiles the executables for [package] and saves them in the global
- /// cache.
- ///
- /// Returns a map from executable name to path for the snapshots that were
- /// successfully precompiled.
- Future<Map<String, String>> _precompileExecutables(Entrypoint entrypoint,
- String package) {
- return log.progress("Precompiling executables", () {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var binDir = p.join(_directory, package, 'bin');
- cleanDir(binDir);
- new Future.value(entrypoint.loadPackageGraph()).then((x0) {
- try {
- var graph = x0;
- new Future.value(
- AssetEnvironment.create(
- entrypoint,
- BarbackMode.RELEASE,
- entrypoints: graph.packages[package].executableIds,
- useDart2JS: false)).then((x1) {
- try {
- var environment = x1;
- environment.barback.errors.listen(((error) {
- log.error(log.red("Build error:\n$error"));
- }));
- completer0.complete(
- environment.precompileExecutables(package, binDir));
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } catch (e1, s1) {
- completer0.completeError(e1, s1);
- }
- }, onError: completer0.completeError);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- });
- }
-
- /// Downloads [id] into the system cache if it's a cached package.
- ///
- /// Returns the resolved [PackageId] for [id].
- Future<PackageId> _cacheDependency(PackageId id) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var source = cache.sources[id.source];
- join0() {
- completer0.complete(source.resolveId(id));
- }
- if (!id.isRoot && source is CachedSource) {
- new Future.value(source.downloadToSystemCache(id)).then((x0) {
- try {
- x0;
- join0();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Finishes activating package [package] by saving [lockFile] in the cache.
- void _writeLockFile(String package, LockFile lockFile) {
- ensureDir(p.join(_directory, package));
-
- // TODO(nweiz): This cleans up Dart 1.6's old lockfile location. Remove it
- // when Dart 1.6 is old enough that we don't think anyone will have these
- // lockfiles anymore (issue 20703).
- var oldPath = p.join(_directory, "$package.lock");
- if (fileExists(oldPath)) deleteEntry(oldPath);
-
- writeTextFile(
- _getLockFilePath(package),
- lockFile.serialize(cache.rootDir, cache.sources));
-
- var id = lockFile.packages[package];
- log.message('Activated ${_formatPackage(id)}.');
- }
-
- /// Shows the user the currently active package with [name], if any.
- void _describeActive(String name) {
- try {
- var lockFile = new LockFile.load(_getLockFilePath(name), cache.sources);
- var id = lockFile.packages[name];
-
- if (id.source == 'git') {
- var url = GitSource.urlFromDescription(id.description);
- log.message(
- 'Package ${log.bold(name)} is currently active from Git '
- 'repository "${url}".');
- } else if (id.source == 'path') {
- var path = PathSource.pathFromDescription(id.description);
- log.message(
- 'Package ${log.bold(name)} is currently active at path ' '"$path".');
- } else {
- log.message(
- 'Package ${log.bold(name)} is currently active at version '
- '${log.bold(id.version)}.');
- }
- } on IOException catch (error) {
- // If we couldn't read the lock file, it's not activated.
- return null;
- }
- }
-
- /// Deactivates a previously-activated package named [name].
- ///
- /// Returns `false` if no package with [name] was currently active.
- bool deactivate(String name) {
- var dir = p.join(_directory, name);
- if (!dirExists(dir)) return false;
-
- _deleteBinStubs(name);
-
- var lockFile = new LockFile.load(_getLockFilePath(name), cache.sources);
- var id = lockFile.packages[name];
- log.message('Deactivated package ${_formatPackage(id)}.');
-
- deleteEntry(dir);
-
- return true;
- }
-
- /// Finds the active package with [name].
- ///
- /// Returns an [Entrypoint] loaded with the active package if found.
- Future<Entrypoint> find(String name) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var lockFilePath = _getLockFilePath(name);
- var lockFile;
- join0() {
- var id = lockFile.packages[name];
- lockFile.packages.remove(name);
- var source = cache.sources[id.source];
- join1() {
- assert(id.source == "path");
- completer0.complete(
- new Entrypoint(PathSource.pathFromDescription(id.description), cache));
- }
- if (source is CachedSource) {
- new Future.value(
- cache.sources[id.source].getDirectory(id)).then((x0) {
- try {
- var dir = x0;
- var package = new Package.load(name, dir, cache.sources);
- completer0.complete(
- new Entrypoint.inMemory(package, lockFile, cache));
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- } else {
- join1();
- }
- }
- catch0(error, s1) {
- try {
- if (error is IOException) {
- var oldLockFilePath = p.join(_directory, '${name}.lock');
- join2() {
- ensureDir(p.dirname(lockFilePath));
- new File(oldLockFilePath).renameSync(lockFilePath);
- join0();
- }
- catch1(error, s2) {
- try {
- if (error is IOException) {
- dataError("No active package ${log.bold(name)}.");
- join2();
- } else {
- throw error;
- }
- } catch (error, s2) {
- completer0.completeError(error, s2);
- }
- }
- try {
- lockFile = new LockFile.load(oldLockFilePath, cache.sources);
- join2();
- } catch (e1, s3) {
- catch1(e1, s3);
- }
- } else {
- throw error;
- }
- } catch (error, s1) {
- completer0.completeError(error, s1);
- }
- }
- try {
- lockFile = new LockFile.load(lockFilePath, cache.sources);
- join0();
- } catch (e2, s4) {
- catch0(e2, s4);
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Runs [package]'s [executable] with [args].
- ///
- /// If [executable] is available in its precompiled form, that will be
- /// recompiled if the SDK has been upgraded since it was first compiled and
- /// then run. Otherwise, it will be run from source.
- ///
- /// If [mode] is passed, it's used as the barback mode; it defaults to
- /// [BarbackMode.RELEASE].
- ///
- /// Returns the exit code from the executable.
- Future<int> runExecutable(String package, String executable,
- Iterable<String> args, {BarbackMode mode}) {
- if (mode == null) mode = BarbackMode.RELEASE;
-
- var binDir = p.join(_directory, package, 'bin');
- if (mode != BarbackMode.RELEASE ||
- !fileExists(p.join(binDir, '$executable.dart.snapshot'))) {
- return find(package).then((entrypoint) {
- return exe.runExecutable(
- entrypoint,
- package,
- executable,
- args,
- mode: mode,
- isGlobal: true);
- });
- }
-
- // Unless the user overrides the verbosity, we want to filter out the
- // normal pub output shown while loading the environment.
- if (log.verbosity == log.Verbosity.NORMAL) {
- log.verbosity = log.Verbosity.WARNING;
- }
-
- var snapshotPath = p.join(binDir, '$executable.dart.snapshot');
- return exe.runSnapshot(snapshotPath, args, recompile: () {
- log.fine(
- "$package:$executable is out of date and needs to be " "recompiled.");
- return find(
- package).then(
- (entrypoint) =>
- entrypoint.loadPackageGraph()).then(
- (graph) => _precompileExecutables(graph.entrypoint, package));
- });
- }
-
- /// Gets the path to the lock file for an activated cached package with
- /// [name].
- String _getLockFilePath(String name) =>
- p.join(_directory, name, "pubspec.lock");
-
- /// Shows the user a formatted list of globally activated packages.
- void listActivePackages() {
- if (!dirExists(_directory)) return;
-
- listDir(_directory).map(_loadPackageId).toList()
- ..sort((id1, id2) => id1.name.compareTo(id2.name))
- ..forEach((id) => log.message(_formatPackage(id)));
- }
-
- /// Returns the [PackageId] for the globally-activated package at [path].
- ///
- /// [path] should be a path within [_directory]. It can either be an old-style
- /// path to a single lockfile or a new-style path to a directory containing a
- /// lockfile.
- PackageId _loadPackageId(String path) {
- var name = p.basenameWithoutExtension(path);
- if (!fileExists(path)) path = p.join(path, 'pubspec.lock');
-
- var id =
- new LockFile.load(p.join(_directory, path), cache.sources).packages[name];
-
- if (id == null) {
- throw new FormatException(
- "Pubspec for activated package $name didn't " "contain an entry for itself.");
- }
-
- return id;
- }
-
- /// Returns formatted string representing the package [id].
- String _formatPackage(PackageId id) {
- if (id.source == 'git') {
- var url = GitSource.urlFromDescription(id.description);
- return '${log.bold(id.name)} ${id.version} from Git repository "$url"';
- } else if (id.source == 'path') {
- var path = PathSource.pathFromDescription(id.description);
- return '${log.bold(id.name)} ${id.version} at path "$path"';
- } else {
- return '${log.bold(id.name)} ${id.version}';
- }
- }
-
- /// Repairs any corrupted globally-activated packages and their binstubs.
- ///
- /// Returns a pair of two [int]s. The first indicates how many packages were
- /// successfully re-activated; the second indicates how many failed.
- Future<Pair<int, int>> repairActivatedPackages() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var executables = {};
- join0() {
- var successes = 0;
- var failures = 0;
- join1() {
- join2() {
- completer0.complete(new Pair(successes, failures));
- }
- if (executables.isNotEmpty) {
- var packages = pluralize("package", executables.length);
- var message =
- new StringBuffer("Binstubs exist for non-activated " "packages:\n");
- executables.forEach(((package, executableNames) {
- executableNames.forEach(
- (executable) => deleteEntry(p.join(_binStubDir, executable)));
- message.writeln(
- " From ${log.bold(package)}: " "${toSentence(executableNames)}");
- }));
- log.error(message);
- join2();
- } else {
- join2();
- }
- }
- if (dirExists(_directory)) {
- var it0 = listDir(_directory).iterator;
- break0() {
- join1();
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var entry = it0.current;
- var id;
- join3() {
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- catch0(error, stackTrace) {
- try {
- var message =
- "Failed to reactivate " "${log.bold(p.basenameWithoutExtension(entry))}";
- join4() {
- log.error(message, error, stackTrace);
- failures++;
- tryDeleteEntry(entry);
- join3();
- }
- if (id != null) {
- message += " ${id.version}";
- join5() {
- join4();
- }
- if (id.source != "hosted") {
- message += " from ${id.source}";
- join5();
- } else {
- join5();
- }
- } else {
- join4();
- }
- } catch (error, stackTrace) {
- completer0.completeError(error, stackTrace);
- }
- }
- try {
- id = _loadPackageId(entry);
- log.message(
- "Reactivating ${log.bold(id.name)} ${id.version}...");
- new Future.value(find(id.name)).then((x0) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- var entrypoint = x0;
- new Future.value(
- entrypoint.loadPackageGraph()).then((x1) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- var graph = x1;
- new Future.value(
- _precompileExecutables(entrypoint, id.name)).then((x2) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- var snapshots = x2;
- var packageExecutables =
- executables.remove(id.name);
- join6() {
- _updateBinStubs(
- graph.packages[id.name],
- packageExecutables,
- overwriteBinStubs: true,
- snapshots: snapshots,
- suggestIfNotOnPath: false);
- successes++;
- join3();
- }
- if (packageExecutables == null) {
- packageExecutables = [];
- join6();
- } else {
- join6();
- }
- } catch (e0, s0) {
- catch0(e0, s0);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: catch0);
- } catch (e1, s1) {
- catch0(e1, s1);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: catch0);
- } catch (e2, s2) {
- catch0(e2, s2);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: catch0);
- } catch (e3, s3) {
- catch0(e3, s3);
- }
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } else {
- join1();
- }
- }
- if (dirExists(_binStubDir)) {
- var it1 = listDir(_binStubDir).iterator;
- break1() {
- join0();
- }
- var trampoline1;
- continue1() {
- trampoline1 = null;
- if (it1.moveNext()) {
- var entry = it1.current;
- join7() {
- trampoline1 = continue1;
- do trampoline1(); while (trampoline1 != null);
- }
- catch1(error, stackTrace) {
- try {
- log.error(
- "Error reading binstub for " "\"${p.basenameWithoutExtension(entry)}\"",
- error,
- stackTrace);
- tryDeleteEntry(entry);
- join7();
- } catch (error, stackTrace) {
- completer0.completeError(error, stackTrace);
- }
- }
- try {
- var binstub = readTextFile(entry);
- var package = _binStubProperty(binstub, "Package");
- join8() {
- var executable = _binStubProperty(binstub, "Executable");
- join9() {
- executables.putIfAbsent(package, (() {
- return [];
- })).add(executable);
- join7();
- }
- if (executable == null) {
- throw new ApplicationException("No 'Executable' property.");
- join9();
- } else {
- join9();
- }
- }
- if (package == null) {
- throw new ApplicationException("No 'Package' property.");
- join8();
- } else {
- join8();
- }
- } catch (e4, s4) {
- catch1(e4, s4);
- }
- } else {
- break1();
- }
- }
- trampoline1 = continue1;
- do trampoline1(); while (trampoline1 != null);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Updates the binstubs for [package].
- ///
- /// A binstub is a little shell script in `PUB_CACHE/bin` that runs an
- /// executable from a globally activated package. This removes any old
- /// binstubs from the previously activated version of the package and
- /// (optionally) creates new ones for the executables listed in the package's
- /// pubspec.
- ///
- /// [executables] is the names of the executables that should have binstubs.
- /// If `null`, all executables in the package will get binstubs. If empty, no
- /// binstubs will be created.
- ///
- /// If [overwriteBinStubs] is `true`, any binstubs that collide with
- /// existing binstubs in other packages will be overwritten by this one's.
- /// Otherwise, the previous ones will be preserved.
- ///
- /// If [snapshots] is given, it is a map of the names of executables whose
- /// snapshots were precompiled to the paths of those snapshots. Binstubs for
- /// those will run the snapshot directly and skip pub entirely.
- ///
-
- /// If [suggestIfNotOnPath] is `true` (the default), this will warn the user if
- /// the bin directory isn't on their path.
- void _updateBinStubs(Package package, List<String> executables,
- {bool overwriteBinStubs, Map<String, String> snapshots, bool suggestIfNotOnPath:
- true}) {
- if (snapshots == null) snapshots = const {};
-
- // Remove any previously activated binstubs for this package, in case the
- // list of executables has changed.
- _deleteBinStubs(package.name);
-
- if ((executables != null && executables.isEmpty) ||
- package.pubspec.executables.isEmpty) {
- return;
- }
-
- ensureDir(_binStubDir);
-
- var installed = [];
- var collided = {};
- var allExecutables = ordered(package.pubspec.executables.keys);
- for (var executable in allExecutables) {
- if (executables != null && !executables.contains(executable)) continue;
-
- var script = package.pubspec.executables[executable];
-
- var previousPackage = _createBinStub(
- package,
- executable,
- script,
- overwrite: overwriteBinStubs,
- snapshot: snapshots[script]);
- if (previousPackage != null) {
- collided[executable] = previousPackage;
-
- if (!overwriteBinStubs) continue;
- }
-
- installed.add(executable);
- }
-
- if (installed.isNotEmpty) {
- var names = namedSequence("executable", installed.map(log.bold));
- log.message("Installed $names.");
- }
-
- // Show errors for any collisions.
- if (collided.isNotEmpty) {
- for (var command in ordered(collided.keys)) {
- if (overwriteBinStubs) {
- log.warning(
- "Replaced ${log.bold(command)} previously installed from "
- "${log.bold(collided[command])}.");
- } else {
- log.warning(
- "Executable ${log.bold(command)} was already installed "
- "from ${log.bold(collided[command])}.");
- }
- }
-
- if (!overwriteBinStubs) {
- log.warning(
- "Deactivate the other package(s) or activate "
- "${log.bold(package.name)} using --overwrite.");
- }
- }
-
- // Show errors for any unknown executables.
- if (executables != null) {
- var unknown = ordered(
- executables.where((exe) => !package.pubspec.executables.keys.contains(exe)));
- if (unknown.isNotEmpty) {
- dataError("Unknown ${namedSequence('executable', unknown)}.");
- }
- }
-
- // Show errors for any missing scripts.
- // TODO(rnystrom): This can print false positives since a script may be
- // produced by a transformer. Do something better.
- var binFiles = package.listFiles(
- beneath: "bin",
- recursive: false).map((path) => package.relative(path)).toList();
- for (var executable in installed) {
- var script = package.pubspec.executables[executable];
- var scriptPath = p.join("bin", "$script.dart");
- if (!binFiles.contains(scriptPath)) {
- log.warning(
- 'Warning: Executable "$executable" runs "$scriptPath", '
- 'which was not found in ${log.bold(package.name)}.');
- }
- }
-
- if (suggestIfNotOnPath && installed.isNotEmpty) {
- _suggestIfNotOnPath(installed.first);
- }
- }
-
- /// Creates a binstub named [executable] that runs [script] from [package].
- ///
- /// If [overwrite] is `true`, this will replace an existing binstub with that
- /// name for another package.
- ///
- /// If [snapshot] is non-null, it is a path to a snapshot file. The binstub
- /// will invoke that directly. Otherwise, it will run `pub global run`.
- ///
- /// If a collision occurs, returns the name of the package that owns the
- /// existing binstub. Otherwise returns `null`.
- String _createBinStub(Package package, String executable, String script,
- {bool overwrite, String snapshot}) {
- var binStubPath = p.join(_binStubDir, executable);
-
- if (Platform.operatingSystem == "windows") binStubPath += ".bat";
-
- // See if the binstub already exists. If so, it's for another package
- // since we already deleted all of this package's binstubs.
- var previousPackage;
- if (fileExists(binStubPath)) {
- var contents = readTextFile(binStubPath);
- previousPackage = _binStubProperty(contents, "Package");
- if (previousPackage == null) {
- log.fine("Could not parse binstub $binStubPath:\n$contents");
- } else if (!overwrite) {
- return previousPackage;
- }
- }
-
- // If the script was precompiled to a snapshot, just invoke that directly
- // and skip pub global run entirely.
- var invocation;
- if (snapshot != null) {
- // We expect absolute paths from the precompiler since relative ones
- // won't be relative to the right directory when the user runs this.
- assert(p.isAbsolute(snapshot));
- invocation = 'dart "$snapshot"';
- } else {
- invocation = "pub global run ${package.name}:$script";
- }
-
- if (Platform.operatingSystem == "windows") {
- var batch = """
-@echo off
-rem This file was created by pub v${sdk.version}.
-rem Package: ${package.name}
-rem Version: ${package.version}
-rem Executable: ${executable}
-rem Script: ${script}
-$invocation %*
-""";
-
- if (snapshot != null) {
- batch += """
-
-rem The VM exits with code 255 if the snapshot version is out-of-date.
-rem If it is, we need to delete it and run "pub global" manually.
-if not errorlevel 255 (
- exit /b %errorlevel%
-)
-
-pub global run ${package.name}:$script %*
-""";
- }
-
- writeTextFile(binStubPath, batch);
- } else {
- var bash = """
-#!/usr/bin/env sh
-# This file was created by pub v${sdk.version}.
-# Package: ${package.name}
-# Version: ${package.version}
-# Executable: ${executable}
-# Script: ${script}
-$invocation "\$@"
-""";
-
- if (snapshot != null) {
- bash += """
-
-# The VM exits with code 255 if the snapshot version is out-of-date.
-# If it is, we need to delete it and run "pub global" manually.
-exit_code=\$?
-if [ \$exit_code != 255 ]; then
- exit \$exit_code
-fi
-
-pub global run ${package.name}:$script "\$@"
-""";
- }
-
- writeTextFile(binStubPath, bash);
-
- // Make it executable.
- var result = Process.runSync('chmod', ['+x', binStubPath]);
- if (result.exitCode != 0) {
- // Couldn't make it executable so don't leave it laying around.
- try {
- deleteEntry(binStubPath);
- } on IOException catch (err) {
- // Do nothing. We're going to fail below anyway.
- log.fine("Could not delete binstub:\n$err");
- }
-
- fail(
- 'Could not make "$binStubPath" executable (exit code '
- '${result.exitCode}):\n${result.stderr}');
- }
- }
-
- return previousPackage;
- }
-
- /// Deletes all existing binstubs for [package].
- void _deleteBinStubs(String package) {
- if (!dirExists(_binStubDir)) return;
-
- for (var file in listDir(_binStubDir, includeDirs: false)) {
- var contents = readTextFile(file);
- var binStubPackage = _binStubProperty(contents, "Package");
- if (binStubPackage == null) {
- log.fine("Could not parse binstub $file:\n$contents");
- continue;
- }
-
- if (binStubPackage == package) {
- log.fine("Deleting old binstub $file");
- deleteEntry(file);
- }
- }
- }
-
- /// Checks to see if the binstubs are on the user's PATH and, if not, suggests
- /// that the user add the directory to their PATH.
- ///
- /// [installed] should be the name of an installed executable that can be used
- /// to test whether accessing it on the path works.
- void _suggestIfNotOnPath(String installed) {
- if (Platform.operatingSystem == "windows") {
- // See if the shell can find one of the binstubs.
- // "\q" means return exit code 0 if found or 1 if not.
- var result = runProcessSync("where", [r"\q", installed + ".bat"]);
- if (result.exitCode == 0) return;
-
- log.warning(
- "${log.yellow('Warning:')} Pub installs executables into "
- "${log.bold(_binStubDir)}, which is not on your path.\n"
- "You can fix that by adding that directory to your system's "
- '"Path" environment variable.\n'
- 'A web search for "configure windows path" will show you how.');
- } else {
- // See if the shell can find one of the binstubs.
- var result = runProcessSync("which", [installed]);
- if (result.exitCode == 0) return;
-
- var binDir = _binStubDir;
- if (binDir.startsWith(Platform.environment['HOME'])) {
- binDir =
- p.join("~", p.relative(binDir, from: Platform.environment['HOME']));
- }
-
- log.warning(
- "${log.yellow('Warning:')} Pub installs executables into "
- "${log.bold(binDir)}, which is not on your path.\n"
- "You can fix that by adding this to your shell's config file "
- "(.bashrc, .bash_profile, etc.):\n" "\n"
- " ${log.bold('export PATH="\$PATH":"$binDir"')}\n" "\n");
- }
- }
-
- /// Returns the value of the property named [name] in the bin stub script
- /// [source].
- String _binStubProperty(String source, String name) {
- var pattern = new RegExp(quoteRegExp(name) + r": ([a-zA-Z0-9_-]+)");
- var match = pattern.firstMatch(source);
- return match == null ? null : match[1];
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/http.dart b/sdk/lib/_internal/pub_generated/lib/src/http.dart
deleted file mode 100644
index eea72ae..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/http.dart
+++ /dev/null
@@ -1,270 +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.
-
-/// Helpers for dealing with HTTP.
-library pub.http;
-
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:http/http.dart' as http;
-import 'package:http_throttle/http_throttle.dart';
-
-import 'io.dart';
-import 'log.dart' as log;
-import 'oauth2.dart' as oauth2;
-import 'sdk.dart' as sdk;
-import 'utils.dart';
-
-// TODO(nweiz): make this configurable
-/// The amount of time in milliseconds to allow HTTP requests before assuming
-/// they've failed.
-final HTTP_TIMEOUT = 30 * 1000;
-
-/// Headers and field names that should be censored in the log output.
-final _CENSORED_FIELDS = const ['refresh_token', 'authorization'];
-
-/// Headers required for pub.dartlang.org API requests.
-///
-/// The Accept header tells pub.dartlang.org which version of the API we're
-/// expecting, so it can either serve that version or give us a 406 error if
-/// it's not supported.
-final PUB_API_HEADERS = const {
- 'Accept': 'application/vnd.pub.v2+json'
-};
-
-/// An HTTP client that transforms 40* errors and socket exceptions into more
-/// user-friendly error messages.
-///
-/// This also adds a 30-second timeout to every request. This can be configured
-/// on a per-request basis by setting the 'Pub-Request-Timeout' header to the
-/// desired number of milliseconds, or to "None" to disable the timeout.
-class _PubHttpClient extends http.BaseClient {
- final _requestStopwatches = new Map<http.BaseRequest, Stopwatch>();
-
- http.Client _inner;
-
- _PubHttpClient([http.Client inner])
- : this._inner = inner == null ? new http.Client() : inner;
-
- Future<http.StreamedResponse> send(http.BaseRequest request) {
- _requestStopwatches[request] = new Stopwatch()..start();
- request.headers[HttpHeaders.USER_AGENT] = "Dart pub ${sdk.version}";
- _logRequest(request);
-
- // TODO(nweiz): remove this when issue 4061 is fixed.
- var stackTrace;
- try {
- throw null;
- } catch (_, localStackTrace) {
- stackTrace = localStackTrace;
- }
-
- var timeoutLength = HTTP_TIMEOUT;
- var timeoutString = request.headers.remove('Pub-Request-Timeout');
- if (timeoutString == 'None') {
- timeoutLength = null;
- } else if (timeoutString != null) {
- timeoutLength = int.parse(timeoutString);
- }
-
- var future = _inner.send(request).then((streamedResponse) {
- _logResponse(streamedResponse);
-
- var status = streamedResponse.statusCode;
- // 401 responses should be handled by the OAuth2 client. It's very
- // unlikely that they'll be returned by non-OAuth2 requests. We also want
- // to pass along 400 responses from the token endpoint.
- var tokenRequest =
- urisEqual(streamedResponse.request.url, oauth2.tokenEndpoint);
- if (status < 400 || status == 401 || (status == 400 && tokenRequest)) {
- return streamedResponse;
- }
-
- if (status == 406 &&
- request.headers['Accept'] == PUB_API_HEADERS['Accept']) {
- fail(
- "Pub ${sdk.version} is incompatible with the current version of "
- "${request.url.host}.\n" "Upgrade pub to the latest version and try again.");
- }
-
- if (status == 500 &&
- (request.url.host == "pub.dartlang.org" ||
- request.url.host == "storage.googleapis.com")) {
- var message =
- "HTTP error 500: Internal Server Error at " "${request.url}.";
-
- if (request.url.host == "pub.dartlang.org" ||
- request.url.host == "storage.googleapis.com") {
- message +=
- "\nThis is likely a transient error. Please try again " "later.";
- }
-
- fail(message);
- }
-
- return http.Response.fromStream(streamedResponse).then((response) {
- throw new PubHttpException(response);
- });
- }).catchError((error, stackTrace) {
- if (error is SocketException && error.osError != null) {
- if (error.osError.errorCode == 8 ||
- error.osError.errorCode == -2 ||
- error.osError.errorCode == -5 ||
- error.osError.errorCode == 11001 ||
- error.osError.errorCode == 11004) {
- fail(
- 'Could not resolve URL "${request.url.origin}".',
- error,
- stackTrace);
- } else if (error.osError.errorCode == -12276) {
- fail(
- 'Unable to validate SSL certificate for ' '"${request.url.origin}".',
- error,
- stackTrace);
- }
- }
- throw error;
- });
-
- if (timeoutLength == null) return future;
- return timeout(
- future,
- timeoutLength,
- request.url,
- 'fetching URL "${request.url}"');
- }
-
- /// Logs the fact that [request] was sent, and information about it.
- void _logRequest(http.BaseRequest request) {
- var requestLog = new StringBuffer();
- requestLog.writeln("HTTP ${request.method} ${request.url}");
- request.headers.forEach(
- (name, value) => requestLog.writeln(_logField(name, value)));
-
- if (request.method == 'POST') {
- var contentTypeString = request.headers[HttpHeaders.CONTENT_TYPE];
- if (contentTypeString == null) contentTypeString = '';
- var contentType = ContentType.parse(contentTypeString);
- if (request is http.MultipartRequest) {
- requestLog.writeln();
- requestLog.writeln("Body fields:");
- request.fields.forEach(
- (name, value) => requestLog.writeln(_logField(name, value)));
-
- // TODO(nweiz): make MultipartRequest.files readable, and log them?
- } else if (request is http.Request) {
- if (contentType.value == 'application/x-www-form-urlencoded') {
- requestLog.writeln();
- requestLog.writeln("Body fields:");
- request.bodyFields.forEach(
- (name, value) => requestLog.writeln(_logField(name, value)));
- } else if (contentType.value == 'text/plain' ||
- contentType.value == 'application/json') {
- requestLog.write(request.body);
- }
- }
- }
-
- log.fine(requestLog.toString().trim());
- }
-
- /// Logs the fact that [response] was received, and information about it.
- void _logResponse(http.StreamedResponse response) {
- // TODO(nweiz): Fork the response stream and log the response body. Be
- // careful not to log OAuth2 private data, though.
-
- var responseLog = new StringBuffer();
- var request = response.request;
- var stopwatch = _requestStopwatches.remove(request)..stop();
- responseLog.writeln(
- "HTTP response ${response.statusCode} "
- "${response.reasonPhrase} for ${request.method} ${request.url}");
- responseLog.writeln("took ${stopwatch.elapsed}");
- response.headers.forEach(
- (name, value) => responseLog.writeln(_logField(name, value)));
-
- log.fine(responseLog.toString().trim());
- }
-
- /// Returns a log-formatted string for the HTTP field or header with the given
- /// [name] and [value].
- String _logField(String name, String value) {
- if (_CENSORED_FIELDS.contains(name.toLowerCase())) {
- return "$name: <censored>";
- } else {
- return "$name: $value";
- }
- }
-}
-
-/// The [_PubHttpClient] wrapped by [httpClient].
-final _pubClient = new _PubHttpClient();
-
-/// The HTTP client to use for all HTTP requests.
-final httpClient = new ThrottleClient(16, _pubClient);
-
-/// The underlying HTTP client wrapped by [httpClient].
-http.Client get innerHttpClient => _pubClient._inner;
-set innerHttpClient(http.Client client) => _pubClient._inner = client;
-
-/// Handles a successful JSON-formatted response from pub.dartlang.org.
-///
-/// These responses are expected to be of the form `{"success": {"message":
-/// "some message"}}`. If the format is correct, the message will be printed;
-/// otherwise an error will be raised.
-void handleJsonSuccess(http.Response response) {
- var parsed = parseJsonResponse(response);
- if (parsed['success'] is! Map ||
- !parsed['success'].containsKey('message') ||
- parsed['success']['message'] is! String) {
- invalidServerResponse(response);
- }
- log.message(parsed['success']['message']);
-}
-
-/// Handles an unsuccessful JSON-formatted response from pub.dartlang.org.
-///
-/// These responses are expected to be of the form `{"error": {"message": "some
-/// message"}}`. If the format is correct, the message will be raised as an
-/// error; otherwise an [invalidServerResponse] error will be raised.
-void handleJsonError(http.Response response) {
- var errorMap = parseJsonResponse(response);
- if (errorMap['error'] is! Map ||
- !errorMap['error'].containsKey('message') ||
- errorMap['error']['message'] is! String) {
- invalidServerResponse(response);
- }
- fail(errorMap['error']['message']);
-}
-
-/// Parses a response body, assuming it's JSON-formatted.
-///
-/// Throws a user-friendly error if the response body is invalid JSON, or if
-/// it's not a map.
-Map parseJsonResponse(http.Response response) {
- var value;
- try {
- value = JSON.decode(response.body);
- } on FormatException catch (e) {
- invalidServerResponse(response);
- }
- if (value is! Map) invalidServerResponse(response);
- return value;
-}
-
-/// Throws an error describing an invalid response from the server.
-void invalidServerResponse(http.Response response) =>
- fail('Invalid server response:\n${response.body}');
-
-/// Exception thrown when an HTTP operation fails.
-class PubHttpException implements Exception {
- final http.Response response;
-
- const PubHttpException(this.response);
-
- String toString() =>
- 'HTTP error ${response.statusCode}: ' '${response.reasonPhrase}';
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/io.dart b/sdk/lib/_internal/pub_generated/lib/src/io.dart
deleted file mode 100644
index 35df8d1..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/io.dart
+++ /dev/null
@@ -1,1028 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// Helper functionality to make working with IO easier.
-library pub.io;
-
-import 'dart:async';
-import 'dart:collection';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-import 'package:pool/pool.dart';
-import 'package:http/http.dart' show ByteStream;
-import 'package:http_multi_server/http_multi_server.dart';
-import 'package:stack_trace/stack_trace.dart';
-
-import 'exit_codes.dart' as exit_codes;
-import 'exceptions.dart';
-import 'error_group.dart';
-import 'log.dart' as log;
-import 'sdk.dart' as sdk;
-import 'utils.dart';
-
-export 'package:http/http.dart' show ByteStream;
-
-/// The pool used for restricting access to asynchronous operations that consume
-/// file descriptors.
-///
-/// The maximum number of allocated descriptors is based on empirical tests that
-/// indicate that beyond 32, additional file reads don't provide substantial
-/// additional throughput.
-final _descriptorPool = new Pool(32);
-
-/// Determines if a file or directory exists at [path].
-bool entryExists(String path) =>
- dirExists(path) || fileExists(path) || linkExists(path);
-
-/// Returns whether [link] exists on the file system.
-///
-/// This returns `true` for any symlink, regardless of what it points at or
-/// whether it's broken.
-bool linkExists(String link) => new Link(link).existsSync();
-
-/// Returns whether [file] exists on the file system.
-///
-/// This returns `true` for a symlink only if that symlink is unbroken and
-/// points to a file.
-bool fileExists(String file) => new File(file).existsSync();
-
-/// Returns the canonical path for [pathString].
-///
-/// This is the normalized, absolute path, with symlinks resolved. As in
-/// [transitiveTarget], broken or recursive symlinks will not be fully resolved.
-///
-/// This doesn't require [pathString] to point to a path that exists on the
-/// filesystem; nonexistent or unreadable path entries are treated as normal
-/// directories.
-String canonicalize(String pathString) {
- var seen = new Set<String>();
- var components =
- new Queue<String>.from(path.split(path.normalize(path.absolute(pathString))));
-
- // The canonical path, built incrementally as we iterate through [components].
- var newPath = components.removeFirst();
-
- // Move through the components of the path, resolving each one's symlinks as
- // necessary. A resolved component may also add new components that need to be
- // resolved in turn.
- while (!components.isEmpty) {
- seen.add(path.join(newPath, path.joinAll(components)));
- var resolvedPath =
- resolveLink(path.join(newPath, components.removeFirst()));
- var relative = path.relative(resolvedPath, from: newPath);
-
- // If the resolved path of the component relative to `newPath` is just ".",
- // that means component was a symlink pointing to its parent directory. We
- // can safely ignore such components.
- if (relative == '.') continue;
-
- var relativeComponents = new Queue<String>.from(path.split(relative));
-
- // If the resolved path is absolute relative to `newPath`, that means it's
- // on a different drive. We need to canonicalize the entire target of that
- // symlink again.
- if (path.isAbsolute(relative)) {
- // If we've already tried to canonicalize the new path, we've encountered
- // a symlink loop. Avoid going infinite by treating the recursive symlink
- // as the canonical path.
- if (seen.contains(relative)) {
- newPath = relative;
- } else {
- newPath = relativeComponents.removeFirst();
- relativeComponents.addAll(components);
- components = relativeComponents;
- }
- continue;
- }
-
- // Pop directories off `newPath` if the component links upwards in the
- // directory hierarchy.
- while (relativeComponents.first == '..') {
- newPath = path.dirname(newPath);
- relativeComponents.removeFirst();
- }
-
- // If there's only one component left, [resolveLink] guarantees that it's
- // not a link (or is a broken link). We can just add it to `newPath` and
- // continue resolving the remaining components.
- if (relativeComponents.length == 1) {
- newPath = path.join(newPath, relativeComponents.single);
- continue;
- }
-
- // If we've already tried to canonicalize the new path, we've encountered a
- // symlink loop. Avoid going infinite by treating the recursive symlink as
- // the canonical path.
- var newSubPath = path.join(newPath, path.joinAll(relativeComponents));
- if (seen.contains(newSubPath)) {
- newPath = newSubPath;
- continue;
- }
-
- // If there are multiple new components to resolve, add them to the
- // beginning of the queue.
- relativeComponents.addAll(components);
- components = relativeComponents;
- }
- return newPath;
-}
-
-/// Returns the transitive target of [link] (if A links to B which links to C,
-/// this will return C).
-///
-/// If [link] is part of a symlink loop (e.g. A links to B which links back to
-/// A), this returns the path to the first repeated link (so
-/// `transitiveTarget("A")` would return `"A"` and `transitiveTarget("A")` would
-/// return `"B"`).
-///
-/// This accepts paths to non-links or broken links, and returns them as-is.
-String resolveLink(String link) {
- var seen = new Set<String>();
- while (linkExists(link) && !seen.contains(link)) {
- seen.add(link);
- link =
- path.normalize(path.join(path.dirname(link), new Link(link).targetSync()));
- }
- return link;
-}
-
-/// Reads the contents of the text file [file].
-String readTextFile(String file) =>
- new File(file).readAsStringSync(encoding: UTF8);
-
-/// Reads the contents of the binary file [file].
-List<int> readBinaryFile(String file) {
- log.io("Reading binary file $file.");
- var contents = new File(file).readAsBytesSync();
- log.io("Read ${contents.length} bytes from $file.");
- return contents;
-}
-
-/// Creates [file] and writes [contents] to it.
-///
-/// If [dontLogContents] is true, the contents of the file will never be logged.
-String writeTextFile(String file, String contents, {bool dontLogContents:
- false}) {
- // Sanity check: don't spew a huge file.
- log.io("Writing ${contents.length} characters to text file $file.");
- if (!dontLogContents && contents.length < 1024 * 1024) {
- log.fine("Contents:\n$contents");
- }
-
- new File(file).writeAsStringSync(contents);
- return file;
-}
-
-/// Creates [file] and writes [contents] to it.
-String writeBinaryFile(String file, List<int> contents) {
- log.io("Writing ${contents.length} bytes to binary file $file.");
- new File(file).openSync(mode: FileMode.WRITE)
- ..writeFromSync(contents)
- ..closeSync();
- log.fine("Wrote text file $file.");
- return file;
-}
-
-/// Writes [stream] to a new file at path [file].
-///
-/// Replaces any file already at that path. Completes when the file is done
-/// being written.
-Future<String> createFileFromStream(Stream<List<int>> stream, String file) {
- // TODO(nweiz): remove extra logging when we figure out the windows bot issue.
- log.io("Creating $file from stream.");
-
- return _descriptorPool.withResource(() {
- return stream.pipe(new File(file).openWrite()).then((_) {
- log.fine("Created $file from stream.");
- return file;
- });
- });
-}
-
-/// Copies all files in [files] to the directory [destination].
-///
-/// Their locations in [destination] will be determined by their relative
-/// location to [baseDir]. Any existing files at those paths will be
-/// overwritten.
-void copyFiles(Iterable<String> files, String baseDir, String destination) {
- for (var file in files) {
- var newPath = path.join(destination, path.relative(file, from: baseDir));
- ensureDir(path.dirname(newPath));
- copyFile(file, newPath);
- }
-}
-
-/// Copies a file from [source] to [destination].
-void copyFile(String source, String destination) {
- writeBinaryFile(destination, readBinaryFile(source));
-}
-
-/// Creates a directory [dir].
-String createDir(String dir) {
- new Directory(dir).createSync();
- return dir;
-}
-
-/// Ensures that [dir] and all its parent directories exist.
-///
-/// If they don't exist, creates them.
-String ensureDir(String dir) {
- new Directory(dir).createSync(recursive: true);
- return dir;
-}
-
-/// Creates a temp directory in [dir], whose name will be [prefix] with
-/// characters appended to it to make a unique name.
-///
-/// Returns the path of the created directory.
-String createTempDir(String base, String prefix) {
- var tempDir = new Directory(base).createTempSync(prefix);
- log.io("Created temp directory ${tempDir.path}");
- return tempDir.path;
-}
-
-/// Creates a temp directory in the system temp directory, whose name will be
-/// 'pub_' with characters appended to it to make a unique name.
-///
-/// Returns the path of the created directory.
-String createSystemTempDir() {
- var tempDir = Directory.systemTemp.createTempSync('pub_');
- log.io("Created temp directory ${tempDir.path}");
- return tempDir.path;
-}
-
-/// Lists the contents of [dir].
-///
-/// If [recursive] is `true`, lists subdirectory contents (defaults to `false`).
-/// If [includeHidden] is `true`, includes files and directories beginning with
-/// `.` (defaults to `false`). If [includeDirs] is `true`, includes directories
-/// as well as files (defaults to `true`).
-///
-/// [whiteList] is a list of hidden filenames to include even when
-/// [includeHidden] is `false`.
-///
-/// Note that dart:io handles recursive symlinks in an unfortunate way. You
-/// end up with two copies of every entity that is within the recursive loop.
-/// We originally had our own directory list code that addressed that, but it
-/// had a noticeable performance impact. In the interest of speed, we'll just
-/// live with that annoying behavior.
-///
-/// The returned paths are guaranteed to begin with [dir]. Broken symlinks won't
-/// be returned.
-List<String> listDir(String dir, {bool recursive: false, bool includeHidden:
- false, bool includeDirs: true, Iterable<String> whitelist}) {
- if (whitelist == null) whitelist = [];
- var whitelistFilter = createFileFilter(whitelist);
-
- // This is used in some performance-sensitive paths and can list many, many
- // files. As such, it leans more havily towards optimization as opposed to
- // readability than most code in pub. In particular, it avoids using the path
- // package, since re-parsing a path is very expensive relative to string
- // operations.
- return new Directory(
- dir).listSync(recursive: recursive, followLinks: true).where((entity) {
- if (!includeDirs && entity is Directory) return false;
- if (entity is Link) return false;
- if (includeHidden) return true;
-
- // Using substring here is generally problematic in cases where dir has one
- // or more trailing slashes. If you do listDir("foo"), you'll get back
- // paths like "foo/bar". If you do listDir("foo/"), you'll get "foo/bar"
- // (note the trailing slash was dropped. If you do listDir("foo//"), you'll
- // get "foo//bar".
- //
- // This means if you strip off the prefix, the resulting string may have a
- // leading separator (if the prefix did not have a trailing one) or it may
- // not. However, since we are only using the results of that to call
- // contains() on, the leading separator is harmless.
- assert(entity.path.startsWith(dir));
- var pathInDir = entity.path.substring(dir.length);
-
- // If the basename is whitelisted, don't count its "/." as making the file
- // hidden.
- var whitelistedBasename =
- whitelistFilter.firstWhere(pathInDir.contains, orElse: () => null);
- if (whitelistedBasename != null) {
- pathInDir =
- pathInDir.substring(0, pathInDir.length - whitelistedBasename.length);
- }
-
- if (pathInDir.contains("/.")) return false;
- if (Platform.operatingSystem != "windows") return true;
- return !pathInDir.contains("\\.");
- }).map((entity) => entity.path).toList();
-}
-
-/// Returns whether [dir] exists on the file system.
-///
-/// This returns `true` for a symlink only if that symlink is unbroken and
-/// points to a directory.
-bool dirExists(String dir) => new Directory(dir).existsSync();
-
-/// Tries to resiliently perform [operation].
-///
-/// Some file system operations can intermittently fail on Windows because
-/// other processes are locking a file. We've seen this with virus scanners
-/// when we try to delete or move something while it's being scanned. To
-/// mitigate that, on Windows, this will retry the operation a few times if it
-/// fails.
-void _attempt(String description, void operation()) {
- if (Platform.operatingSystem != 'windows') {
- operation();
- return;
- }
-
- getErrorReason(error) {
- if (error.osError.errorCode == 5) {
- return "access was denied";
- }
-
- if (error.osError.errorCode == 32) {
- return "it was in use by another process";
- }
-
- return null;
- }
-
- for (var i = 0; i < 2; i++) {
- try {
- operation();
- return;
- } on FileSystemException catch (error) {
- var reason = getErrorReason(error);
- if (reason == null) rethrow;
-
- log.io("Failed to $description because $reason. " "Retrying in 50ms.");
- sleep(new Duration(milliseconds: 50));
- }
- }
-
- try {
- operation();
- } on FileSystemException catch (error) {
- var reason = getErrorReason(error);
- if (reason == null) rethrow;
-
- fail(
- "Failed to $description because $reason.\n"
- "This may be caused by a virus scanner or having a file\n"
- "in the directory open in another application.");
- }
-}
-
-/// Deletes whatever's at [path], whether it's a file, directory, or symlink.
-///
-/// If it's a directory, it will be deleted recursively.
-void deleteEntry(String path) {
- _attempt("delete entry", () {
- if (linkExists(path)) {
- log.io("Deleting link $path.");
- new Link(path).deleteSync();
- } else if (dirExists(path)) {
- log.io("Deleting directory $path.");
- new Directory(path).deleteSync(recursive: true);
- } else if (fileExists(path)) {
- log.io("Deleting file $path.");
- new File(path).deleteSync();
- }
- });
-}
-
-/// Attempts to delete whatever's at [path], but doesn't throw an exception if
-/// the deletion fails.
-void tryDeleteEntry(String path) {
- try {
- deleteEntry(path);
- } catch (error, stackTrace) {
- log.fine(
- "Failed to delete $path: $error\n" "${new Chain.forTrace(stackTrace)}");
- }
-}
-
-/// "Cleans" [dir].
-///
-/// If that directory already exists, it is deleted. Then a new empty directory
-/// is created.
-void cleanDir(String dir) {
- if (entryExists(dir)) deleteEntry(dir);
- ensureDir(dir);
-}
-
-/// Renames (i.e. moves) the directory [from] to [to].
-void renameDir(String from, String to) {
- _attempt("rename directory", () {
- log.io("Renaming directory $from to $to.");
- try {
- new Directory(from).renameSync(to);
- } on IOException catch (error) {
- // Ensure that [to] isn't left in an inconsistent state. See issue 12436.
- if (entryExists(to)) deleteEntry(to);
- rethrow;
- }
- });
-}
-
-/// Creates a new symlink at path [symlink] that points to [target].
-///
-/// Returns a [Future] which completes to the path to the symlink file.
-///
-/// If [relative] is true, creates a symlink with a relative path from the
-/// symlink to the target. Otherwise, uses the [target] path unmodified.
-///
-/// Note that on Windows, only directories may be symlinked to.
-void createSymlink(String target, String symlink, {bool relative: false}) {
- if (relative) {
- // Relative junction points are not supported on Windows. Instead, just
- // make sure we have a clean absolute path because it will interpret a
- // relative path to be relative to the cwd, not the symlink, and will be
- // confused by forward slashes.
- if (Platform.operatingSystem == 'windows') {
- target = path.normalize(path.absolute(target));
- } else {
- // If the directory where we're creating the symlink was itself reached
- // by traversing a symlink, we want the relative path to be relative to
- // it's actual location, not the one we went through to get to it.
- var symlinkDir = canonicalize(path.dirname(symlink));
- target = path.normalize(path.relative(target, from: symlinkDir));
- }
- }
-
- log.fine("Creating $symlink pointing to $target");
- new Link(symlink).createSync(target);
-}
-
-/// Creates a new symlink that creates an alias at [symlink] that points to the
-/// `lib` directory of package [target].
-///
-/// If [target] does not have a `lib` directory, this shows a warning if
-/// appropriate and then does nothing.
-///
-/// If [relative] is true, creates a symlink with a relative path from the
-/// symlink to the target. Otherwise, uses the [target] path unmodified.
-void createPackageSymlink(String name, String target, String symlink,
- {bool isSelfLink: false, bool relative: false}) {
- // See if the package has a "lib" directory. If not, there's nothing to
- // symlink to.
- target = path.join(target, 'lib');
- if (!dirExists(target)) return;
-
- log.fine("Creating ${isSelfLink ? "self" : ""}link for package '$name'.");
- createSymlink(target, symlink, relative: relative);
-}
-
-/// Whether pub is running from within the Dart SDK, as opposed to from the Dart
-/// source repository.
-final bool runningFromSdk = Platform.script.path.endsWith('.snapshot');
-
-/// Resolves [target] relative to the path to pub's `asset` directory.
-String assetPath(String target) {
- if (runningFromSdk) {
- return path.join(
- sdk.rootDirectory,
- 'lib',
- '_internal',
- 'pub',
- 'asset',
- target);
- } else {
- return path.join(pubRoot, 'asset', target);
- }
-}
-
-/// Returns the path to the root of pub's sources in the Dart repo.
-String get pubRoot => path.join(repoRoot, 'sdk', 'lib', '_internal', 'pub');
-
-/// Returns the path to the root of the Dart repository.
-///
-/// This throws a [StateError] if it's called when running pub from the SDK.
-String get repoRoot {
- if (runningFromSdk) {
- throw new StateError("Can't get the repo root from the SDK.");
- }
-
- // Get the path to the directory containing this very file.
- var libDir = path.dirname(libraryPath('pub.io'));
-
- // TODO(rnystrom): Remove this when #104 is fixed.
- // If we are running from the async/await compiled build directory, walk out
- // out of that. It will be something like:
- //
- // <repo>/<build>/<config>/pub_async/lib/src
- if (libDir.contains('pub_async')) {
- return path.normalize(path.join(libDir, '..', '..', '..', '..', '..'));
- }
-
- // Otherwise, assume we're running directly from the source location in the
- // repo:
- //
- // <repo>/sdk/lib/_internal/pub/lib/src
- return path.normalize(path.join(libDir, '..', '..', '..', '..', '..', '..'));
-}
-
-/// A line-by-line stream of standard input.
-final Stream<String> stdinLines =
- streamToLines(new ByteStream(stdin).toStringStream());
-
-/// Displays a message and reads a yes/no confirmation from the user.
-///
-/// Returns a [Future] that completes to `true` if the user confirms or `false`
-/// if they do not.
-///
-/// This will automatically append " (y/n)?" to the message, so [message]
-/// should just be a fragment like, "Are you sure you want to proceed".
-Future<bool> confirm(String message) {
- log.fine('Showing confirm message: $message');
- if (runningAsTest) {
- log.message("$message (y/n)?");
- } else {
- stdout.write(log.format("$message (y/n)? "));
- }
- return streamFirst(
- stdinLines).then((line) => new RegExp(r"^[yY]").hasMatch(line));
-}
-
-/// Reads and discards all output from [stream].
-///
-/// Returns a [Future] that completes when the stream is closed.
-Future drainStream(Stream stream) {
- return stream.fold(null, (x, y) {});
-}
-
-/// Flushes the stdout and stderr streams, then exits the program with the given
-/// status code.
-///
-/// This returns a Future that will never complete, since the program will have
-/// exited already. This is useful to prevent Future chains from proceeding
-/// after you've decided to exit.
-Future flushThenExit(int status) {
- return Future.wait(
- [stdout.close(), stderr.close()]).then((_) => exit(status));
-}
-
-/// Returns a [EventSink] that pipes all data to [consumer] and a [Future] that
-/// will succeed when [EventSink] is closed or fail with any errors that occur
-/// while writing.
-Pair<EventSink, Future> consumerToSink(StreamConsumer consumer) {
- var controller = new StreamController(sync: true);
- var done = controller.stream.pipe(consumer);
- return new Pair<EventSink, Future>(controller.sink, done);
-}
-
-// TODO(nweiz): remove this when issue 7786 is fixed.
-/// Pipes all data and errors from [stream] into [sink].
-///
-/// When [stream] is done, the returned [Future] is completed and [sink] is
-/// closed if [closeSink] is true.
-///
-/// When an error occurs on [stream], that error is passed to [sink]. If
-/// [cancelOnError] is true, [Future] will be completed successfully and no
-/// more data or errors will be piped from [stream] to [sink]. If
-/// [cancelOnError] and [closeSink] are both true, [sink] will then be
-/// closed.
-Future store(Stream stream, EventSink sink, {bool cancelOnError: true,
- bool closeSink: true}) {
- var completer = new Completer();
- stream.listen(sink.add, onError: (e, stackTrace) {
- sink.addError(e, stackTrace);
- if (cancelOnError) {
- completer.complete();
- if (closeSink) sink.close();
- }
- }, onDone: () {
- if (closeSink) sink.close();
- completer.complete();
- }, cancelOnError: cancelOnError);
- return completer.future;
-}
-
-/// Spawns and runs the process located at [executable], passing in [args].
-///
-/// Returns a [Future] that will complete with the results of the process after
-/// it has ended.
-///
-/// The spawned process will inherit its parent's environment variables. If
-/// [environment] is provided, that will be used to augment (not replace) the
-/// the inherited variables.
-Future<PubProcessResult> runProcess(String executable, List<String> args,
- {workingDir, Map<String, String> environment}) {
- return _descriptorPool.withResource(() {
- return _doProcess(
- Process.run,
- executable,
- args,
- workingDir,
- environment).then((result) {
- var pubResult =
- new PubProcessResult(result.stdout, result.stderr, result.exitCode);
- log.processResult(executable, pubResult);
- return pubResult;
- });
- });
-}
-
-/// Spawns the process located at [executable], passing in [args].
-///
-/// Returns a [Future] that will complete with the [Process] once it's been
-/// started.
-///
-/// The spawned process will inherit its parent's environment variables. If
-/// [environment] is provided, that will be used to augment (not replace) the
-/// the inherited variables.
-Future<PubProcess> startProcess(String executable, List<String> args,
- {workingDir, Map<String, String> environment}) {
- return _descriptorPool.request().then((resource) {
- return _doProcess(
- Process.start,
- executable,
- args,
- workingDir,
- environment).then((ioProcess) {
- var process = new PubProcess(ioProcess);
- process.exitCode.whenComplete(resource.release);
- return process;
- });
- });
-}
-
-/// Like [runProcess], but synchronous.
-PubProcessResult runProcessSync(String executable, List<String> args,
- {String workingDir, Map<String, String> environment}) {
- var result =
- _doProcess(Process.runSync, executable, args, workingDir, environment);
- var pubResult =
- new PubProcessResult(result.stdout, result.stderr, result.exitCode);
- log.processResult(executable, pubResult);
- return pubResult;
-}
-
-/// A wrapper around [Process] that exposes `dart:async`-style APIs.
-class PubProcess {
- /// The underlying `dart:io` [Process].
- final Process _process;
-
- /// The mutable field for [stdin].
- EventSink<List<int>> _stdin;
-
- /// The mutable field for [stdinClosed].
- Future _stdinClosed;
-
- /// The mutable field for [stdout].
- ByteStream _stdout;
-
- /// The mutable field for [stderr].
- ByteStream _stderr;
-
- /// The mutable field for [exitCode].
- Future<int> _exitCode;
-
- /// The sink used for passing data to the process's standard input stream.
- ///
- /// Errors on this stream are surfaced through [stdinClosed], [stdout],
- /// [stderr], and [exitCode], which are all members of an [ErrorGroup].
- EventSink<List<int>> get stdin => _stdin;
-
- // TODO(nweiz): write some more sophisticated Future machinery so that this
- // doesn't surface errors from the other streams/futures, but still passes its
- // unhandled errors to them. Right now it's impossible to recover from a stdin
- // error and continue interacting with the process.
- /// A [Future] that completes when [stdin] is closed, either by the user or by
- /// the process itself.
- ///
- /// This is in an [ErrorGroup] with [stdout], [stderr], and [exitCode], so any
- /// error in process will be passed to it, but won't reach the top-level error
- /// handler unless nothing has handled it.
- Future get stdinClosed => _stdinClosed;
-
- /// The process's standard output stream.
- ///
- /// This is in an [ErrorGroup] with [stdinClosed], [stderr], and [exitCode],
- /// so any error in process will be passed to it, but won't reach the
- /// top-level error handler unless nothing has handled it.
- ByteStream get stdout => _stdout;
-
- /// The process's standard error stream.
- ///
- /// This is in an [ErrorGroup] with [stdinClosed], [stdout], and [exitCode],
- /// so any error in process will be passed to it, but won't reach the
- /// top-level error handler unless nothing has handled it.
- ByteStream get stderr => _stderr;
-
- /// A [Future] that will complete to the process's exit code once the process
- /// has finished running.
- ///
- /// This is in an [ErrorGroup] with [stdinClosed], [stdout], and [stderr], so
- /// any error in process will be passed to it, but won't reach the top-level
- /// error handler unless nothing has handled it.
- Future<int> get exitCode => _exitCode;
-
- /// Creates a new [PubProcess] wrapping [process].
- PubProcess(Process process)
- : _process = process {
- var errorGroup = new ErrorGroup();
-
- var pair = consumerToSink(process.stdin);
- _stdin = pair.first;
- _stdinClosed = errorGroup.registerFuture(pair.last);
-
- _stdout = new ByteStream(errorGroup.registerStream(process.stdout));
- _stderr = new ByteStream(errorGroup.registerStream(process.stderr));
-
- var exitCodeCompleter = new Completer();
- _exitCode = errorGroup.registerFuture(exitCodeCompleter.future);
- _process.exitCode.then((code) => exitCodeCompleter.complete(code));
- }
-
- /// Sends [signal] to the underlying process.
- bool kill([ProcessSignal signal = ProcessSignal.SIGTERM]) =>
- _process.kill(signal);
-}
-
-/// Calls [fn] with appropriately modified arguments.
-///
-/// [fn] should have the same signature as [Process.start], except that the
-/// returned value may have any return type.
-_doProcess(Function fn, String executable, List<String> args, String workingDir,
- Map<String, String> environment) {
- // TODO(rnystrom): Should dart:io just handle this?
- // Spawning a process on Windows will not look for the executable in the
- // system path. So, if executable looks like it needs that (i.e. it doesn't
- // have any path separators in it), then spawn it through a shell.
- if ((Platform.operatingSystem == "windows") &&
- (executable.indexOf('\\') == -1)) {
- args = flatten(["/c", executable, args]);
- executable = "cmd";
- }
-
- log.process(executable, args, workingDir == null ? '.' : workingDir);
-
- return fn(
- executable,
- args,
- workingDirectory: workingDir,
- environment: environment);
-}
-
-/// Wraps [input], an asynchronous network operation to provide a timeout.
-///
-/// If [input] completes before [milliseconds] have passed, then the return
-/// value completes in the same way. However, if [milliseconds] pass before
-/// [input] has completed, it completes with a [TimeoutException] with
-/// [description] (which should be a fragment describing the action that timed
-/// out).
-///
-/// [url] is the URL being accessed asynchronously.
-///
-/// Note that timing out will not cancel the asynchronous operation behind
-/// [input].
-Future timeout(Future input, int milliseconds, Uri url, String description) {
- // TODO(nwiez): Replace this with [Future.timeout].
- var completer = new Completer();
- var duration = new Duration(milliseconds: milliseconds);
- var timer = new Timer(duration, () {
- // Include the duration ourselves in the message instead of passing it to
- // TimeoutException since we show nicer output.
- var message =
- 'Timed out after ${niceDuration(duration)} while ' '$description.';
-
- if (url.host == "pub.dartlang.org" ||
- url.host == "storage.googleapis.com") {
- message += "\nThis is likely a transient error. Please try again later.";
- }
-
- completer.completeError(new TimeoutException(message), new Chain.current());
- });
- input.then((value) {
- if (completer.isCompleted) return;
- timer.cancel();
- completer.complete(value);
- }).catchError((e, stackTrace) {
- if (completer.isCompleted) return;
- timer.cancel();
- completer.completeError(e, stackTrace);
- });
- return completer.future;
-}
-
-/// Creates a temporary directory and passes its path to [fn].
-///
-/// Once the [Future] returned by [fn] completes, the temporary directory and
-/// all its contents are deleted. [fn] can also return `null`, in which case
-/// the temporary directory is deleted immediately afterwards.
-///
-/// Returns a future that completes to the value that the future returned from
-/// [fn] completes to.
-Future withTempDir(Future fn(String path)) {
- return new Future.sync(() {
- var tempDir = createSystemTempDir();
- return new Future.sync(
- () => fn(tempDir)).whenComplete(() => deleteEntry(tempDir));
- });
-}
-
-/// Binds an [HttpServer] to [host] and [port].
-///
-/// If [host] is "localhost", this will automatically listen on both the IPv4
-/// and IPv6 loopback addresses.
-Future<HttpServer> bindServer(String host, int port) {
- if (host == 'localhost') return HttpMultiServer.loopback(port);
- return HttpServer.bind(host, port);
-}
-
-/// Extracts a `.tar.gz` file from [stream] to [destination].
-///
-/// Returns whether or not the extraction was successful.
-Future<bool> extractTarGz(Stream<List<int>> stream, String destination) {
- log.fine("Extracting .tar.gz stream to $destination.");
-
- if (Platform.operatingSystem == "windows") {
- return _extractTarGzWindows(stream, destination);
- }
-
- var args = ["--extract", "--gunzip", "--directory", destination];
- if (_noUnknownKeyword) {
- // BSD tar (the default on OS X) can insert strange headers to a tarfile
- // that GNU tar (the default on Linux) is unable to understand. This will
- // cause GNU tar to emit a number of harmless but scary-looking warnings
- // which are silenced by this flag.
- args.insert(0, "--warning=no-unknown-keyword");
- }
-
- return startProcess("tar", args).then((process) {
- // Ignore errors on process.std{out,err}. They'll be passed to
- // process.exitCode, and we don't want them being top-levelled by
- // std{out,err}Sink.
- store(process.stdout.handleError((_) {}), stdout, closeSink: false);
- store(process.stderr.handleError((_) {}), stderr, closeSink: false);
- return Future.wait([store(stream, process.stdin), process.exitCode]);
- }).then((results) {
- var exitCode = results[1];
- if (exitCode != exit_codes.SUCCESS) {
- throw new Exception(
- "Failed to extract .tar.gz stream to $destination " "(exit code $exitCode).");
- }
- log.fine("Extracted .tar.gz stream to $destination. Exit code $exitCode.");
- });
-}
-
-/// Whether to include "--warning=no-unknown-keyword" when invoking tar.
-///
-/// This flag quiets warnings that come from opening OS X-generated tarballs on
-/// Linux, but only GNU tar >= 1.26 supports it.
-final bool _noUnknownKeyword = _computeNoUnknownKeyword();
-bool _computeNoUnknownKeyword() {
- if (!Platform.isLinux) return false;
- var result = Process.runSync("tar", ["--version"]);
- if (result.exitCode != 0) {
- throw new ApplicationException(
- "Failed to run tar (exit code ${result.exitCode}):\n${result.stderr}");
- }
-
- var match =
- new RegExp(r"^tar \(GNU tar\) (\d+).(\d+)\n").firstMatch(result.stdout);
- if (match == null) return false;
-
- var major = int.parse(match[1]);
- var minor = int.parse(match[2]);
- return major >= 2 || (major == 1 && minor >= 23);
-}
-
-String get pathTo7zip {
- if (runningFromSdk) return assetPath(path.join('7zip', '7za.exe'));
- return path.join(repoRoot, 'third_party', '7zip', '7za.exe');
-}
-
-Future<bool> _extractTarGzWindows(Stream<List<int>> stream, String destination)
- {
- // TODO(rnystrom): In the repo's history, there is an older implementation of
- // this that does everything in memory by piping streams directly together
- // instead of writing out temp files. The code is simpler, but unfortunately,
- // 7zip seems to periodically fail when we invoke it from Dart and tell it to
- // read from stdin instead of a file. Consider resurrecting that version if
- // we can figure out why it fails.
-
- return withTempDir((tempDir) {
- // Write the archive to a temp file.
- var dataFile = path.join(tempDir, 'data.tar.gz');
- return createFileFromStream(stream, dataFile).then((_) {
- // 7zip can't unarchive from gzip -> tar -> destination all in one step
- // first we un-gzip it to a tar file.
- // Note: Setting the working directory instead of passing in a full file
- // path because 7zip says "A full path is not allowed here."
- return runProcess(pathTo7zip, ['e', 'data.tar.gz'], workingDir: tempDir);
- }).then((result) {
- if (result.exitCode != exit_codes.SUCCESS) {
- throw new Exception(
- 'Could not un-gzip (exit code ${result.exitCode}). ' 'Error:\n'
- '${result.stdout.join("\n")}\n' '${result.stderr.join("\n")}');
- }
-
- // Find the tar file we just created since we don't know its name.
- var tarFile = listDir(
- tempDir).firstWhere((file) => path.extension(file) == '.tar', orElse: () {
- throw new FormatException('The gzip file did not contain a tar file.');
- });
-
- // Untar the archive into the destination directory.
- return runProcess(pathTo7zip, ['x', tarFile], workingDir: destination);
- }).then((result) {
- if (result.exitCode != exit_codes.SUCCESS) {
- throw new Exception(
- 'Could not un-tar (exit code ${result.exitCode}). ' 'Error:\n'
- '${result.stdout.join("\n")}\n' '${result.stderr.join("\n")}');
- }
- return true;
- });
- });
-}
-
-/// Create a .tar.gz archive from a list of entries.
-///
-/// Each entry can be a [String], [Directory], or [File] object. The root of
-/// the archive is considered to be [baseDir], which defaults to the current
-/// working directory.
-///
-/// Returns a [ByteStream] that emits the contents of the archive.
-ByteStream createTarGz(List contents, {baseDir}) {
- return new ByteStream(futureStream(new Future.sync(() {
- var buffer = new StringBuffer();
- buffer.write('Creating .tag.gz stream containing:\n');
- contents.forEach((file) => buffer.write('$file\n'));
- log.fine(buffer.toString());
-
- if (baseDir == null) baseDir = path.current;
- baseDir = path.absolute(baseDir);
- contents = contents.map((entry) {
- entry = path.absolute(entry);
- if (!path.isWithin(baseDir, entry)) {
- throw new ArgumentError('Entry $entry is not inside $baseDir.');
- }
- return path.relative(entry, from: baseDir);
- }).toList();
-
- if (Platform.operatingSystem != "windows") {
- var args = ["--create", "--gzip", "--directory", baseDir];
- args.addAll(contents);
- // TODO(nweiz): It's possible that enough command-line arguments will
- // make the process choke, so at some point we should save the arguments
- // to a file and pass them in via --files-from for tar and -i@filename
- // for 7zip.
- return startProcess("tar", args).then((process) => process.stdout);
- }
-
- // Don't use [withTempDir] here because we don't want to delete the temp
- // directory until the returned stream has closed.
- var tempDir = createSystemTempDir();
- return new Future.sync(() {
- // Create the tar file.
- var tarFile = path.join(tempDir, "intermediate.tar");
- var args = ["a", "-w$baseDir", tarFile];
- args.addAll(contents.map((entry) => '-i!$entry'));
-
- // We're passing 'baseDir' both as '-w' and setting it as the working
- // directory explicitly here intentionally. The former ensures that the
- // files added to the archive have the correct relative path in the
- // archive. The latter enables relative paths in the "-i" args to be
- // resolved.
- return runProcess(pathTo7zip, args, workingDir: baseDir).then((_) {
- // GZIP it. 7zip doesn't support doing both as a single operation.
- // Send the output to stdout.
- args = ["a", "unused", "-tgzip", "-so", tarFile];
- return startProcess(pathTo7zip, args);
- }).then((process) => process.stdout);
- }).then((stream) {
- return stream.transform(onDoneTransformer(() => deleteEntry(tempDir)));
- }).catchError((e) {
- deleteEntry(tempDir);
- throw e;
- });
- })));
-}
-
-/// Contains the results of invoking a [Process] and waiting for it to complete.
-class PubProcessResult {
- final List<String> stdout;
- final List<String> stderr;
- final int exitCode;
-
- PubProcessResult(String stdout, String stderr, this.exitCode)
- : this.stdout = _toLines(stdout),
- this.stderr = _toLines(stderr);
-
- // TODO(rnystrom): Remove this and change to returning one string.
- static List<String> _toLines(String output) {
- var lines = splitLines(output);
- if (!lines.isEmpty && lines.last == "") lines.removeLast();
- return lines;
- }
-
- bool get success => exitCode == exit_codes.SUCCESS;
-}
-
-/// Gets a [Uri] for [uri], which can either already be one, or be a [String].
-Uri _getUri(uri) {
- if (uri is Uri) return uri;
- return Uri.parse(uri);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/lock_file.dart b/sdk/lib/_internal/pub_generated/lib/src/lock_file.dart
deleted file mode 100644
index fa964c7..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/lock_file.dart
+++ /dev/null
@@ -1,147 +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 pub.lock_file;
-
-import 'package:path/path.dart' as p;
-import 'package:pub_semver/pub_semver.dart';
-import 'package:source_span/source_span.dart';
-import 'package:yaml/yaml.dart';
-
-import 'io.dart';
-import 'package.dart';
-import 'source_registry.dart';
-import 'utils.dart';
-
-/// A parsed and validated `pubspec.lock` file.
-class LockFile {
- /// The packages this lockfile pins.
- Map<String, PackageId> packages;
-
- /// Creates a new lockfile containing [ids].
- factory LockFile(List<PackageId> ids) {
- var lockFile = new LockFile.empty();
- for (var id in ids) {
- if (!id.isRoot) lockFile.packages[id.name] = id;
- }
-
- return lockFile;
- }
-
- LockFile._(this.packages);
-
- LockFile.empty()
- : packages = <String, PackageId>{};
-
- /// Loads a lockfile from [filePath].
- factory LockFile.load(String filePath, SourceRegistry sources) {
- return LockFile._parse(filePath, readTextFile(filePath), sources);
- }
-
- /// Parses a lockfile whose text is [contents].
- factory LockFile.parse(String contents, SourceRegistry sources) {
- return LockFile._parse(null, contents, sources);
- }
-
- /// Parses the lockfile whose text is [contents].
- ///
- /// [filePath] is the system-native path to the lockfile on disc. It may be
- /// `null`.
- static LockFile _parse(String filePath, String contents,
- SourceRegistry sources) {
- var packages = <String, PackageId>{};
-
- if (contents.trim() == '') return new LockFile.empty();
-
- var sourceUrl;
- if (filePath != null) sourceUrl = p.toUri(filePath);
- var parsed = loadYamlNode(contents, sourceUrl: sourceUrl);
-
- _validate(parsed is Map, 'The lockfile must be a YAML mapping.', parsed);
-
- var packageEntries = parsed['packages'];
- if (packageEntries != null) {
- _validate(
- packageEntries is Map,
- 'The "packages" field must be a map.',
- parsed.nodes['packages']);
-
- packageEntries.forEach((name, spec) {
- // Parse the version.
- _validate(
- spec.containsKey('version'),
- 'Package $name is missing a version.',
- spec);
- var version = new Version.parse(spec['version']);
-
- // Parse the source.
- _validate(
- spec.containsKey('source'),
- 'Package $name is missing a source.',
- spec);
- var sourceName = spec['source'];
-
- _validate(
- spec.containsKey('description'),
- 'Package $name is missing a description.',
- spec);
- var description = spec['description'];
-
- // Let the source parse the description.
- var source = sources[sourceName];
- try {
- description =
- source.parseDescription(filePath, description, fromLockFile: true);
- } on FormatException catch (ex) {
- throw new SourceSpanFormatException(
- ex.message,
- spec.nodes['source'].span);
- }
-
- var id = new PackageId(name, sourceName, version, description);
-
- // Validate the name.
- _validate(
- name == id.name,
- "Package name $name doesn't match ${id.name}.",
- spec);
-
- packages[name] = id;
- });
- }
-
- return new LockFile._(packages);
- }
-
- /// If [condition] is `false` throws a format error with [message] for [node].
- static void _validate(bool condition, String message, YamlNode node) {
- if (condition) return;
- throw new SourceSpanFormatException(message, node.span);
- }
-
- /// Returns the serialized YAML text of the lock file.
- ///
- /// [packageDir] is the containing directory of the root package, used to
- /// properly serialize package descriptions.
- String serialize(String packageDir, SourceRegistry sources) {
- // Convert the dependencies to a simple object.
- var data = {};
- packages.forEach((name, package) {
- var description =
- sources[package.source].serializeDescription(packageDir, package.description);
-
- data[name] = {
- 'version': package.version.toString(),
- 'source': package.source,
- 'description': description
- };
- });
-
- return """
-# Generated by pub
-# See http://pub.dartlang.org/doc/glossary.html#lockfile
-${yamlToString({'packages': data})}
-""";
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/log.dart b/sdk/lib/_internal/pub_generated/lib/src/log.dart
deleted file mode 100644
index ecf67ed..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/log.dart
+++ /dev/null
@@ -1,551 +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.
-
-/// Message logging.
-library pub.log;
-
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:args/command_runner.dart';
-import 'package:path/path.dart' as p;
-import 'package:source_span/source_span.dart';
-import 'package:stack_trace/stack_trace.dart';
-
-import 'exceptions.dart';
-import 'io.dart';
-import 'progress.dart';
-import 'transcript.dart';
-import 'utils.dart';
-
-/// The singleton instance so that we can have a nice api like:
-///
-/// log.json.error(...);
-final json = new _JsonLogger();
-
-/// The current logging verbosity.
-Verbosity verbosity = Verbosity.NORMAL;
-
-/// Whether or not to log entries with prejudice.
-bool withPrejudice = false;
-
-/// In cases where there's a ton of log spew, make sure we don't eat infinite
-/// memory.
-///
-/// This can occur when the backtracking solver stumbles into a pathological
-/// dependency graph. It generally will find a solution, but it may log
-/// thousands and thousands of entries to get there.
-const _MAX_TRANSCRIPT = 10000;
-
-/// The list of recorded log messages. Will only be recorded if
-/// [recordTranscript()] is called.
-Transcript<Entry> _transcript;
-
-/// The currently-animated progress indicator, if any.
-///
-/// This will also be in [_progresses].
-Progress _animatedProgress;
-
-final _cyan = getSpecial('\u001b[36m');
-final _green = getSpecial('\u001b[32m');
-final _magenta = getSpecial('\u001b[35m');
-final _red = getSpecial('\u001b[31m');
-final _yellow = getSpecial('\u001b[33m');
-final _gray = getSpecial('\u001b[1;30m');
-final _none = getSpecial('\u001b[0m');
-final _noColor = getSpecial('\u001b[39m');
-final _bold = getSpecial('\u001b[1m');
-
-/// An enum type for defining the different logging levels a given message can
-/// be associated with.
-///
-/// By default, [ERROR] and [WARNING] messages are printed to sterr. [MESSAGE]
-/// messages are printed to stdout, and others are ignored.
-class Level {
- /// An error occurred and an operation could not be completed.
- ///
- /// Usually shown to the user on stderr.
- static const ERROR = const Level._("ERR ");
-
- /// Something unexpected happened, but the program was able to continue,
- /// though possibly in a degraded fashion.
- static const WARNING = const Level._("WARN");
-
- /// A message intended specifically to be shown to the user.
- static const MESSAGE = const Level._("MSG ");
-
- /// Some interaction with the external world occurred, such as a network
- /// operation, process spawning, or file IO.
- static const IO = const Level._("IO ");
-
- /// Incremental output during pub's version constraint solver.
- static const SOLVER = const Level._("SLVR");
-
- /// Fine-grained and verbose additional information.
- ///
- /// Used to provide program state context for other logs (such as what pub
- /// was doing when an IO operation occurred) or just more detail for an
- /// operation.
- static const FINE = const Level._("FINE");
-
- const Level._(this.name);
- final String name;
-
- String toString() => name;
-}
-
-typedef _LogFn(Entry entry);
-
-/// An enum type to control which log levels are displayed and how they are
-/// displayed.
-class Verbosity {
- /// Silence all logging.
- static const NONE = const Verbosity._("none", const {
- Level.ERROR: null,
- Level.WARNING: null,
- Level.MESSAGE: null,
- Level.IO: null,
- Level.SOLVER: null,
- Level.FINE: null
- });
-
- /// Shows only errors and warnings.
- static const WARNING = const Verbosity._("warning", const {
- Level.ERROR: _logToStderr,
- Level.WARNING: _logToStderr,
- Level.MESSAGE: null,
- Level.IO: null,
- Level.SOLVER: null,
- Level.FINE: null
- });
-
- /// The default verbosity which shows errors, warnings, and messages.
- static const NORMAL = const Verbosity._("normal", const {
- Level.ERROR: _logToStderr,
- Level.WARNING: _logToStderr,
- Level.MESSAGE: _logToStdout,
- Level.IO: null,
- Level.SOLVER: null,
- Level.FINE: null
- });
-
- /// Shows errors, warnings, messages, and IO event logs.
- static const IO = const Verbosity._("io", const {
- Level.ERROR: _logToStderrWithLabel,
- Level.WARNING: _logToStderrWithLabel,
- Level.MESSAGE: _logToStdoutWithLabel,
- Level.IO: _logToStderrWithLabel,
- Level.SOLVER: null,
- Level.FINE: null
- });
-
- /// Shows errors, warnings, messages, and version solver logs.
- static const SOLVER = const Verbosity._("solver", const {
- Level.ERROR: _logToStderr,
- Level.WARNING: _logToStderr,
- Level.MESSAGE: _logToStdout,
- Level.IO: null,
- Level.SOLVER: _logToStdout,
- Level.FINE: null
- });
-
- /// Shows all logs.
- static const ALL = const Verbosity._("all", const {
- Level.ERROR: _logToStderrWithLabel,
- Level.WARNING: _logToStderrWithLabel,
- Level.MESSAGE: _logToStdoutWithLabel,
- Level.IO: _logToStderrWithLabel,
- Level.SOLVER: _logToStderrWithLabel,
- Level.FINE: _logToStderrWithLabel
- });
-
- const Verbosity._(this.name, this._loggers);
- final String name;
- final Map<Level, _LogFn> _loggers;
-
- /// Returns whether or not logs at [level] will be printed.
- bool isLevelVisible(Level level) => _loggers[level] != null;
-
- String toString() => name;
-}
-
-/// A single log entry.
-class Entry {
- final Level level;
- final List<String> lines;
-
- Entry(this.level, this.lines);
-}
-
-/// Logs [message] at [Level.ERROR].
-///
-/// If [error] is passed, it's appended to [message]. If [trace] is passed, it's
-/// printed at log level fine.
-void error(message, [error, StackTrace trace]) {
- if (error != null) {
- message = "$message: $error";
- if (error is Error && trace == null) trace = error.stackTrace;
- }
- write(Level.ERROR, message);
- if (trace != null) write(Level.FINE, new Chain.forTrace(trace));
-}
-
-/// Logs [message] at [Level.WARNING].
-void warning(message) => write(Level.WARNING, message);
-
-/// Logs [message] at [Level.MESSAGE].
-void message(message) => write(Level.MESSAGE, message);
-
-/// Logs [message] at [Level.IO].
-void io(message) => write(Level.IO, message);
-
-/// Logs [message] at [Level.SOLVER].
-void solver(message) => write(Level.SOLVER, message);
-
-/// Logs [message] at [Level.FINE].
-void fine(message) => write(Level.FINE, message);
-
-/// Logs [message] at [level].
-void write(Level level, message) {
- message = message.toString();
- var lines = splitLines(message);
-
- // Discard a trailing newline. This is useful since StringBuffers often end
- // up with an extra newline at the end from using [writeln].
- if (lines.isNotEmpty && lines.last == "") {
- lines.removeLast();
- }
-
- var entry = new Entry(level, lines.map(format).toList());
-
- var logFn = verbosity._loggers[level];
- if (logFn != null) logFn(entry);
-
- if (_transcript != null) _transcript.add(entry);
-}
-
-final _capitalizedAnsiEscape = new RegExp(r'\u001b\[\d+(;\d+)?M');
-
-/// Returns [string] formatted as it would be if it were logged.
-String format(String string) {
- if (!withPrejudice) return string;
-
- // [toUpperCase] can corrupt terminal colorings, so fix them up using
- // [replaceAllMapped].
- string = string.toUpperCase().replaceAllMapped(
- _capitalizedAnsiEscape,
- (match) => match[0].toLowerCase());
-
- // Don't use [bold] because it's disabled under [withPrejudice].
- return "$_bold$string$_none";
-}
-
-/// Logs an asynchronous IO operation.
-///
-/// Logs [startMessage] before the operation starts, then when [operation]
-/// completes, invokes [endMessage] with the completion value and logs the
-/// result of that. Returns a future that completes after the logging is done.
-///
-/// If [endMessage] is omitted, then logs "Begin [startMessage]" before the
-/// operation and "End [startMessage]" after it.
-Future ioAsync(String startMessage, Future operation, [String
- endMessage(value)]) {
- if (endMessage == null) {
- io("Begin $startMessage.");
- } else {
- io(startMessage);
- }
-
- return operation.then((result) {
- if (endMessage == null) {
- io("End $startMessage.");
- } else {
- io(endMessage(result));
- }
- return result;
- });
-}
-
-/// Logs the spawning of an [executable] process with [arguments] at [IO]
-/// level.
-void process(String executable, List<String> arguments, String workingDirectory)
- {
- io(
- "Spawning \"$executable ${arguments.join(' ')}\" in "
- "${p.absolute(workingDirectory)}");
-}
-
-/// Logs the results of running [executable].
-void processResult(String executable, PubProcessResult result) {
- // Log it all as one message so that it shows up as a single unit in the logs.
- var buffer = new StringBuffer();
- buffer.writeln("Finished $executable. Exit code ${result.exitCode}.");
-
- dumpOutput(String name, List<String> output) {
- if (output.length == 0) {
- buffer.writeln("Nothing output on $name.");
- } else {
- buffer.writeln("$name:");
- var numLines = 0;
- for (var line in output) {
- if (++numLines > 1000) {
- buffer.writeln(
- '[${output.length - 1000}] more lines of output ' 'truncated...]');
- break;
- }
-
- buffer.writeln("| $line");
- }
- }
- }
-
- dumpOutput("stdout", result.stdout);
- dumpOutput("stderr", result.stderr);
-
- io(buffer.toString().trim());
-}
-
-/// Logs an exception.
-void exception(exception, [StackTrace trace]) {
- if (exception is SilentException) return;
-
- var chain = trace == null ? new Chain.current() : new Chain.forTrace(trace);
-
- // This is basically the top-level exception handler so that we don't
- // spew a stack trace on our users.
- if (exception is SourceSpanException) {
- error(exception.toString(color: canUseSpecialChars));
- } else {
- error(getErrorMessage(exception));
- }
- fine("Exception type: ${exception.runtimeType}");
-
- if (json.enabled) {
- if (exception is UsageException) {
- // Don't print usage info in JSON output.
- json.error(exception.message);
- } else {
- json.error(exception);
- }
- }
-
- if (!isUserFacingException(exception)) {
- error(chain.terse);
- } else {
- fine(chain.terse);
- }
-
- if (exception is WrappedException && exception.innerError != null) {
- var message = "Wrapped exception: ${exception.innerError}";
- if (exception.innerChain != null) {
- message = "$message\n${exception.innerChain}";
- }
- fine(message);
- }
-}
-
-/// Enables recording of log entries.
-void recordTranscript() {
- _transcript = new Transcript<Entry>(_MAX_TRANSCRIPT);
-}
-
-/// If [recordTranscript()] was called, then prints the previously recorded log
-/// transcript to stderr.
-void dumpTranscript() {
- if (_transcript == null) return;
-
- stderr.writeln('---- Log transcript ----');
- _transcript.forEach((entry) {
- _printToStream(stderr, entry, showLabel: true);
- }, (discarded) {
- stderr.writeln('---- ($discarded discarded) ----');
- });
- stderr.writeln('---- End log transcript ----');
-}
-
-/// Prints [message] then displays an updated elapsed time until the future
-/// returned by [callback] completes.
-///
-/// If anything else is logged during this (including another call to
-/// [progress]) that cancels the progress animation, although the total time
-/// will still be printed once it finishes. If [fine] is passed, the progress
-/// information will only be visible at [Level.FINE].
-Future progress(String message, Future callback(), {bool fine: false}) {
- _stopProgress();
-
- var progress = new Progress(message, fine: fine);
- _animatedProgress = progress;
- return callback().whenComplete(progress.stop);
-}
-
-/// Stops animating the running progress indicator, if currently running.
-void _stopProgress() {
- if (_animatedProgress != null) _animatedProgress.stopAnimating();
- _animatedProgress = null;
-}
-
-/// The number of outstanding calls to [muteProgress] that have not been unmuted
-/// yet.
-int _numMutes = 0;
-
-/// Whether progress animation should be muted or not.
-bool get isMuted => _numMutes > 0;
-
-/// Stops animating any ongoing progress.
-///
-/// This is called before spawning Git since Git sometimes writes directly to
-/// the terminal to ask for login credentials, which would then get overwritten
-/// by the progress animation.
-///
-/// Each call to this must be paired with a call to [unmuteProgress].
-void muteProgress() {
- _numMutes++;
-}
-
-/// Resumes animating any ongoing progress once all calls to [muteProgress]
-/// have made their matching [unmuteProgress].
-void unmuteProgress() {
- assert(_numMutes > 0);
- _numMutes--;
-}
-
-/// Wraps [text] in the ANSI escape codes to make it bold when on a platform
-/// that supports that.
-///
-/// Use this to highlight the most important piece of a long chunk of text.
-///
-/// This is disabled under [withPrejudice] since all text is bold with
-/// prejudice.
-String bold(text) => withPrejudice ? text : "$_bold$text$_none";
-
-/// Wraps [text] in the ANSI escape codes to make it gray when on a platform
-/// that supports that.
-///
-/// Use this for text that's less important than the text around it.
-///
-/// The gray marker also enables bold, so it needs to be handled specially with
-/// [withPrejudice] to avoid disabling bolding entirely.
-String gray(text) =>
- withPrejudice ? "$_gray$text$_noColor" : "$_gray$text$_none";
-
-/// Wraps [text] in the ANSI escape codes to color it cyan when on a platform
-/// that supports that.
-///
-/// Use this to highlight something interesting but neither good nor bad.
-String cyan(text) => "$_cyan$text$_noColor";
-
-/// Wraps [text] in the ANSI escape codes to color it green when on a platform
-/// that supports that.
-///
-/// Use this to highlight something successful or otherwise positive.
-String green(text) => "$_green$text$_noColor";
-
-/// Wraps [text] in the ANSI escape codes to color it magenta when on a
-/// platform that supports that.
-///
-/// Use this to highlight something risky that the user should be aware of but
-/// may intend to do.
-String magenta(text) => "$_magenta$text$_noColor";
-
-/// Wraps [text] in the ANSI escape codes to color it red when on a platform
-/// that supports that.
-///
-/// Use this to highlight unequivocal errors, problems, or failures.
-String red(text) => "$_red$text$_noColor";
-
-/// Wraps [text] in the ANSI escape codes to color it yellow when on a platform
-/// that supports that.
-///
-/// Use this to highlight warnings, cautions or other things that are bad but
-/// do not prevent the user's goal from being reached.
-String yellow(text) => "$_yellow$text$_noColor";
-
-/// Log function that prints the message to stdout.
-void _logToStdout(Entry entry) {
- _logToStream(stdout, entry, showLabel: false);
-}
-
-/// Log function that prints the message to stdout with the level name.
-void _logToStdoutWithLabel(Entry entry) {
- _logToStream(stdout, entry, showLabel: true);
-}
-
-/// Log function that prints the message to stderr.
-void _logToStderr(Entry entry) {
- _logToStream(stderr, entry, showLabel: false);
-}
-
-/// Log function that prints the message to stderr with the level name.
-void _logToStderrWithLabel(Entry entry) {
- _logToStream(stderr, entry, showLabel: true);
-}
-
-void _logToStream(IOSink sink, Entry entry, {bool showLabel}) {
- if (json.enabled) return;
-
- _printToStream(sink, entry, showLabel: showLabel);
-}
-
-void _printToStream(IOSink sink, Entry entry, {bool showLabel}) {
- _stopProgress();
-
- bool firstLine = true;
- for (var line in entry.lines) {
- if (showLabel) {
- if (firstLine) {
- sink.write('${entry.level.name}: ');
- } else {
- sink.write(' | ');
- }
- }
-
- sink.writeln(line);
-
- firstLine = false;
- }
-}
-
-/// Namespace-like class for collecting the methods for JSON logging.
-class _JsonLogger {
- /// Whether logging should use machine-friendly JSON output or human-friendly
- /// text.
- ///
- /// If set to `true`, then no regular logging is printed. Logged messages
- /// will still be recorded and displayed if the transcript is printed.
- bool enabled = false;
-
- /// Creates an error JSON object for [error] and prints it if JSON output
- /// is enabled.
- ///
- /// Always prints to stdout.
- void error(error, [stackTrace]) {
- var errorJson = {
- "error": error.toString()
- };
-
- if (stackTrace == null && error is Error) stackTrace = error.stackTrace;
- if (stackTrace != null) {
- errorJson["stackTrace"] = new Chain.forTrace(stackTrace).toString();
- }
-
- // If the error came from a file, include the path.
- if (error is SourceSpanException && error.span.sourceUrl != null) {
- errorJson["path"] = p.fromUri(error.span.sourceUrl);
- }
-
- if (error is FileException) {
- errorJson["path"] = error.path;
- }
-
- this.message(errorJson);
- }
-
- /// Encodes [message] to JSON and prints it if JSON output is enabled.
- void message(message) {
- if (!enabled) return;
-
- print(JSON.encode(message));
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/oauth2.dart b/sdk/lib/_internal/pub_generated/lib/src/oauth2.dart
deleted file mode 100644
index 6edac4b..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/oauth2.dart
+++ /dev/null
@@ -1,222 +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 pub.oauth2;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:oauth2/oauth2.dart';
-import 'package:path/path.dart' as path;
-import 'package:shelf/shelf.dart' as shelf;
-import 'package:shelf/shelf_io.dart' as shelf_io;
-
-import 'http.dart';
-import 'io.dart';
-import 'log.dart' as log;
-import 'system_cache.dart';
-import 'utils.dart';
-
-export 'package:oauth2/oauth2.dart';
-
-/// The pub client's OAuth2 identifier.
-final _identifier =
- '818368855108-8grd2eg9tj9f38os6f1urbcvsq399u8n.apps.' 'googleusercontent.com';
-
-/// The pub client's OAuth2 secret.
-///
-/// This isn't actually meant to be kept a secret.
-final _secret = 'SWeqj8seoJW0w7_CpEPFLX0K';
-
-/// The URL to which the user will be directed to authorize the pub client to
-/// get an OAuth2 access token.
-///
-/// `access_type=offline` and `approval_prompt=force` ensures that we always get
-/// a refresh token from the server. See the [Google OAuth2 documentation][].
-///
-/// [Google OAuth2 documentation]: https://developers.google.com/accounts/docs/OAuth2WebServer#offline
-final authorizationEndpoint = Uri.parse(
- 'https://accounts.google.com/o/oauth2/auth?access_type=offline'
- '&approval_prompt=force');
-
-/// The URL from which the pub client will request an access token once it's
-/// been authorized by the user.
-///
-/// This can be controlled externally by setting the `_PUB_TEST_TOKEN_ENDPOINT`
-/// environment variable.
-Uri get tokenEndpoint {
- var tokenEndpoint = Platform.environment['_PUB_TEST_TOKEN_ENDPOINT'];
- if (tokenEndpoint != null) {
- return Uri.parse(tokenEndpoint);
- } else {
- return _tokenEndpoint;
- }
-}
-
-final _tokenEndpoint = Uri.parse('https://accounts.google.com/o/oauth2/token');
-
-/// The OAuth2 scopes that the pub client needs.
-///
-/// Currently the client only needs the user's email so that the server can
-/// verify their identity.
-final _scopes = ['https://www.googleapis.com/auth/userinfo.email'];
-
-/// An in-memory cache of the user's OAuth2 credentials.
-///
-/// This should always be the same as the credentials file stored in the system
-/// cache.
-Credentials _credentials;
-
-/// Delete the cached credentials, if they exist.
-void clearCredentials(SystemCache cache) {
- _credentials = null;
- var credentialsFile = _credentialsFile(cache);
- if (entryExists(credentialsFile)) deleteEntry(credentialsFile);
-}
-
-/// Asynchronously passes an OAuth2 [Client] to [fn], and closes the client when
-/// the [Future] returned by [fn] completes.
-///
-/// This takes care of loading and saving the client's credentials, as well as
-/// prompting the user for their authorization. It will also re-authorize and
-/// re-run [fn] if a recoverable authorization error is detected.
-Future withClient(SystemCache cache, Future fn(Client client)) {
- return _getClient(cache).then((client) {
- var completer = new Completer();
- return fn(client).whenComplete(() {
- client.close();
- // Be sure to save the credentials even when an error happens.
- _saveCredentials(cache, client.credentials);
- });
- }).catchError((error) {
- if (error is ExpirationException) {
- log.error(
- "Pub's authorization to upload packages has expired and "
- "can't be automatically refreshed.");
- return withClient(cache, fn);
- } else if (error is AuthorizationException) {
- var message = "OAuth2 authorization failed";
- if (error.description != null) {
- message = "$message (${error.description})";
- }
- log.error("$message.");
- clearCredentials(cache);
- return withClient(cache, fn);
- } else {
- throw error;
- }
- });
-}
-
-/// Gets a new OAuth2 client.
-///
-/// If saved credentials are available, those are used; otherwise, the user is
-/// prompted to authorize the pub client.
-Future<Client> _getClient(SystemCache cache) {
- return new Future.sync(() {
- var credentials = _loadCredentials(cache);
- if (credentials == null) return _authorize();
-
- var client =
- new Client(_identifier, _secret, credentials, httpClient: httpClient);
- _saveCredentials(cache, client.credentials);
- return client;
- });
-}
-
-/// Loads the user's OAuth2 credentials from the in-memory cache or the
-/// filesystem if possible.
-///
-/// If the credentials can't be loaded for any reason, the returned [Future]
-/// completes to `null`.
-Credentials _loadCredentials(SystemCache cache) {
- log.fine('Loading OAuth2 credentials.');
-
- try {
- if (_credentials != null) return _credentials;
-
- var path = _credentialsFile(cache);
- if (!fileExists(path)) return null;
-
- var credentials = new Credentials.fromJson(readTextFile(path));
- if (credentials.isExpired && !credentials.canRefresh) {
- log.error(
- "Pub's authorization to upload packages has expired and "
- "can't be automatically refreshed.");
- return null; // null means re-authorize.
- }
-
- return credentials;
- } catch (e) {
- log.error(
- 'Warning: could not load the saved OAuth2 credentials: $e\n'
- 'Obtaining new credentials...');
- return null; // null means re-authorize.
- }
-}
-
-/// Save the user's OAuth2 credentials to the in-memory cache and the
-/// filesystem.
-void _saveCredentials(SystemCache cache, Credentials credentials) {
- log.fine('Saving OAuth2 credentials.');
- _credentials = credentials;
- var credentialsPath = _credentialsFile(cache);
- ensureDir(path.dirname(credentialsPath));
- writeTextFile(credentialsPath, credentials.toJson(), dontLogContents: true);
-}
-
-/// The path to the file in which the user's OAuth2 credentials are stored.
-String _credentialsFile(SystemCache cache) =>
- path.join(cache.rootDir, 'credentials.json');
-
-/// Gets the user to authorize pub as a client of pub.dartlang.org via oauth2.
-///
-/// Returns a Future that completes to a fully-authorized [Client].
-Future<Client> _authorize() {
- var grant = new AuthorizationCodeGrant(
- _identifier,
- _secret,
- authorizationEndpoint,
- tokenEndpoint,
- httpClient: httpClient);
-
- // Spin up a one-shot HTTP server to receive the authorization code from the
- // Google OAuth2 server via redirect. This server will close itself as soon as
- // the code is received.
- var completer = new Completer();
- bindServer('localhost', 0).then((server) {
- shelf_io.serveRequests(server, (request) {
- if (request.url.path != "/") {
- return new shelf.Response.notFound('Invalid URI.');
- }
-
- log.message('Authorization received, processing...');
- var queryString = request.url.query;
- if (queryString == null) queryString = '';
-
- // Closing the server here is safe, since it will wait until the response
- // is sent to actually shut down.
- server.close();
- chainToCompleter(
- grant.handleAuthorizationResponse(queryToMap(queryString)),
- completer);
-
- return new shelf.Response.found('http://pub.dartlang.org/authorized');
- });
-
- var authUrl = grant.getAuthorizationUrl(
- Uri.parse('http://localhost:${server.port}'),
- scopes: _scopes);
-
- log.message(
- 'Pub needs your authorization to upload packages on your behalf.\n'
- 'In a web browser, go to $authUrl\n' 'Then click "Allow access".\n\n'
- 'Waiting for your authorization...');
- });
-
- return completer.future.then((client) {
- log.message('Successfully authorized.\n');
- return client;
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/package.dart b/sdk/lib/_internal/pub_generated/lib/src/package.dart
deleted file mode 100644
index e454d4b..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/package.dart
+++ /dev/null
@@ -1,393 +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 pub.package;
-
-import 'dart:io';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-import 'package:pub_semver/pub_semver.dart';
-
-import 'barback/transformer_id.dart';
-import 'io.dart';
-import 'git.dart' as git;
-import 'pubspec.dart';
-import 'source_registry.dart';
-import 'utils.dart';
-
-final _README_REGEXP = new RegExp(r"^README($|\.)", caseSensitive: false);
-
-/// A named, versioned, unit of code and resource reuse.
-class Package {
- /// Compares [a] and [b] orders them by name then version number.
- ///
- /// This is normally used as a [Comparator] to pass to sort. This does not
- /// take a package's description or root directory into account, so multiple
- /// distinct packages may order the same.
- static int orderByNameAndVersion(Package a, Package b) {
- var name = a.name.compareTo(b.name);
- if (name != 0) return name;
-
- return a.version.compareTo(b.version);
- }
-
- /// The path to the directory containing the package.
- final String dir;
-
- /// The name of the package.
- String get name {
- if (pubspec.name != null) return pubspec.name;
- if (dir != null) return p.basename(dir);
- return null;
- }
-
- /// The package's version.
- Version get version => pubspec.version;
-
- /// The parsed pubspec associated with this package.
- final Pubspec pubspec;
-
- /// The immediate dependencies this package specifies in its pubspec.
- List<PackageDep> get dependencies => pubspec.dependencies;
-
- /// The immediate dev dependencies this package specifies in its pubspec.
- List<PackageDep> get devDependencies => pubspec.devDependencies;
-
- /// The dependency overrides this package specifies in its pubspec.
- List<PackageDep> get dependencyOverrides => pubspec.dependencyOverrides;
-
- /// All immediate dependencies this package specifies.
- ///
- /// This includes regular, dev dependencies, and overrides.
- Set<PackageDep> get immediateDependencies {
- var deps = {};
-
- addToMap(dep) {
- deps[dep.name] = dep;
- }
-
- dependencies.forEach(addToMap);
- devDependencies.forEach(addToMap);
-
- // Make sure to add these last so they replace normal dependencies.
- dependencyOverrides.forEach(addToMap);
-
- return deps.values.toSet();
- }
-
- /// Returns a list of asset ids for all Dart executables in this package's bin
- /// directory.
- List<AssetId> get executableIds {
- return ordered(
- listFiles(
- beneath: "bin",
- recursive: false)).where(
- (executable) => p.extension(executable) == '.dart').map((executable) {
- return new AssetId(
- name,
- p.toUri(p.relative(executable, from: dir)).toString());
- }).toList();
- }
-
- /// Returns the path to the README file at the root of the entrypoint, or null
- /// if no README file is found.
- ///
- /// If multiple READMEs are found, this uses the same conventions as
- /// pub.dartlang.org for choosing the primary one: the README with the fewest
- /// extensions that is lexically ordered first is chosen.
- String get readmePath {
- var readmes = listFiles(
- recursive: false).map(
- p.basename).where((entry) => entry.contains(_README_REGEXP));
- if (readmes.isEmpty) return null;
-
- return p.join(dir, readmes.reduce((readme1, readme2) {
- var extensions1 = ".".allMatches(readme1).length;
- var extensions2 = ".".allMatches(readme2).length;
- var comparison = extensions1.compareTo(extensions2);
- if (comparison == 0) comparison = readme1.compareTo(readme2);
- return (comparison <= 0) ? readme1 : readme2;
- }));
- }
-
- /// Loads the package whose root directory is [packageDir].
- ///
- /// [name] is the expected name of that package (e.g. the name given in the
- /// dependency), or `null` if the package being loaded is the entrypoint
- /// package.
- Package.load(String name, String packageDir, SourceRegistry sources)
- : dir = packageDir,
- pubspec = new Pubspec.load(packageDir, sources, expectedName: name);
-
- /// Constructs a package with the given pubspec.
- ///
- /// The package will have no directory associated with it.
- Package.inMemory(this.pubspec)
- : dir = null;
-
- /// Creates a package with [pubspec] located at [dir].
- Package(this.pubspec, this.dir);
-
- /// Given a relative path within this package, returns its absolute path.
- ///
- /// This is similar to `p.join(dir, part1, ...)`, except that subclasses may
- /// override it to report that certain paths exist elsewhere than within
- /// [dir]. For example, a [CachedPackage]'s `lib` directory is in the
- /// `.pub/deps` directory.
- String path(String part1, [String part2, String part3, String part4,
- String part5, String part6, String part7]) {
- if (dir == null) {
- throw new StateError(
- "Package $name is in-memory and doesn't have paths " "on disk.");
- }
- return p.join(dir, part1, part2, part3, part4, part5, part6, part7);
- }
-
- /// Given an absolute path within this package (such as that returned by
- /// [path] or [listFiles]), returns it relative to the package root.
- String relative(String path) {
- if (dir == null) {
- throw new StateError(
- "Package $name is in-memory and doesn't have paths " "on disk.");
- }
- return p.relative(path, from: dir);
- }
-
- /// Returns the path to the library identified by [id] within [this].
- String transformerPath(TransformerId id) {
- if (id.package != name) {
- throw new ArgumentError("Transformer $id isn't in package $name.");
- }
-
- if (id.path != null) return path('lib', p.fromUri('${id.path}.dart'));
-
- var transformerPath = path('lib/transformer.dart');
- if (fileExists(transformerPath)) return transformerPath;
- return path('lib/$name.dart');
- }
-
- /// The basenames of files that are included in [list] despite being hidden.
- static final _WHITELISTED_FILES = const ['.htaccess'];
-
- /// A set of patterns that match paths to blacklisted files.
- static final _blacklistedFiles = createFileFilter(['pubspec.lock']);
-
- /// A set of patterns that match paths to blacklisted directories.
- static final _blacklistedDirs = createDirectoryFilter(['packages']);
-
- /// Returns a list of files that are considered to be part of this package.
- ///
- /// If this is a Git repository, this will respect .gitignore; otherwise, it
- /// will return all non-hidden, non-blacklisted files.
- ///
- /// If [beneath] is passed, this will only return files beneath that path,
- /// which is expected to be relative to the package's root directory. If
- /// [recursive] is true, this will return all files beneath that path;
- /// otherwise, it will only return files one level beneath it.
- ///
- /// If [useGitIgnore] is passed, this will take the .gitignore rules into
- /// account if the package's root directory is a Git repository.
- ///
- /// Note that the returned paths won't always be beneath [dir]. To safely
- /// convert them to paths relative to the package root, use [relative].
- List<String> listFiles({String beneath, bool recursive: true,
- bool useGitIgnore: false}) {
- if (beneath == null) {
- beneath = dir;
- } else {
- beneath = p.join(dir, beneath);
- }
-
- if (!dirExists(beneath)) return [];
-
- // This is used in some performance-sensitive paths and can list many, many
- // files. As such, it leans more havily towards optimization as opposed to
- // readability than most code in pub. In particular, it avoids using the
- // path package, since re-parsing a path is very expensive relative to
- // string operations.
- var files;
- if (useGitIgnore && git.isInstalled && dirExists(path('.git'))) {
- // Later versions of git do not allow a path for ls-files that appears to
- // be outside of the repo, so make sure we give it a relative path.
- var relativeBeneath = p.relative(beneath, from: dir);
-
- // List all files that aren't gitignored, including those not checked in
- // to Git.
- files = git.runSync(
- ["ls-files", "--cached", "--others", "--exclude-standard", relativeBeneath],
- workingDir: dir);
-
- // If we're not listing recursively, strip out paths that contain
- // separators. Since git always prints forward slashes, we always detect
- // them.
- if (!recursive) {
- // If we're listing a subdirectory, we only want to look for slashes
- // after the subdirectory prefix.
- var relativeStart =
- relativeBeneath == '.' ? 0 : relativeBeneath.length + 1;
- files = files.where((file) => !file.contains('/', relativeStart));
- }
-
- // Git always prints files relative to the repository root, but we want
- // them relative to the working directory. It also prints forward slashes
- // on Windows which we normalize away for easier testing.
- files = files.map((file) {
- if (Platform.operatingSystem != 'windows') return "$dir/$file";
- return "$dir\\${file.replaceAll("/", "\\")}";
- }).where((file) {
- // Filter out broken symlinks, since git doesn't do so automatically.
- return fileExists(file);
- });
- } else {
- files = listDir(
- beneath,
- recursive: recursive,
- includeDirs: false,
- whitelist: _WHITELISTED_FILES);
- }
-
- return files.where((file) {
- // Using substring here is generally problematic in cases where dir has
- // one or more trailing slashes. If you do listDir("foo"), you'll get back
- // paths like "foo/bar". If you do listDir("foo/"), you'll get "foo/bar"
- // (note the trailing slash was dropped. If you do listDir("foo//"),
- // you'll get "foo//bar".
- //
- // This means if you strip off the prefix, the resulting string may have a
- // leading separator (if the prefix did not have a trailing one) or it may
- // not. However, since we are only using the results of that to call
- // contains() on, the leading separator is harmless.
- assert(file.startsWith(beneath));
- file = file.substring(beneath.length);
- return !_blacklistedFiles.any(file.endsWith) &&
- !_blacklistedDirs.any(file.contains);
- }).toList();
- }
-
- /// Returns a debug string for the package.
- String toString() => '$name $version ($dir)';
-}
-
-/// This is the private base class of [PackageRef], [PackageID], and
-/// [PackageDep].
-///
-/// It contains functionality and state that those classes share but is private
-/// so that from outside of this library, there is no type relationship between
-/// those three types.
-class _PackageName {
- _PackageName(this.name, this.source, this.description);
-
- /// The name of the package being identified.
- final String name;
-
- /// The name of the [Source] used to look up this package given its
- /// [description].
- ///
- /// If this is a root package, this will be `null`.
- final String source;
-
- /// The metadata used by the package's [source] to identify and locate it.
- ///
- /// It contains whatever [Source]-specific data it needs to be able to get
- /// the package. For example, the description of a git sourced package might
- /// by the URL "git://github.com/dart/uilib.git".
- final description;
-
- /// Whether this package is the root package.
- bool get isRoot => source == null;
-
- String toString() {
- if (isRoot) return "$name (root)";
- return "$name from $source";
- }
-
- /// Returns a [PackageRef] with this one's [name], [source], and
- /// [description].
- PackageRef toRef() => new PackageRef(name, source, description);
-
- /// Returns a [PackageId] for this package with the given concrete version.
- PackageId atVersion(Version version) =>
- new PackageId(name, source, version, description);
-
- /// Returns a [PackageDep] for this package with the given version constraint.
- PackageDep withConstraint(VersionConstraint constraint) =>
- new PackageDep(name, source, constraint, description);
-}
-
-/// A reference to a [Package], but not any particular version(s) of it.
-class PackageRef extends _PackageName {
- PackageRef(String name, String source, description)
- : super(name, source, description);
-
- int get hashCode => name.hashCode ^ source.hashCode;
-
- bool operator ==(other) {
- // TODO(rnystrom): We're assuming here that we don't need to delve into the
- // description.
- return other is PackageRef && other.name == name && other.source == source;
- }
-}
-
-/// A reference to a specific version of a package.
-///
-/// A package ID contains enough information to correctly get the package.
-///
-/// Note that it's possible for multiple distinct package IDs to point to
-/// different packages that have identical contents. For example, the same
-/// package may be available from multiple sources. As far as Pub is concerned,
-/// those packages are different.
-class PackageId extends _PackageName {
- /// The package's version.
- final Version version;
-
- PackageId(String name, String source, this.version, description)
- : super(name, source, description);
-
- /// Creates an ID for the given root package.
- PackageId.root(Package package)
- : version = package.version,
- super(package.name, null, package.name);
-
- int get hashCode => name.hashCode ^ source.hashCode ^ version.hashCode;
-
- bool operator ==(other) {
- // TODO(rnystrom): We're assuming here that we don't need to delve into the
- // description.
- return other is PackageId &&
- other.name == name &&
- other.source == source &&
- other.version == version;
- }
-
- String toString() {
- if (isRoot) return "$name $version (root)";
- return "$name $version from $source";
- }
-}
-
-/// A reference to a constrained range of versions of one package.
-class PackageDep extends _PackageName {
- /// The allowed package versions.
- final VersionConstraint constraint;
-
- PackageDep(String name, String source, this.constraint, description)
- : super(name, source, description);
-
- String toString() {
- if (isRoot) return "$name $constraint (root)";
- return "$name $constraint from $source ($description)";
- }
-
- int get hashCode => name.hashCode ^ source.hashCode;
-
- bool operator ==(other) {
- // TODO(rnystrom): We're assuming here that we don't need to delve into the
- // description.
- return other is PackageDep &&
- other.name == name &&
- other.source == source &&
- other.constraint == constraint;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/package_graph.dart b/sdk/lib/_internal/pub_generated/lib/src/package_graph.dart
deleted file mode 100644
index 739a7d7..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/package_graph.dart
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright (c) 2013, 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 pub.package_graph;
-
-import 'barback/transformer_cache.dart';
-import 'entrypoint.dart';
-import 'lock_file.dart';
-import 'package.dart';
-import 'source/cached.dart';
-import 'utils.dart';
-
-/// A holistic view of the entire transitive dependency graph for an entrypoint.
-///
-/// A package graph can be loaded using [Entrypoint.loadPackageGraph].
-class PackageGraph {
- /// The entrypoint.
- final Entrypoint entrypoint;
-
- /// The entrypoint's lockfile.
- ///
- /// This describes the sources and resolved descriptions of everything in
- /// [packages].
- final LockFile lockFile;
-
- /// The transitive dependencies of the entrypoint (including itself).
- ///
- /// This may not include all transitive dependencies of the entrypoint if the
- /// creator of the package graph knows only a subset of the packages are
- /// relevant in the current context.
- final Map<String, Package> packages;
-
- /// A map of transitive dependencies for each package.
- Map<String, Set<Package>> _transitiveDependencies;
-
- /// The transformer cache, if it's been loaded.
- TransformerCache _transformerCache;
-
- PackageGraph(this.entrypoint, this.lockFile, this.packages);
-
- /// Loads the transformer cache for this graph.
- ///
- /// This may only be called if [entrypoint] represents a physical package.
- /// This may modify the cache.
- TransformerCache loadTransformerCache() {
- if (_transformerCache == null) {
- if (entrypoint.root.dir == null) {
- throw new StateError(
- "Can't load the transformer cache for virtual "
- "entrypoint ${entrypoint.root.name}.");
- }
- _transformerCache = new TransformerCache.load(this);
- }
- return _transformerCache;
- }
-
- /// Returns all transitive dependencies of [package].
- ///
- /// For the entrypoint this returns all packages in [packages], which includes
- /// dev and override. For any other package, it ignores dev and override
- /// dependencies.
- Set<Package> transitiveDependencies(String package) {
- if (package == entrypoint.root.name) return packages.values.toSet();
-
- if (_transitiveDependencies == null) {
- var closure = transitiveClosure(
- mapMap(
- packages,
- value: (_, package) => package.dependencies.map((dep) => dep.name)));
- _transitiveDependencies = mapMap(
- closure,
- value: (_, names) => names.map((name) => packages[name]).toSet());
- }
-
- return _transitiveDependencies[package];
- }
-
- /// Returns whether [package] is mutable.
- ///
- /// A package is considered to be mutable if it or any of its dependencies
- /// don't come from a cached source, since the user can change its contents
- /// without modifying the pub cache. Information generated from mutable
- /// packages is generally not safe to cache, since it may change frequently.
- bool isPackageMutable(String package) {
- var id = lockFile.packages[package];
- if (id == null) return true;
-
- var source = entrypoint.cache.sources[id.source];
- if (source is! CachedSource) return true;
-
- return transitiveDependencies(package).any((dep) {
- var depId = lockFile.packages[dep.name];
-
- // The entrypoint package doesn't have a lockfile entry. It's always
- // mutable.
- if (depId == null) return true;
-
- return entrypoint.cache.sources[depId.source] is! CachedSource;
- });
- }
-
- /// Returns whether [package] is static.
- ///
- /// A package is considered to be static if it's not transformed and it came
- /// from a cached source. Static packages don't need to be fully processed by
- /// barback.
- ///
- /// Note that a static package isn't the same as an immutable package (see
- /// [isPackageMutable]).
- bool isPackageStatic(String package) {
- var id = lockFile.packages[package];
- if (id == null) return false;
-
- var source = entrypoint.cache.sources[id.source];
- if (source is! CachedSource) return false;
-
- return packages[package].pubspec.transformers.isEmpty;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/preprocess.dart b/sdk/lib/_internal/pub_generated/lib/src/preprocess.dart
deleted file mode 100644
index bf05f89..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/preprocess.dart
+++ /dev/null
@@ -1,144 +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.
-
-library pub.preprocess;
-
-import 'package:pub_semver/pub_semver.dart';
-import 'package:string_scanner/string_scanner.dart';
-
-/// Runs a simple preprocessor over [input] to remove sections that are
-/// incompatible with the available barback version.
-///
-/// [versions] are the available versions of each installed package, and
-/// [sourceUrl] is a [String] or [Uri] indicating where [input] came from. It's
-/// used for error reporting.
-///
-/// For the most part, the preprocessor leaves text in the source document
-/// alone. However, it handles two types of lines specially. Lines that begin
-/// with `//>` are uncommented by the preprocessor, and lines that begin with
-/// `//#` are operators.
-///
-/// The preprocessor currently supports one top-level operator, "if":
-///
-/// //# if barback >=0.14.1
-/// ...
-/// //# else
-/// ...
-/// //# end
-///
-/// If can check against any package installed in the current package. It can
-/// check the version of the package, as above, or (if the version range is
-/// omitted) whether the package exists at all. If the condition is true,
-/// everything within the first block is included in the output and everything
-/// within the second block is removed; otherwise, the first block is removed
-/// and the second block is included. The `else` block is optional.
-///
-/// It's important that the preprocessor syntax also be valid Dart code, because
-/// pub loads the source files before preprocessing and runs them against the
-/// version of barback that was compiled into pub. This is why the `//>` syntax
-/// exists: so that code can be hidden from the running pub process but still be
-/// visible to the barback isolate. For example:
-///
-/// //# if barback >= 0.14.1
-/// ClassMirror get aggregateClass => reflectClass(AggregateTransformer);
-/// //# else
-/// //> ClassMirror get aggregateClass => null;
-/// //# end
-String preprocess(String input, Map<String, Version> versions, sourceUrl) {
- // Short-circuit if there are no preprocessor directives in the file.
- if (!input.contains(new RegExp(r"^//[>#]", multiLine: true))) return input;
- return new _Preprocessor(input, versions, sourceUrl).run();
-}
-
-/// The preprocessor class.
-class _Preprocessor {
- /// The scanner over the input string.
- final StringScanner _scanner;
-
- final Map<String, Version> _versions;
-
- /// The buffer to which the output is written.
- final _buffer = new StringBuffer();
-
- _Preprocessor(String input, this._versions, sourceUrl)
- : _scanner = new StringScanner(input, sourceUrl: sourceUrl);
-
- /// Run the preprocessor and return the processed output.
- String run() {
- while (!_scanner.isDone) {
- if (_scanner.scan(new RegExp(r"//#[ \t]*"))) {
- _if();
- } else {
- _emitText();
- }
- }
-
- _scanner.expectDone();
- return _buffer.toString();
- }
-
- /// Emit lines of the input document directly until an operator is
- /// encountered.
- void _emitText() {
- while (!_scanner.isDone && !_scanner.matches("//#")) {
- if (_scanner.scan("//>")) {
- if (!_scanner.matches("\n")) _scanner.expect(" ");
- }
-
- _scanner.scan(new RegExp(r"[^\n]*\n?"));
- _buffer.write(_scanner.lastMatch[0]);
- }
- }
-
- /// Move through lines of the input document without emitting them until an
- /// operator is encountered.
- void _ignoreText() {
- while (!_scanner.isDone && !_scanner.matches("//#")) {
- _scanner.scan(new RegExp(r"[^\n]*\n?"));
- }
- }
-
- /// Handle an `if` operator.
- void _if() {
- _scanner.expect(new RegExp(r"if[ \t]+"), name: "if statement");
- _scanner.expect(new RegExp(r"[a-zA-Z0-9_]+"), name: "package name");
- var package = _scanner.lastMatch[0];
-
- _scanner.scan(new RegExp(r"[ \t]*"));
- var constraint = VersionConstraint.any;
- if (_scanner.scan(new RegExp(r"[^\n]+"))) {
- try {
- constraint = new VersionConstraint.parse(_scanner.lastMatch[0]);
- } on FormatException catch (error) {
- _scanner.error("Invalid version constraint: ${error.message}");
- }
- }
- _scanner.expect("\n");
-
- var allowed =
- _versions.containsKey(package) &&
- constraint.allows(_versions[package]);
- if (allowed) {
- _emitText();
- } else {
- _ignoreText();
- }
-
- _scanner.expect("//#");
- _scanner.scan(new RegExp(r"[ \t]*"));
- if (_scanner.scan("else")) {
- _scanner.expect("\n");
- if (allowed) {
- _ignoreText();
- } else {
- _emitText();
- }
- _scanner.expect("//#");
- _scanner.scan(new RegExp(r"[ \t]*"));
- }
-
- _scanner.expect("end");
- if (!_scanner.isDone) _scanner.expect("\n");
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/progress.dart b/sdk/lib/_internal/pub_generated/lib/src/progress.dart
deleted file mode 100644
index 483157d2..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/progress.dart
+++ /dev/null
@@ -1,100 +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 pub.progress;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'log.dart' as log;
-import 'utils.dart';
-
-/// A live-updating progress indicator for long-running log entries.
-class Progress {
- /// The timer used to write "..." during a progress log.
- Timer _timer;
-
- /// The [Stopwatch] used to track how long a progress log has been running.
- final _stopwatch = new Stopwatch();
-
- /// The progress message as it's being incrementally appended.
- ///
- /// When the progress is done, a single entry will be added to the log for it.
- final String _message;
-
- /// Gets the current progress time as a parenthesized, formatted string.
- String get _time => "(${niceDuration(_stopwatch.elapsed)})";
-
- /// Creates a new progress indicator.
- ///
- /// If [fine] is passed, this will log progress messages on [log.Level.FINE]
- /// as opposed to [log.Level.MESSAGE].
- Progress(this._message, {bool fine: false}) {
- _stopwatch.start();
-
- var level = fine ? log.Level.FINE : log.Level.MESSAGE;
-
- // The animation is only shown when it would be meaningful to a human.
- // That means we're writing a visible message to a TTY at normal log levels
- // with non-JSON output.
- if (stdioType(stdout) != StdioType.TERMINAL ||
- !log.verbosity.isLevelVisible(level) ||
- log.json.enabled ||
- fine ||
- log.verbosity.isLevelVisible(log.Level.FINE)) {
- // Not animating, so just log the start and wait until the task is
- // completed.
- log.write(level, "$_message...");
- return;
- }
-
- _timer = new Timer.periodic(new Duration(milliseconds: 100), (_) {
- _update();
- });
-
- _update();
- }
-
- /// Stops the progress indicator.
- void stop() {
- _stopwatch.stop();
-
- // Always log the final time as [log.fine] because for the most part normal
- // users don't care about the precise time information beyond what's shown
- // in the animation.
- log.fine("$_message finished $_time.");
-
- // If we were animating, print one final update to show the user the final
- // time.
- if (_timer == null) return;
- _timer.cancel();
- _timer = null;
- _update();
- stdout.writeln();
- }
-
- /// Stop animating the progress indicator.
- ///
- /// This will continue running the stopwatch so that the full time can be
- /// logged in [stop].
- void stopAnimating() {
- if (_timer == null) return;
-
- // Print a final message without a time indicator so that we don't leave a
- // misleading half-complete time indicator on the console.
- stdout.writeln(log.format("\r$_message..."));
- _timer.cancel();
- _timer = null;
- }
-
- /// Refreshes the progress line.
- void _update() {
- if (log.isMuted) return;
-
- stdout.write(log.format("\r$_message... "));
-
- // Show the time only once it gets noticeably long.
- if (_stopwatch.elapsed.inSeconds > 0) stdout.write("${log.gray(_time)} ");
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/pubspec.dart b/sdk/lib/_internal/pub_generated/lib/src/pubspec.dart
deleted file mode 100644
index 92c068a..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/pubspec.dart
+++ /dev/null
@@ -1,628 +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 pub.pubspec;
-
-import 'package:path/path.dart' as path;
-import 'package:pub_semver/pub_semver.dart';
-import 'package:source_span/source_span.dart';
-import 'package:yaml/yaml.dart';
-
-import 'barback/transformer_config.dart';
-import 'exceptions.dart';
-import 'io.dart';
-import 'package.dart';
-import 'source_registry.dart';
-import 'utils.dart';
-
-/// The parsed contents of a pubspec file.
-///
-/// The fields of a pubspec are, for the most part, validated when they're first
-/// accessed. This allows a partially-invalid pubspec to be used if only the
-/// valid portions are relevant. To get a list of all errors in the pubspec, use
-/// [allErrors].
-class Pubspec {
- // If a new lazily-initialized field is added to this class and the
- // initialization can throw a [PubspecException], that error should also be
- // exposed through [allErrors].
-
- /// The registry of sources to use when parsing [dependencies] and
- /// [devDependencies].
- ///
- /// This will be null if this was created using [new Pubspec] or [new
- /// Pubspec.empty].
- final SourceRegistry _sources;
-
- /// The location from which the pubspec was loaded.
- ///
- /// This can be null if the pubspec was created in-memory or if its location
- /// is unknown.
- Uri get _location => fields.span.sourceUrl;
-
- /// All pubspec fields.
- ///
- /// This includes the fields from which other properties are derived.
- final YamlMap fields;
-
- /// The package's name.
- String get name {
- if (_name != null) return _name;
-
- var name = fields['name'];
- if (name == null) {
- throw new PubspecException(
- 'Missing the required "name" field.',
- fields.span);
- } else if (name is! String) {
- throw new PubspecException(
- '"name" field must be a string.',
- fields.nodes['name'].span);
- }
-
- _name = name;
- return _name;
- }
- String _name;
-
- /// The package's version.
- Version get version {
- if (_version != null) return _version;
-
- var version = fields['version'];
- if (version == null) {
- _version = Version.none;
- return _version;
- }
-
- var span = fields.nodes['version'].span;
- if (version is num) {
- var fixed = '$version.0';
- if (version is int) {
- fixed = '$fixed.0';
- }
- _error(
- '"version" field must have three numeric components: major, '
- 'minor, and patch. Instead of "$version", consider "$fixed".',
- span);
- }
- if (version is! String) {
- _error('"version" field must be a string.', span);
- }
-
- _version =
- _wrapFormatException('version number', span, () => new Version.parse(version));
- return _version;
- }
- Version _version;
-
- /// The additional packages this package depends on.
- List<PackageDep> get dependencies {
- if (_dependencies != null) return _dependencies;
- _dependencies = _parseDependencies('dependencies');
- _checkDependencyOverlap(_dependencies, _devDependencies);
- return _dependencies;
- }
- List<PackageDep> _dependencies;
-
- /// The packages this package depends on when it is the root package.
- List<PackageDep> get devDependencies {
- if (_devDependencies != null) return _devDependencies;
- _devDependencies = _parseDependencies('dev_dependencies');
- _checkDependencyOverlap(_dependencies, _devDependencies);
- return _devDependencies;
- }
- List<PackageDep> _devDependencies;
-
- /// The dependency constraints that this package overrides when it is the
- /// root package.
- ///
- /// Dependencies here will replace any dependency on a package with the same
- /// name anywhere in the dependency graph.
- List<PackageDep> get dependencyOverrides {
- if (_dependencyOverrides != null) return _dependencyOverrides;
- _dependencyOverrides = _parseDependencies('dependency_overrides');
- return _dependencyOverrides;
- }
- List<PackageDep> _dependencyOverrides;
-
- /// The configurations of the transformers to use for this package.
- List<Set<TransformerConfig>> get transformers {
- if (_transformers != null) return _transformers;
-
- var transformers = fields['transformers'];
- if (transformers == null) {
- _transformers = [];
- return _transformers;
- }
-
- if (transformers is! List) {
- _error(
- '"transformers" field must be a list.',
- fields.nodes['transformers'].span);
- }
-
- var i = 0;
- _transformers = transformers.nodes.map((phase) {
- var phaseNodes = phase is YamlList ? phase.nodes : [phase];
- return phaseNodes.map((transformerNode) {
- var transformer = transformerNode.value;
- if (transformer is! String && transformer is! Map) {
- _error(
- 'A transformer must be a string or map.',
- transformerNode.span);
- }
-
- var libraryNode;
- var configurationNode;
- if (transformer is String) {
- libraryNode = transformerNode;
- } else {
- if (transformer.length != 1) {
- _error(
- 'A transformer map must have a single key: the transformer ' 'identifier.',
- transformerNode.span);
- } else if (transformer.keys.single is! String) {
- _error(
- 'A transformer identifier must be a string.',
- transformer.nodes.keys.single.span);
- }
-
- libraryNode = transformer.nodes.keys.single;
- configurationNode = transformer.nodes.values.single;
- if (configurationNode is! YamlMap) {
- _error(
- "A transformer's configuration must be a map.",
- configurationNode.span);
- }
- }
-
- var config = _wrapSpanFormatException('transformer config', () {
- return new TransformerConfig.parse(
- libraryNode.value,
- libraryNode.span,
- configurationNode);
- });
-
- var package = config.id.package;
- if (package != name &&
- !config.id.isBuiltInTransformer &&
- !dependencies.any((ref) => ref.name == package) &&
- !devDependencies.any((ref) => ref.name == package) &&
- !dependencyOverrides.any((ref) => ref.name == package)) {
- _error('"$package" is not a dependency.', libraryNode.span);
- }
-
- return config;
- }).toSet();
- }).toList();
-
- return _transformers;
- }
- List<Set<TransformerConfig>> _transformers;
-
- /// The environment-related metadata.
- PubspecEnvironment get environment {
- if (_environment != null) return _environment;
-
- var yaml = fields['environment'];
- if (yaml == null) {
- _environment = new PubspecEnvironment(VersionConstraint.any);
- return _environment;
- }
-
- if (yaml is! Map) {
- _error(
- '"environment" field must be a map.',
- fields.nodes['environment'].span);
- }
-
- _environment =
- new PubspecEnvironment(_parseVersionConstraint(yaml.nodes['sdk']));
- return _environment;
- }
- PubspecEnvironment _environment;
-
- /// The URL of the server that the package should default to being published
- /// to, "none" if the package should not be published, or `null` if it should
- /// be published to the default server.
- ///
- /// If this does return a URL string, it will be a valid parseable URL.
- String get publishTo {
- if (_parsedPublishTo) return _publishTo;
-
- var publishTo = fields['publish_to'];
- if (publishTo != null) {
- var span = fields.nodes['publish_to'].span;
-
- if (publishTo is! String) {
- _error('"publish_to" field must be a string.', span);
- }
-
- // It must be "none" or a valid URL.
- if (publishTo != "none") {
- _wrapFormatException(
- '"publish_to" field',
- span,
- () => Uri.parse(publishTo));
- }
- }
-
- _parsedPublishTo = true;
- _publishTo = publishTo;
- return _publishTo;
- }
- bool _parsedPublishTo = false;
- String _publishTo;
-
- /// The executables that should be placed on the user's PATH when this
- /// package is globally activated.
- ///
- /// It is a map of strings to string. Each key is the name of the command
- /// that will be placed on the user's PATH. The value is the name of the
- /// .dart script (without extension) in the package's `bin` directory that
- /// should be run for that command. Both key and value must be "simple"
- /// strings: alphanumerics, underscores and hypens only. If a value is
- /// omitted, it is inferred to use the same name as the key.
- Map<String, String> get executables {
- if (_executables != null) return _executables;
-
- _executables = {};
- var yaml = fields['executables'];
- if (yaml == null) return _executables;
-
- if (yaml is! Map) {
- _error(
- '"executables" field must be a map.',
- fields.nodes['executables'].span);
- }
-
- yaml.nodes.forEach((key, value) {
- // Don't allow path separators or other stuff meaningful to the shell.
- validateName(name, description) {
- }
-
- if (key.value is! String) {
- _error('"executables" keys must be strings.', key.span);
- }
-
- final keyPattern = new RegExp(r"^[a-zA-Z0-9_-]+$");
- if (!keyPattern.hasMatch(key.value)) {
- _error(
- '"executables" keys may only contain letters, '
- 'numbers, hyphens and underscores.',
- key.span);
- }
-
- if (value.value == null) {
- value = key;
- } else if (value.value is! String) {
- _error('"executables" values must be strings or null.', value.span);
- }
-
- final valuePattern = new RegExp(r"[/\\]");
- if (valuePattern.hasMatch(value.value)) {
- _error(
- '"executables" values may not contain path separators.',
- value.span);
- }
-
- _executables[key.value] = value.value;
- });
-
- return _executables;
- }
- Map<String, String> _executables;
-
- /// Whether the package is private and cannot be published.
- ///
- /// This is specified in the pubspec by setting "publish_to" to "none".
- bool get isPrivate => publishTo == "none";
-
- /// Whether or not the pubspec has no contents.
- bool get isEmpty =>
- name == null && version == Version.none && dependencies.isEmpty;
-
- /// Loads the pubspec for a package located in [packageDir].
- ///
- /// If [expectedName] is passed and the pubspec doesn't have a matching name
- /// field, this will throw a [PubspecError].
- factory Pubspec.load(String packageDir, SourceRegistry sources,
- {String expectedName}) {
- var pubspecPath = path.join(packageDir, 'pubspec.yaml');
- var pubspecUri = path.toUri(pubspecPath);
- if (!fileExists(pubspecPath)) {
- throw new FileException(
- 'Could not find a file named "pubspec.yaml" in "$packageDir".',
- pubspecPath);
- }
-
- return new Pubspec.parse(
- readTextFile(pubspecPath),
- sources,
- expectedName: expectedName,
- location: pubspecUri);
- }
-
- Pubspec(this._name, {Version version, Iterable<PackageDep> dependencies,
- Iterable<PackageDep> devDependencies, Iterable<PackageDep> dependencyOverrides,
- VersionConstraint sdkConstraint,
- Iterable<Iterable<TransformerConfig>> transformers, Map fields,
- SourceRegistry sources})
- : _version = version,
- _dependencies = dependencies == null ? null : dependencies.toList(),
- _devDependencies = devDependencies == null ?
- null :
- devDependencies.toList(),
- _dependencyOverrides = dependencyOverrides == null ?
- null :
- dependencyOverrides.toList(),
- _environment = new PubspecEnvironment(sdkConstraint),
- _transformers = transformers == null ?
- [] :
- transformers.map((phase) => phase.toSet()).toList(),
- fields = fields == null ? new YamlMap() : new YamlMap.wrap(fields),
- _sources = sources;
-
- Pubspec.empty()
- : _sources = null,
- _name = null,
- _version = Version.none,
- _dependencies = <PackageDep>[],
- _devDependencies = <PackageDep>[],
- _environment = new PubspecEnvironment(),
- _transformers = <Set<TransformerConfig>>[],
- fields = new YamlMap();
-
- /// Returns a Pubspec object for an already-parsed map representing its
- /// contents.
- ///
- /// If [expectedName] is passed and the pubspec doesn't have a matching name
- /// field, this will throw a [PubspecError].
- ///
- /// [location] is the location from which this pubspec was loaded.
- Pubspec.fromMap(Map fields, this._sources, {String expectedName,
- Uri location})
- : fields = fields is YamlMap ?
- fields :
- new YamlMap.wrap(fields, sourceUrl: location) {
- // If [expectedName] is passed, ensure that the actual 'name' field exists
- // and matches the expectation.
- if (expectedName == null) return;
- if (name == expectedName) return;
-
- throw new PubspecException(
- '"name" field doesn\'t match expected name ' '"$expectedName".',
- this.fields.nodes["name"].span);
- }
-
- /// Parses the pubspec stored at [filePath] whose text is [contents].
- ///
- /// If the pubspec doesn't define a version for itself, it defaults to
- /// [Version.none].
- factory Pubspec.parse(String contents, SourceRegistry sources,
- {String expectedName, Uri location}) {
- var pubspecNode = loadYamlNode(contents, sourceUrl: location);
- if (pubspecNode is YamlScalar && pubspecNode.value == null) {
- pubspecNode = new YamlMap(sourceUrl: location);
- } else if (pubspecNode is! YamlMap) {
- throw new PubspecException(
- 'The pubspec must be a YAML mapping.',
- pubspecNode.span);
- }
-
- return new Pubspec.fromMap(
- pubspecNode,
- sources,
- expectedName: expectedName,
- location: location);
- }
-
- /// Returns a list of most errors in this pubspec.
- ///
- /// This will return at most one error for each field.
- List<PubspecException> get allErrors {
- var errors = <PubspecException>[];
- _getError(fn()) {
- try {
- fn();
- } on PubspecException catch (e) {
- errors.add(e);
- }
- }
-
- _getError(() => this.name);
- _getError(() => this.version);
- _getError(() => this.dependencies);
- _getError(() => this.devDependencies);
- _getError(() => this.transformers);
- _getError(() => this.environment);
- _getError(() => this.publishTo);
- return errors;
- }
-
- /// Parses the dependency field named [field], and returns the corresponding
- /// list of dependencies.
- List<PackageDep> _parseDependencies(String field) {
- var dependencies = <PackageDep>[];
-
- var yaml = fields[field];
- // Allow an empty dependencies key.
- if (yaml == null) return dependencies;
-
- if (yaml is! Map) {
- _error('"$field" field must be a map.', fields.nodes[field].span);
- }
-
- var nonStringNode =
- yaml.nodes.keys.firstWhere((e) => e.value is! String, orElse: () => null);
- if (nonStringNode != null) {
- _error('A dependency name must be a string.', nonStringNode.span);
- }
-
- yaml.nodes.forEach((nameNode, specNode) {
- var name = nameNode.value;
- var spec = specNode.value;
- if (fields['name'] != null && name == this.name) {
- _error('A package may not list itself as a dependency.', nameNode.span);
- }
-
- var descriptionNode;
- var sourceName;
-
- var versionConstraint = new VersionRange();
- if (spec == null) {
- descriptionNode = nameNode;
- sourceName = _sources.defaultSource.name;
- } else if (spec is String) {
- descriptionNode = nameNode;
- sourceName = _sources.defaultSource.name;
- versionConstraint = _parseVersionConstraint(specNode);
- } else if (spec is Map) {
- // Don't write to the immutable YAML map.
- spec = new Map.from(spec);
-
- if (spec.containsKey('version')) {
- spec.remove('version');
- versionConstraint =
- _parseVersionConstraint(specNode.nodes['version']);
- }
-
- var sourceNames = spec.keys.toList();
- if (sourceNames.length > 1) {
- _error('A dependency may only have one source.', specNode.span);
- }
-
- sourceName = sourceNames.single;
- if (sourceName is! String) {
- _error(
- 'A source name must be a string.',
- specNode.nodes.keys.single.span);
- }
-
- descriptionNode = specNode.nodes[sourceName];
- } else {
- _error(
- 'A dependency specification must be a string or a mapping.',
- specNode.span);
- }
-
- // Let the source validate the description.
- var description =
- _wrapFormatException('description', descriptionNode.span, () {
- var pubspecPath;
- if (_location != null && _isFileUri(_location)) {
- pubspecPath = path.fromUri(_location);
- }
-
- return _sources[sourceName].parseDescription(
- pubspecPath,
- descriptionNode.value,
- fromLockFile: false);
- });
-
- dependencies.add(
- new PackageDep(name, sourceName, versionConstraint, description));
- });
-
- return dependencies;
- }
-
- /// Parses [node] to a [VersionConstraint].
- VersionConstraint _parseVersionConstraint(YamlNode node) {
- if (node.value == null) return VersionConstraint.any;
- if (node.value is! String) {
- _error('A version constraint must be a string.', node.span);
- }
-
- return _wrapFormatException(
- 'version constraint',
- node.span,
- () => new VersionConstraint.parse(node.value));
- }
-
- /// Makes sure the same package doesn't appear as both a regular and dev
- /// dependency.
- void _checkDependencyOverlap(List<PackageDep> dependencies,
- List<PackageDep> devDependencies) {
- if (dependencies == null) return;
- if (devDependencies == null) return;
-
- var dependencyNames = dependencies.map((dep) => dep.name).toSet();
- var collisions =
- dependencyNames.intersection(devDependencies.map((dep) => dep.name).toSet());
- if (collisions.isEmpty) return;
-
- var span = fields["dependencies"].nodes.keys.firstWhere(
- (key) => collisions.contains(key.value)).span;
-
- // TODO(nweiz): associate source range info with PackageDeps and use it
- // here.
- _error(
- '${pluralize('Package', collisions.length)} '
- '${toSentence(collisions.map((package) => '"$package"'))} cannot '
- 'appear in both "dependencies" and "dev_dependencies".',
- span);
- }
-
- /// Runs [fn] and wraps any [FormatException] it throws in a
- /// [PubspecException].
- ///
- /// [description] should be a noun phrase that describes whatever's being
- /// parsed or processed by [fn]. [span] should be the location of whatever's
- /// being processed within the pubspec.
- _wrapFormatException(String description, SourceSpan span, fn()) {
- try {
- return fn();
- } on FormatException catch (e) {
- _error('Invalid $description: ${e.message}', span);
- }
- }
-
- _wrapSpanFormatException(String description, fn()) {
- try {
- return fn();
- } on SourceSpanFormatException catch (e) {
- _error('Invalid $description: ${e.message}', e.span);
- }
- }
-
- /// Throws a [PubspecException] with the given message.
- void _error(String message, SourceSpan span) {
- var name;
- try {
- name = this.name;
- } on PubspecException catch (_) {
- // [name] is null.
- }
-
- throw new PubspecException(message, span);
- }
-}
-
-/// The environment-related metadata in the pubspec.
-///
-/// Corresponds to the data under the "environment:" key in the pubspec.
-class PubspecEnvironment {
- /// The version constraint specifying which SDK versions this package works
- /// with.
- final VersionConstraint sdkVersion;
-
- PubspecEnvironment([VersionConstraint sdk])
- : sdkVersion = sdk != null ? sdk : VersionConstraint.any;
-}
-
-/// An exception thrown when parsing a pubspec.
-///
-/// These exceptions are often thrown lazily while accessing pubspec properties.
-class PubspecException extends SourceSpanFormatException implements
- ApplicationException {
- PubspecException(String message, SourceSpan span)
- : super(message, span);
-}
-
-/// Returns whether [uri] is a file URI.
-///
-/// This is slightly more complicated than just checking if the scheme is
-/// 'file', since relative URIs also refer to the filesystem on the VM.
-bool _isFileUri(Uri uri) => uri.scheme == 'file' || uri.scheme == '';
diff --git a/sdk/lib/_internal/pub_generated/lib/src/sdk.dart b/sdk/lib/_internal/pub_generated/lib/src/sdk.dart
deleted file mode 100644
index 2750821..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/sdk.dart
+++ /dev/null
@@ -1,73 +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.
-
-/// Operations relative to the user's installed Dart SDK.
-library pub.sdk;
-
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-import 'package:pub_semver/pub_semver.dart';
-
-import 'io.dart';
-
-/// Gets the path to the root directory of the SDK.
-///
-/// When running from the actual built SDK, this will be the SDK that contains
-/// the running Dart executable. When running from the repo, it will be the
-/// "sdk" directory in the Dart repository itself.
-final String rootDirectory =
- runningFromSdk ? _rootDirectory : path.join(repoRoot, "sdk");
-
-/// Gets the path to the root directory of the SDK, assuming that the currently
-/// running Dart executable is within it.
-final String _rootDirectory = path.dirname(path.dirname(Platform.executable));
-
-/// The SDK's revision number formatted to be a semantic version.
-///
-/// This can be set so that the version solver tests can artificially select
-/// different SDK versions.
-Version version = _getVersion();
-
-/// Determine the SDK's version number.
-Version _getVersion() {
- // Some of the pub integration tests require an SDK version number, but the
- // tests on the bots are not run from a built SDK so this lets us avoid
- // parsing the missing version file.
- var sdkVersion = Platform.environment["_PUB_TEST_SDK_VERSION"];
- if (sdkVersion != null) return new Version.parse(sdkVersion);
-
- if (runningFromSdk) {
- // Read the "version" file.
- var version = readTextFile(path.join(_rootDirectory, "version")).trim();
- return new Version.parse(version);
- }
-
- // When running from the repo, read the canonical VERSION file in tools/.
- // This makes it possible to run pub without having built the SDK first.
- var contents = readTextFile(path.join(repoRoot, "tools/VERSION"));
-
- parseField(name) {
- var pattern = new RegExp("^$name ([a-z0-9]+)", multiLine: true);
- var match = pattern.firstMatch(contents);
- return match[1];
- }
-
- var channel = parseField("CHANNEL");
- var major = parseField("MAJOR");
- var minor = parseField("MINOR");
- var patch = parseField("PATCH");
- var prerelease = parseField("PRERELEASE");
- var prereleasePatch = parseField("PRERELEASE_PATCH");
-
- var version = "$major.$minor.$patch";
- if (channel == "be") {
- // TODO(rnystrom): tools/utils.py includes the svn commit here. Should we?
- version += "-edge";
- } else if (channel == "dev") {
- version += "-dev.$prerelease.$prereleasePatch";
- }
-
- return new Version.parse(version);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/backtracking_solver.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/backtracking_solver.dart
deleted file mode 100644
index a5bac0f..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/solver/backtracking_solver.dart
+++ /dev/null
@@ -1,810 +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.
-
-/// A back-tracking depth-first solver.
-///
-/// Attempts to find the best solution for a root package's transitive
-/// dependency graph, where a "solution" is a set of concrete package versions.
-/// A valid solution will select concrete versions for every package reached
-/// from the root package's dependency graph, and each of those packages will
-/// fit the version constraints placed on it.
-///
-/// The solver builds up a solution incrementally by traversing the dependency
-/// graph starting at the root package. When it reaches a new package, it gets
-/// the set of versions that meet the current constraint placed on it. It
-/// *speculatively* selects one version from that set and adds it to the
-/// current solution and then proceeds. If it fully traverses the dependency
-/// graph, the solution is valid and it stops.
-///
-/// If it reaches an error because:
-///
-/// - A new dependency is placed on a package that's already been selected in
-/// the solution and the selected version doesn't match the new constraint.
-///
-/// - There are no versions available that meet the constraint placed on a
-/// package.
-///
-/// - etc.
-///
-/// then the current solution is invalid. It will then backtrack to the most
-/// recent speculative version choice and try the next one. That becomes the
-/// new in-progress solution and it tries to proceed from there. It will keep
-/// doing this, traversing and then backtracking when it meets a failure until
-/// a valid solution has been found or until all possible options for all
-/// speculative choices have been exhausted.
-library pub.solver.backtracking_solver;
-
-import 'dart:async';
-import 'dart:collection' show Queue;
-
-import 'package:pub_semver/pub_semver.dart';
-
-import '../barback.dart' as barback;
-import '../exceptions.dart';
-import '../lock_file.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../pubspec.dart';
-import '../sdk.dart' as sdk;
-import '../source_registry.dart';
-import '../source/unknown.dart';
-import '../utils.dart';
-import 'dependency_queue.dart';
-import 'version_queue.dart';
-import 'version_solver.dart';
-
-/// The top-level solver.
-///
-/// Keeps track of the current potential solution, and the other possible
-/// versions for speculative package selections. Backtracks and advances to the
-/// next potential solution in the case of a failure.
-class BacktrackingSolver {
- final SolveType type;
- final SourceRegistry sources;
- final Package root;
-
- /// The lockfile that was present before solving.
- final LockFile lockFile;
-
- final PubspecCache cache;
-
- /// The set of packages that are being explicitly upgraded.
- ///
- /// The solver will only allow the very latest version for each of these
- /// packages.
- final _forceLatest = new Set<String>();
-
- /// The set of packages whose dependecy is being overridden by the root
- /// package, keyed by the name of the package.
- ///
- /// Any dependency on a package that appears in this map will be overriden
- /// to use the one here.
- final _overrides = new Map<String, PackageDep>();
-
- /// The package versions currently selected by the solver, along with the
- /// versions which are remaining to be tried.
- ///
- /// Every time a package is encountered when traversing the dependency graph,
- /// the solver must select a version for it, sometimes when multiple versions
- /// are valid. This keeps track of which versions have been selected so far
- /// and which remain to be tried.
- ///
- /// Each entry in the list is a [VersionQueue], which is an ordered queue of
- /// versions to try for a single package. It maintains the currently selected
- /// version for that package. When a new dependency is encountered, a queue
- /// of versions of that dependency is pushed onto the end of the list. A
- /// queue is removed from the list once it's empty, indicating that none of
- /// the versions provided a solution.
- ///
- /// The solver tries versions in depth-first order, so only the last queue in
- /// the list will have items removed from it. When a new constraint is placed
- /// on an already-selected package, and that constraint doesn't match the
- /// selected version, that will cause the current solution to fail and
- /// trigger backtracking.
- final _selected = <VersionQueue>[];
-
- /// The number of solutions the solver has tried so far.
- int get attemptedSolutions => _attemptedSolutions;
- var _attemptedSolutions = 1;
-
- BacktrackingSolver(SolveType type, SourceRegistry sources, this.root,
- this.lockFile, List<String> useLatest)
- : type = type,
- sources = sources,
- cache = new PubspecCache(type, sources) {
- for (var package in useLatest) {
- _forceLatest.add(package);
- }
-
- for (var override in root.dependencyOverrides) {
- _overrides[override.name] = override;
- }
- }
-
- /// Run the solver.
- ///
- /// Completes with a list of specific package versions if successful or an
- /// error if it failed to find a solution.
- Future<SolveResult> solve() {
- var stopwatch = new Stopwatch();
-
- _logParameters();
-
- // Sort the overrides by package name to make sure they're deterministic.
- var overrides = _overrides.values.toList();
- overrides.sort((a, b) => a.name.compareTo(b.name));
-
- // TODO(nweiz): Use async/await here once
- // https://github.com/dart-lang/async_await/issues/79 is fixed.
- return new Future.sync(() {
- stopwatch.start();
-
- // Pre-cache the root package's known pubspec.
- cache.cache(new PackageId.root(root), root.pubspec);
-
- _validateSdkConstraint(root.pubspec);
- return _traverseSolution();
- }).then((packages) {
- var pubspecs = new Map.fromIterable(
- packages,
- key: (id) => id.name,
- value: (id) => cache.getCachedPubspec(id));
-
- return Future.wait(
- packages.map((id) => sources[id.source].resolveId(id))).then((packages) {
- return new SolveResult.success(
- sources,
- root,
- lockFile,
- packages,
- overrides,
- pubspecs,
- _getAvailableVersions(packages),
- attemptedSolutions);
- });
- }).catchError((error) {
- if (error is! SolveFailure) throw error;
- // Wrap a failure in a result so we can attach some other data.
- return new SolveResult.failure(
- sources,
- root,
- lockFile,
- overrides,
- error,
- attemptedSolutions);
- }).whenComplete(() {
- // Gather some solving metrics.
- var buffer = new StringBuffer();
- buffer.writeln('${runtimeType} took ${stopwatch.elapsed} seconds.');
- buffer.writeln(cache.describeResults());
- log.solver(buffer);
- });
- }
-
- /// Generates a map containing all of the known available versions for each
- /// package in [packages].
- ///
- /// The version list may not always be complete. The the package is the root
- /// root package, or its a package that we didn't unlock while solving
- /// because we weren't trying to upgrade it, we will just know the current
- /// version.
- Map<String, List<Version>> _getAvailableVersions(List<PackageId> packages) {
- var availableVersions = new Map<String, List<Version>>();
- for (var package in packages) {
- var cached = cache.getCachedVersions(package.toRef());
- var versions;
- if (cached != null) {
- versions = cached.map((id) => id.version).toList();
- } else {
- // If the version list was never requested, just use the one known
- // version.
- versions = [package.version];
- }
-
- availableVersions[package.name] = versions;
- }
-
- return availableVersions;
- }
-
- /// Adds [versions], which is the list of all allowed versions of a given
- /// package, to the set of versions to consider for solutions.
- ///
- /// The first item in the list will be the currently selected version of that
- /// package. Subsequent items will be tried if it the current selection fails.
- /// Returns the first selected version.
- PackageId select(VersionQueue versions) {
- _selected.add(versions);
- logSolve();
- return versions.current;
- }
-
- /// Returns the the currently selected id for the package [name] or `null` if
- /// no concrete version has been selected for that package yet.
- PackageId getSelected(String name) {
- // Always prefer the root package.
- if (root.name == name) return new PackageId.root(root);
-
- // Look through the current selections.
- for (var i = _selected.length - 1; i >= 0; i--) {
- if (_selected[i].current.name == name) return _selected[i].current;
- }
-
- return null;
- }
-
- /// Gets the version of [package] currently locked in the lock file.
- ///
- /// Returns `null` if it isn't in the lockfile (or has been unlocked).
- PackageId getLocked(String package) {
- if (type == SolveType.GET) return lockFile.packages[package];
-
- // When downgrading, we don't want to force the latest versions of
- // non-hosted packages, since they don't support multiple versions and thus
- // can't be downgraded.
- if (type == SolveType.DOWNGRADE) {
- var locked = lockFile.packages[package];
- if (locked != null && !sources[locked.source].hasMultipleVersions) {
- return locked;
- }
- }
-
- if (_forceLatest.isEmpty || _forceLatest.contains(package)) return null;
- return lockFile.packages[package];
- }
-
- /// Traverses the root package's dependency graph using the current potential
- /// solution.
- ///
- /// If successful, completes to the solution. If not, backtracks to the most
- /// recently selected version of a package and tries the next version of it.
- /// If there are no more versions, continues to backtrack to previous
- /// selections, and so on. If there is nothing left to backtrack to,
- /// completes to the last failure that occurred.
- Future<List<PackageId>> _traverseSolution() => resetStack(() {
- return new Traverser(this).traverse().catchError((error) {
- if (error is! SolveFailure) throw error;
-
- return _backtrack(error).then((canTry) {
- if (canTry) {
- _attemptedSolutions++;
- return _traverseSolution();
- }
-
- // All out of solutions, so fail.
- throw error;
- });
- });
- });
-
- /// Backtracks from the current failed solution and determines the next
- /// solution to try.
- ///
- /// If possible, it will backjump based on the cause of the [failure] to
- /// minize backtracking. Otherwise, it will simply backtrack to the next
- /// possible solution.
- ///
- /// Returns `true` if there is a new solution to try.
- Future<bool> _backtrack(SolveFailure failure) {
- // Bail if there is nothing to backtrack to.
- if (_selected.isEmpty) return new Future.value(false);
-
- // Mark any packages that may have led to this failure so that we know to
- // consider them when backtracking.
- var dependers = _getTransitiveDependers(failure.package);
-
- for (var selected in _selected) {
- if (dependers.contains(selected.current.name)) {
- selected.fail();
- }
- }
-
- // Advance past the current version of the leaf-most package.
- advanceVersion() {
- _backjump(failure);
- var previous = _selected.last.current;
- return _selected.last.advance().then((success) {
- if (success) {
- logSolve();
- return true;
- }
-
- logSolve('$previous is last version, backtracking');
-
- // That package has no more versions, so pop it and try the next one.
- _selected.removeLast();
- if (_selected.isEmpty) return false;
-
- // If we got here, the leafmost package was discarded so we need to
- // advance the next one.
- return advanceVersion();
- });
- }
-
- return advanceVersion();
- }
-
- /// Walks the selected packages from most to least recent to determine which
- /// ones can be ignored and jumped over by the backtracker.
- ///
- /// The only packages we need to backtrack to are ones that led (possibly
- /// indirectly) to the failure. Everything else can be skipped.
- void _backjump(SolveFailure failure) {
- for (var i = _selected.length - 1; i >= 0; i--) {
- // Each queue will never be empty since it gets discarded by _backtrack()
- // when that happens.
- var selected = _selected[i].current;
-
- // If the failure is a disjoint version range, then no possible versions
- // for that package can match and there's no reason to try them. Instead,
- // just backjump past it.
- if (failure is DisjointConstraintException &&
- selected.name == failure.package) {
- logSolve("skipping past disjoint selected ${selected.name}");
- continue;
- }
-
- if (_selected[i].hasFailed) {
- logSolve('backjump to ${selected.name}');
- _selected.removeRange(i + 1, _selected.length);
- return;
- }
- }
-
- // If we got here, we walked the entire list without finding a package that
- // could lead to another solution, so discard everything. This will happen
- // if every package that led to the failure has no other versions that it
- // can try to select.
- _selected.removeRange(1, _selected.length);
- }
-
- /// Gets the set of currently selected packages that depend on [dependency]
- /// either directly or indirectly.
- ///
- /// When backtracking, it's only useful to consider changing the version of
- /// packages who have a dependency on the failed package that triggered
- /// backtracking. This is used to determine those packages.
- ///
- /// We calculate the full set up front before backtracking because during
- /// backtracking, we will unselect packages and start to lose this
- /// information in the middle of the process.
- ///
- /// For example, consider dependencies A -> B -> C. We've selected A and B
- /// then encounter a problem with C. We start backtracking. B has no more
- /// versions so we discard it and keep backtracking to A. When we get there,
- /// since we've unselected B, we no longer realize that A had a transitive
- /// dependency on C. We would end up backjumping over A and failing.
- ///
- /// Calculating the dependency set up front before we start backtracking
- /// solves that.
- Set<String> _getTransitiveDependers(String dependency) {
- // Generate a reverse dependency graph. For each package, create edges to
- // each package that depends on it.
- var dependers = new Map<String, Set<String>>();
-
- addDependencies(name, deps) {
- dependers.putIfAbsent(name, () => new Set<String>());
- for (var dep in deps) {
- dependers.putIfAbsent(dep.name, () => new Set<String>()).add(name);
- }
- }
-
- for (var i = 0; i < _selected.length; i++) {
- var id = _selected[i].current;
- var pubspec = cache.getCachedPubspec(id);
- if (pubspec != null) addDependencies(id.name, pubspec.dependencies);
- }
-
- // Include the root package's dependencies.
- addDependencies(root.name, root.immediateDependencies);
-
- // Now walk the depending graph to see which packages transitively depend
- // on [dependency].
- var visited = new Set<String>();
- walk(String package) {
- // Don't get stuck in cycles.
- if (visited.contains(package)) return;
- visited.add(package);
- var depender = dependers[package].forEach(walk);
- }
-
- walk(dependency);
- return visited;
- }
-
- /// Logs the initial parameters to the solver.
- void _logParameters() {
- var buffer = new StringBuffer();
- buffer.writeln("Solving dependencies:");
- for (var package in root.dependencies) {
- buffer.write("- $package");
- var locked = getLocked(package.name);
- if (_forceLatest.contains(package.name)) {
- buffer.write(" (use latest)");
- } else if (locked != null) {
- var version = locked.version;
- buffer.write(" (locked to $version)");
- }
- buffer.writeln();
- }
- log.solver(buffer.toString().trim());
- }
-
- /// Logs [message] in the context of the current selected packages.
- ///
- /// If [message] is omitted, just logs a description of leaf-most selection.
- void logSolve([String message]) {
- if (message == null) {
- if (_selected.isEmpty) {
- message = "* start at root";
- } else {
- message = "* select ${_selected.last.current}";
- }
- } else {
- // Otherwise, indent it under the current selected package.
- message = prefixLines(message);
- }
-
- // Indent for the previous selections.
- var prefix = _selected.skip(1).map((_) => '| ').join();
- log.solver(prefixLines(message, prefix: prefix));
- }
-}
-
-/// Given the solver's current set of selected package versions, this tries to
-/// traverse the dependency graph and see if a complete set of valid versions
-/// has been chosen.
-///
-/// If it reaches a conflict, it fails and stops traversing. If it reaches a
-/// package that isn't selected, it refines the solution by adding that
-/// package's set of allowed versions to the solver and then select the best
-/// one and continuing.
-class Traverser {
- final BacktrackingSolver _solver;
-
- /// The queue of packages left to traverse.
- ///
- /// We do a breadth-first traversal using an explicit queue just to avoid the
- /// code complexity of a recursive asynchronous traversal.
- final _packages = new Queue<PackageId>();
-
- /// The packages we have already traversed.
- ///
- /// Used to avoid traversing the same package multiple times, and to build
- /// the complete solution results.
- final _visited = new Set<PackageId>();
-
- /// The dependencies visited so far in the traversal.
- ///
- /// For each package name (the map key) we track the list of dependencies
- /// that other packages have placed on it so that we can calculate the
- /// complete constraint for shared dependencies.
- final _dependencies = <String, List<Dependency>>{};
-
- Traverser(this._solver);
-
- /// Walks the dependency graph starting at the root package and validates
- /// that each reached package has a valid version selected.
- Future<List<PackageId>> traverse() {
- // Start at the root.
- _packages.add(new PackageId.root(_solver.root));
- return _traversePackage();
- }
-
- /// Traverses the next package in the queue.
- ///
- /// Completes to a list of package IDs if the traversal completed
- /// successfully and found a solution. Completes to an error if the traversal
- /// failed. Otherwise, recurses to the next package in the queue, etc.
- Future<List<PackageId>> _traversePackage() {
- if (_packages.isEmpty) {
- // We traversed the whole graph. If we got here, we successfully found
- // a solution.
- return new Future<List<PackageId>>.value(_visited.toList());
- }
-
- var id = _packages.removeFirst();
-
- // Don't visit the same package twice.
- if (_visited.contains(id)) {
- return _traversePackage();
- }
- _visited.add(id);
-
- return _solver.cache.getPubspec(id).then((pubspec) {
- _validateSdkConstraint(pubspec);
-
- var deps = pubspec.dependencies.toSet();
-
- if (id.isRoot) {
- // Include dev dependencies of the root package.
- deps.addAll(pubspec.devDependencies);
-
- // Add all overrides. This ensures a dependency only present as an
- // override is still included.
- deps.addAll(_solver._overrides.values);
- }
-
- // Replace any overridden dependencies.
- deps = deps.map((dep) {
- var override = _solver._overrides[dep.name];
- if (override != null) return override;
-
- // Not overridden.
- return dep;
- }).toSet();
-
- // Make sure the package doesn't have any bad dependencies.
- for (var dep in deps) {
- if (!dep.isRoot && _solver.sources[dep.source] is UnknownSource) {
- throw new UnknownSourceException(
- id.name,
- [new Dependency(id.name, id.version, dep)]);
- }
- }
-
- return _traverseDeps(id, new DependencyQueue(_solver, deps));
- }).catchError((error) {
- if (error is! PackageNotFoundException) throw error;
-
- // We can only get here if the lockfile refers to a specific package
- // version that doesn't exist (probably because it was yanked).
- throw new NoVersionException(id.name, null, id.version, []);
- });
- }
-
- /// Traverses the references that [depender] depends on, stored in [deps].
- ///
- /// Desctructively modifies [deps]. Completes to a list of packages if the
- /// traversal is complete. Completes it to an error if a failure occurred.
- /// Otherwise, recurses.
- Future<List<PackageId>> _traverseDeps(PackageId depender,
- DependencyQueue deps) {
- // Move onto the next package if we've traversed all of these references.
- if (deps.isEmpty) return _traversePackage();
-
- return resetStack(() {
- return deps.advance().then((dep) {
- var dependency = new Dependency(depender.name, depender.version, dep);
- return _registerDependency(dependency).then((_) {
- if (dep.name == "barback") return _addImplicitDependencies();
- });
- }).then((_) => _traverseDeps(depender, deps));
- });
- }
-
- /// Register [dependency]'s constraints on the package it depends on and
- /// enqueues the package for processing if necessary.
- Future _registerDependency(Dependency dependency) {
- return new Future.sync(() {
- _validateDependency(dependency);
-
- var dep = dependency.dep;
- var dependencies = _getDependencies(dep.name);
- dependencies.add(dependency);
-
- var constraint = _getConstraint(dep.name);
-
- // See if it's possible for a package to match that constraint.
- if (constraint.isEmpty) {
- var constraints = dependencies.map(
- (dep) => " ${dep.dep.constraint} from ${dep.depender}").join('\n');
- _solver.logSolve('disjoint constraints on ${dep.name}:\n$constraints');
- throw new DisjointConstraintException(dep.name, dependencies);
- }
-
- var selected = _validateSelected(dep, constraint);
- if (selected != null) {
- // The selected package version is good, so enqueue it to traverse
- // into it.
- _packages.add(selected);
- return null;
- }
-
- // We haven't selected a version. Try all of the versions that match
- // the constraints we currently have for this package.
- var locked = _getValidLocked(dep.name);
-
- return VersionQueue.create(locked, () {
- return _getAllowedVersions(dep);
- }).then((versions) => _packages.add(_solver.select(versions)));
- });
- }
-
- /// Gets all versions of [dep] that match the current constraints placed on
- /// it.
- Future<Iterable<PackageId>> _getAllowedVersions(PackageDep dep) {
- var constraint = _getConstraint(dep.name);
- return _solver.cache.getVersions(dep.toRef()).then((versions) {
- var allowed = versions.where((id) => constraint.allows(id.version));
-
- if (allowed.isEmpty) {
- _solver.logSolve('no versions for ${dep.name} match $constraint');
- throw new NoVersionException(
- dep.name,
- null,
- constraint,
- _getDependencies(dep.name));
- }
-
- // If we're doing an upgrade on this package, only allow the latest
- // version.
- if (_solver._forceLatest.contains(dep.name)) allowed = [allowed.first];
-
- // Remove the locked version, if any, since that was already handled.
- var locked = _getValidLocked(dep.name);
- if (locked != null) {
- allowed = allowed.where((dep) => dep.version != locked.version);
- }
-
- return allowed;
- }).catchError((error, stackTrace) {
- if (error is PackageNotFoundException) {
- // Show the user why the package was being requested.
- throw new DependencyNotFoundException(
- dep.name,
- error,
- _getDependencies(dep.name));
- }
-
- throw error;
- });
- }
-
- /// Ensures that dependency [dep] from [depender] is consistent with the
- /// other dependencies on the same package.
- ///
- /// Throws a [SolveFailure] exception if not. Only validates sources and
- /// descriptions, not the version.
- void _validateDependency(Dependency dependency) {
- var dep = dependency.dep;
-
- // Make sure the dependencies agree on source and description.
- var required = _getRequired(dep.name);
- if (required == null) return;
-
- // Make sure all of the existing sources match the new reference.
- if (required.dep.source != dep.source) {
- _solver.logSolve(
- 'source mismatch on ${dep.name}: ${required.dep.source} ' '!= ${dep.source}');
- throw new SourceMismatchException(dep.name, [required, dependency]);
- }
-
- // Make sure all of the existing descriptions match the new reference.
- var source = _solver.sources[dep.source];
- if (!source.descriptionsEqual(dep.description, required.dep.description)) {
- _solver.logSolve(
- 'description mismatch on ${dep.name}: '
- '${required.dep.description} != ${dep.description}');
- throw new DescriptionMismatchException(dep.name, [required, dependency]);
- }
- }
-
- /// Validates the currently selected package against the new dependency that
- /// [dep] and [constraint] place on it.
- ///
- /// Returns `null` if there is no currently selected package, throws a
- /// [SolveFailure] if the new reference it not does not allow the previously
- /// selected version, or returns the selected package if successful.
- PackageId _validateSelected(PackageDep dep, VersionConstraint constraint) {
- var selected = _solver.getSelected(dep.name);
- if (selected == null) return null;
-
- // Make sure it meets the constraint.
- if (!dep.constraint.allows(selected.version)) {
- _solver.logSolve('selection $selected does not match $constraint');
- throw new NoVersionException(
- dep.name,
- selected.version,
- constraint,
- _getDependencies(dep.name));
- }
-
- return selected;
- }
-
- /// Register pub's implicit dependencies.
- ///
- /// Pub has an implicit version constraint on barback and various other
- /// packages used in barback's plugin isolate.
- Future _addImplicitDependencies() {
- /// Ensure we only add the barback dependency once.
- if (_getDependencies("barback").length != 1) return new Future.value();
-
- return Future.wait(barback.pubConstraints.keys.map((depName) {
- var constraint = barback.pubConstraints[depName];
- _solver.logSolve(
- 'add implicit $constraint pub dependency on ' '$depName');
-
- var override = _solver._overrides[depName];
-
- // Use the same source and description as the dependency override if one
- // exists. This is mainly used by the pkgbuild tests, which use dependency
- // overrides for all repo packages.
- var pubDep = override == null ?
- new PackageDep(depName, "hosted", constraint, depName) :
- override.withConstraint(constraint);
- return _registerDependency(
- new Dependency("pub itself", Version.none, pubDep));
- }));
- }
-
- /// Gets the list of dependencies for package [name].
- ///
- /// Creates an empty list if needed.
- List<Dependency> _getDependencies(String name) {
- return _dependencies.putIfAbsent(name, () => <Dependency>[]);
- }
-
- /// Gets a "required" reference to the package [name].
- ///
- /// This is the first non-root dependency on that package. All dependencies
- /// on a package must agree on source and description, except for references
- /// to the root package. This will return a reference to that "canonical"
- /// source and description, or `null` if there is no required reference yet.
- ///
- /// This is required because you may have a circular dependency back onto the
- /// root package. That second dependency won't be a root dependency and it's
- /// *that* one that other dependencies need to agree on. In other words, you
- /// can have a bunch of dependencies back onto the root package as long as
- /// they all agree with each other.
- Dependency _getRequired(String name) {
- return _getDependencies(
- name).firstWhere((dep) => !dep.dep.isRoot, orElse: () => null);
- }
-
- /// Gets the combined [VersionConstraint] currently being placed on package
- /// [name].
- VersionConstraint _getConstraint(String name) {
- var constraint = _getDependencies(
- name).map(
- (dep) =>
- dep.dep.constraint).fold(VersionConstraint.any, (a, b) => a.intersect(b));
-
- return constraint;
- }
-
- /// Gets the package [name] that's currently contained in the lockfile if it
- /// meets [constraint] and has the same source and description as other
- /// references to that package.
- ///
- /// Returns `null` otherwise.
- PackageId _getValidLocked(String name) {
- var package = _solver.getLocked(name);
- if (package == null) return null;
-
- var constraint = _getConstraint(name);
- if (!constraint.allows(package.version)) {
- _solver.logSolve('$package is locked but does not match $constraint');
- return null;
- } else {
- _solver.logSolve('$package is locked');
- }
-
- var required = _getRequired(name);
- if (required != null) {
- if (package.source != required.dep.source) return null;
-
- var source = _solver.sources[package.source];
- if (!source.descriptionsEqual(
- package.description,
- required.dep.description)) return null;
- }
-
- return package;
- }
-}
-
-/// Ensures that if [pubspec] has an SDK constraint, then it is compatible
-/// with the current SDK.
-///
-/// Throws a [SolveFailure] if not.
-void _validateSdkConstraint(Pubspec pubspec) {
- if (pubspec.environment.sdkVersion.allows(sdk.version)) return;
-
- throw new BadSdkVersionException(
- pubspec.name,
- 'Package ${pubspec.name} requires SDK version '
- '${pubspec.environment.sdkVersion} but the current SDK is ' '${sdk.version}.');
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/dependency_queue.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/dependency_queue.dart
deleted file mode 100644
index 07fdbc4..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/solver/dependency_queue.dart
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright (c) 2013, 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 pub.solver.dependency_queue;
-
-import 'dart:async';
-import 'dart:collection' show Queue;
-
-import '../log.dart' as log;
-import '../package.dart';
-import 'backtracking_solver.dart';
-
-/// A queue of one package's dependencies, ordered by how the solver should
-/// traverse them.
-///
-/// It prefers locked versions so that they stay locked if possible. Then it
-/// prefers a currently selected package so that it only has to consider a
-/// single version.
-///
-/// After that, it orders the remaining packages by the number of versions they
-/// have so that packages with fewer versions are solved first. (If two
-/// packages have the same number of versions, they are sorted alphabetically
-/// just to be deterministic.)
-///
-/// Critically, this queue will *not* sort the dependencies by number of
-/// versions until actually needed. This ensures we don't do any network
-/// requests until we actually need to. In particular, it means that solving
-/// a package graph with an already up-to-date lockfile will do no network
-/// requests.
-class DependencyQueue {
- final BacktrackingSolver _solver;
-
- /// The dependencies for packages that have already been selected.
- final Queue<PackageDep> _presorted;
-
- /// The dependencies on the remaining packages.
- ///
- /// This is lazily sorted right before the first item is requested.
- final List<PackageDep> _remaining;
-
- bool _isSorted = false;
-
- /// Gets whether there are any dependencies left to iterate over.
- bool get isEmpty => _presorted.isEmpty && _remaining.isEmpty;
-
- /// The pending [Future] while the remaining dependencies are being sorted.
- ///
- /// This will only be non-null while a sort is in progress.
- Future _sortFuture;
-
- factory DependencyQueue(BacktrackingSolver solver, Iterable<PackageDep> deps)
- {
- // Separate out the presorted ones.
- var presorted = <PackageDep>[];
- var remaining = <PackageDep>[];
-
- for (var dep in deps) {
- // Selected or locked packages come first.
- if (solver.getSelected(dep.name) != null ||
- solver.getLocked(dep.name) != null) {
- presorted.add(dep);
- } else {
- remaining.add(dep);
- }
- }
-
- // Sort the selected/locked packages by name just to ensure the solver is
- // deterministic.
- presorted.sort((a, b) => a.name.compareTo(b.name));
-
- return new DependencyQueue._(
- solver,
- new Queue<PackageDep>.from(presorted),
- remaining);
- }
-
- DependencyQueue._(this._solver, this._presorted, this._remaining);
-
- /// Emits the next dependency in priority order.
- ///
- /// It is an error to call this if [isEmpty] returns `true`. Note that this
- /// function is *not* re-entrant. You should only advance after the previous
- /// advance has completed.
- Future<PackageDep> advance() {
- // Emit the sorted ones first.
- if (_presorted.isNotEmpty) {
- return new Future.value(_presorted.removeFirst());
- }
-
- // Sort the remaining packages when we need the first one.
- if (!_isSorted) return _sort().then((_) => _remaining.removeAt(0));
-
- return new Future.value(_remaining.removeAt(0));
- }
-
- /// Sorts the unselected packages by number of versions and name.
- Future _sort() {
- // Sorting is not re-entrant.
- assert(_sortFuture == null);
-
- _sortFuture = Future.wait(_remaining.map(_getNumVersions)).then((versions) {
- _sortFuture = null;
-
- // Map deps to the number of versions they have.
- var versionMap = new Map.fromIterables(_remaining, versions);
-
- // Sort in best-first order to minimize backtracking.
- _remaining.sort((a, b) {
- // Traverse into packages with fewer versions since they will lead to
- // less backtracking.
- if (versionMap[a] != versionMap[b]) {
- return versionMap[a].compareTo(versionMap[b]);
- }
-
- // Otherwise, just sort by name so that it's deterministic.
- return a.name.compareTo(b.name);
- });
-
- _isSorted = true;
- });
-
- return _sortFuture;
- }
-
- /// Given a dependency, returns a future that completes to the number of
- /// versions available for it.
- Future<int> _getNumVersions(PackageDep dep) {
- // There is only ever one version of the root package.
- if (dep.isRoot) {
- return new Future.value(1);
- }
-
- return _solver.cache.getVersions(dep.toRef()).then((versions) {
- // If the root package depends on this one, ignore versions that don't
- // match that constraint. Since the root package's dependency constraints
- // won't change during solving, we can safely filter out packages that
- // don't meet it.
- for (var rootDep in _solver.root.immediateDependencies) {
- if (rootDep.name == dep.name) {
- versions =
- versions.where((id) => rootDep.constraint.allows(id.version));
- break;
- }
- }
-
- return versions.length;
- }).catchError((error, trace) {
- // If it fails for any reason, just treat that as no versions. This
- // will sort this reference higher so that we can traverse into it
- // and report the error more properly.
- log.solver("Could not get versions for $dep:\n$error\n\n$trace");
- return 0;
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/solve_report.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/solve_report.dart
deleted file mode 100644
index 4e6cfa6..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/solver/solve_report.dart
+++ /dev/null
@@ -1,248 +0,0 @@
-// Copyright (c) 2013, 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 pub.solver.solve_report;
-
-import 'package:pub_semver/pub_semver.dart';
-
-import '../lock_file.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../source_registry.dart';
-import '../utils.dart';
-import 'version_solver.dart';
-
-/// Unlike [SolveResult], which is the static data describing a resolution,
-/// this class contains the mutable state used while generating the report
-/// itself.
-///
-/// It's a report builder.
-class SolveReport {
- final SolveType _type;
- final SourceRegistry _sources;
- final Package _root;
- final LockFile _previousLockFile;
- final SolveResult _result;
-
- /// The dependencies in [_result], keyed by package name.
- final _dependencies = new Map<String, PackageId>();
-
- final _output = new StringBuffer();
-
- SolveReport(this._type, this._sources, this._root, this._previousLockFile,
- this._result) {
- // Fill the map so we can use it later.
- for (var id in _result.packages) {
- _dependencies[id.name] = id;
- }
- }
-
- /// Displays a report of the results of the version resolution relative to
- /// the previous lock file.
- void show() {
- _reportChanges();
- _reportOverrides();
- }
-
- /// Displays a one-line message summarizing what changes were made (or would
- /// be made) to the lockfile.
- ///
- /// If [dryRun] is true, describes it in terms of what would be done.
- void summarize({bool dryRun: false}) {
- // Count how many dependencies actually changed.
- var dependencies = _dependencies.keys.toSet();
- dependencies.addAll(_previousLockFile.packages.keys);
- dependencies.remove(_root.name);
-
- var numChanged = dependencies.where((name) {
- var oldId = _previousLockFile.packages[name];
- var newId = _dependencies[name];
-
- // Added or removed dependencies count.
- if (oldId == null) return true;
- if (newId == null) return true;
-
- // The dependency existed before, so see if it was modified.
- return !_sources.idsEqual(oldId, newId);
- }).length;
-
- if (dryRun) {
- if (numChanged == 0) {
- log.message("No dependencies would change.");
- } else if (numChanged == 1) {
- log.message("Would change $numChanged dependency.");
- } else {
- log.message("Would change $numChanged dependencies.");
- }
- } else {
- if (numChanged == 0) {
- if (_type == SolveType.GET) {
- log.message("Got dependencies!");
- } else {
- log.message("No dependencies changed.");
- }
- } else if (numChanged == 1) {
- log.message("Changed $numChanged dependency!");
- } else {
- log.message("Changed $numChanged dependencies!");
- }
- }
- }
-
- /// Displays a report of all of the previous and current dependencies and
- /// how they have changed.
- void _reportChanges() {
- _output.clear();
-
- // Show the new set of dependencies ordered by name.
- var names = _result.packages.map((id) => id.name).toList();
- names.remove(_root.name);
- names.sort();
- names.forEach(_reportPackage);
-
- // Show any removed ones.
- var removed = _previousLockFile.packages.keys.toSet();
- removed.removeAll(names);
- if (removed.isNotEmpty) {
- _output.writeln("These packages are no longer being depended on:");
- removed = removed.toList();
- removed.sort();
- removed.forEach((name) => _reportPackage(name, alwaysShow: true));
- }
-
- log.message(_output);
- }
-
- /// Displays a warning about the overrides currently in effect.
- void _reportOverrides() {
- _output.clear();
-
- if (_result.overrides.isNotEmpty) {
- _output.writeln("Warning: You are using these overridden dependencies:");
- var overrides = _result.overrides.map((dep) => dep.name).toList();
- overrides.sort((a, b) => a.compareTo(b));
-
- overrides.forEach(
- (name) => _reportPackage(name, alwaysShow: true, highlightOverride: false));
-
- log.warning(_output);
- }
- }
-
- /// Reports the results of the upgrade on the package named [name].
- ///
- /// If [alwaysShow] is true, the package is reported even if it didn't change,
- /// regardless of [_type]. If [highlightOverride] is true (or absent), writes
- /// "(override)" next to overridden packages.
- void _reportPackage(String name, {bool alwaysShow: false,
- bool highlightOverride: true}) {
- var newId = _dependencies[name];
- var oldId = _previousLockFile.packages[name];
- var id = newId != null ? newId : oldId;
-
- var isOverridden =
- _result.overrides.map((dep) => dep.name).contains(id.name);
-
- // If the package was previously a dependency but the dependency has
- // changed in some way.
- var changed = false;
-
- // If the dependency was added or removed.
- var addedOrRemoved = false;
-
- // Show a one-character "icon" describing the change. They are:
- //
- // ! The package is being overridden.
- // - The package was removed.
- // + The package was added.
- // > The package was upgraded from a lower version.
- // < The package was downgraded from a higher version.
- // * Any other change between the old and new package.
- var icon;
- if (isOverridden) {
- icon = log.magenta("! ");
- } else if (newId == null) {
- icon = log.red("- ");
- addedOrRemoved = true;
- } else if (oldId == null) {
- icon = log.green("+ ");
- addedOrRemoved = true;
- } else if (!_sources.idDescriptionsEqual(oldId, newId)) {
- icon = log.cyan("* ");
- changed = true;
- } else if (oldId.version < newId.version) {
- icon = log.green("> ");
- changed = true;
- } else if (oldId.version > newId.version) {
- icon = log.cyan("< ");
- changed = true;
- } else {
- // Unchanged.
- icon = " ";
- }
-
- if (_type == SolveType.GET && !(alwaysShow || changed || addedOrRemoved)) {
- return;
- }
-
- _output.write(icon);
- _output.write(log.bold(id.name));
- _output.write(" ");
- _writeId(id);
-
- // If the package was upgraded, show what it was upgraded from.
- if (changed) {
- _output.write(" (was ");
- _writeId(oldId);
- _output.write(")");
- }
-
- // Highlight overridden packages.
- if (isOverridden && highlightOverride) {
- _output.write(" ${log.magenta('(overridden)')}");
- }
-
- // See if there are any newer versions of the package that we were
- // unable to upgrade to.
- if (newId != null && _type != SolveType.DOWNGRADE) {
- var versions = _result.availableVersions[newId.name];
-
- var newerStable = false;
- var newerUnstable = false;
-
- for (var version in versions) {
- if (version > newId.version) {
- if (version.isPreRelease) {
- newerUnstable = true;
- } else {
- newerStable = true;
- }
- }
- }
-
- // If there are newer stable versions, only show those.
- var message;
- if (newerStable) {
- message = "(${maxAll(versions, Version.prioritize)} available)";
- } else if (newerUnstable) {
- message = "(${maxAll(versions)} available)";
- }
-
- if (message != null) _output.write(" ${log.cyan(message)}");
- }
-
- _output.writeln();
- }
-
- /// Writes a terse description of [id] (not including its name) to the output.
- void _writeId(PackageId id) {
- _output.write(id.version);
-
- var source = _sources[id.source];
- if (source != _sources.defaultSource) {
- var description = source.formatDescription(_root.dir, id.description);
- _output.write(" from ${id.source} $description");
- }
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/version_queue.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/version_queue.dart
deleted file mode 100644
index 86c6e98..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/solver/version_queue.dart
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright (c) 2013, 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 pub.solver.version_queue;
-
-import 'dart:async';
-import 'dart:collection' show Queue;
-
-import '../package.dart';
-
-/// A function that asynchronously returns a sequence of package IDs.
-typedef Future<Iterable<PackageId>> PackageIdGenerator();
-
-/// A prioritized, asynchronous queue of the possible versions that can be
-/// selected for one package.
-///
-/// If there is a locked version, that comes first, followed by other versions
-/// in descending order. This avoids requesting the list of versions until
-/// needed (i.e. after any locked version has been consumed) to avoid unneeded
-/// network requests.
-class VersionQueue {
- /// The set of allowed versions that match [_constraint].
- ///
- /// If [_locked] is not `null`, this will initially be `null` until we
- /// advance past the locked version.
- Queue<PackageId> _allowed;
-
- /// The callback that will generate the sequence of packages. This will be
- /// called as lazily as possible.
- final PackageIdGenerator _allowedGenerator;
-
- /// The currently locked version of the package, or `null` if there is none,
- /// or we have advanced past it.
- PackageId _locked;
-
- /// Gets the currently selected version.
- PackageId get current {
- if (_locked != null) return _locked;
- return _allowed.first;
- }
-
- /// Whether the currently selected version has been responsible for a solve
- /// failure, or depends on a package that has.
- ///
- /// The solver uses this to determine which packages to backtrack to after a
- /// failure occurs. Any selected package that did *not* cause the failure can
- /// be skipped by the backtracker.
- bool get hasFailed => _hasFailed;
- bool _hasFailed = false;
-
- /// Creates a new [VersionQueue] queue for starting with the optional
- /// [locked] package followed by the results of calling [allowedGenerator].
- ///
- /// This is asynchronous so that [current] can always be accessed
- /// synchronously. If there is no locked version, we need to get the list of
- /// versions asynchronously before we can determine what the first one is.
- static Future<VersionQueue> create(PackageId locked,
- PackageIdGenerator allowedGenerator) {
- var versions = new VersionQueue._(locked, allowedGenerator);
-
- // If there is a locked version, it's the current one so it's synchronously
- // available now.
- if (locked != null) return new Future.value(versions);
-
- // Otherwise, the current version needs to be calculated before we can
- // return.
- return versions._calculateAllowed().then((_) => versions);
- }
-
- VersionQueue._(this._locked, this._allowedGenerator);
-
- /// Tries to advance to the next possible version.
- ///
- /// Returns `true` if it moved to a new version (which can be accessed from
- /// [current]. Returns `false` if there are no more versions.
- Future<bool> advance() {
- // Any failure was the fault of the previous version, not necessarily the
- // new one.
- _hasFailed = false;
-
- // If we have a locked version, consume it first.
- if (_locked != null) {
- // Advancing past the locked version, so need to load the others now
- // so that [current] is available.
- return _calculateAllowed().then((_) {
- _locked = null;
- return _allowed.isNotEmpty;
- });
- }
-
- // Move to the next allowed version.
- _allowed.removeFirst();
- return new Future.value(_allowed.isNotEmpty);
- }
-
- /// Marks the selected version as being directly or indirectly responsible
- /// for a solve failure.
- void fail() {
- _hasFailed = true;
- }
-
- /// Determines the list of allowed versions matching its constraint and places
- /// them in [_allowed].
- Future _calculateAllowed() {
- return _allowedGenerator().then((allowed) {
- _allowed = new Queue<PackageId>.from(allowed);
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/version_solver.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/version_solver.dart
deleted file mode 100644
index d22ace7..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/solver/version_solver.dart
+++ /dev/null
@@ -1,510 +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 pub.solver.version_solver;
-
-import 'dart:async';
-import "dart:convert";
-
-import 'package:pub_semver/pub_semver.dart';
-import 'package:stack_trace/stack_trace.dart';
-
-import '../exceptions.dart';
-import '../lock_file.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../pubspec.dart';
-import '../source_registry.dart';
-import '../utils.dart';
-import 'backtracking_solver.dart';
-import 'solve_report.dart';
-
-/// Attempts to select the best concrete versions for all of the transitive
-/// dependencies of [root] taking into account all of the [VersionConstraint]s
-/// that those dependencies place on each other and the requirements imposed by
-/// [lockFile].
-///
-/// If [useLatest] is given, then only the latest versions of the referenced
-/// packages will be used. This is for forcing an upgrade to one or more
-/// packages.
-///
-/// If [upgradeAll] is true, the contents of [lockFile] are ignored.
-Future<SolveResult> resolveVersions(SolveType type, SourceRegistry sources,
- Package root, {LockFile lockFile, List<String> useLatest}) {
- if (lockFile == null) lockFile = new LockFile.empty();
- if (useLatest == null) useLatest = [];
-
- return log.progress('Resolving dependencies', () {
- return new BacktrackingSolver(
- type,
- sources,
- root,
- lockFile,
- useLatest).solve();
- });
-}
-
-/// The result of a version resolution.
-class SolveResult {
- /// Whether the solver found a complete solution or failed.
- bool get succeeded => error == null;
-
- /// The list of concrete package versions that were selected for each package
- /// reachable from the root, or `null` if the solver failed.
- final List<PackageId> packages;
-
- /// The dependency overrides that were used in the solution.
- final List<PackageDep> overrides;
-
- /// A map from package names to the pubspecs for the versions of those
- /// packages that were installed, or `null` if the solver failed.
- final Map<String, Pubspec> pubspecs;
-
- /// The available versions of all selected packages from their source.
- ///
- /// Will be empty if the solve failed. An entry here may not include the full
- /// list of versions available if the given package was locked and did not
- /// need to be unlocked during the solve.
- final Map<String, List<Version>> availableVersions;
-
- /// The error that prevented the solver from finding a solution or `null` if
- /// it was successful.
- final SolveFailure error;
-
- /// The number of solutions that were attempted before either finding a
- /// successful solution or exhausting all options.
- ///
- /// In other words, one more than the number of times it had to backtrack
- /// because it found an invalid solution.
- final int attemptedSolutions;
-
- final SourceRegistry _sources;
- final Package _root;
- final LockFile _previousLockFile;
-
- /// Returns the names of all packages that were changed.
- ///
- /// This includes packages that were added or removed.
- Set<String> get changedPackages {
- if (packages == null) return null;
-
- var changed = packages.where(
- (id) =>
- !_sources.idsEqual(
- _previousLockFile.packages[id.name],
- id)).map((id) => id.name).toSet();
-
- return changed.union(
- _previousLockFile.packages.keys.where(
- (package) => !availableVersions.containsKey(package)).toSet());
- }
-
- SolveResult.success(this._sources, this._root, this._previousLockFile,
- this.packages, this.overrides, this.pubspecs, this.availableVersions,
- this.attemptedSolutions)
- : error = null;
-
- SolveResult.failure(this._sources, this._root, this._previousLockFile,
- this.overrides, this.error, this.attemptedSolutions)
- : this.packages = null,
- this.pubspecs = null,
- this.availableVersions = {};
-
- /// Displays a report of what changes were made to the lockfile.
- ///
- /// [type] is the type of version resolution that was run.
- void showReport(SolveType type) {
- new SolveReport(type, _sources, _root, _previousLockFile, this).show();
- }
-
- /// Displays a one-line message summarizing what changes were made (or would
- /// be made) to the lockfile.
- ///
- /// [type] is the type of version resolution that was run.
- void summarizeChanges(SolveType type, {bool dryRun: false}) {
- new SolveReport(
- type,
- _sources,
- _root,
- _previousLockFile,
- this).summarize(dryRun: dryRun);
- }
-
- String toString() {
- if (!succeeded) {
- return 'Failed to solve after $attemptedSolutions attempts:\n' '$error';
- }
-
- return 'Took $attemptedSolutions tries to resolve to\n'
- '- ${packages.join("\n- ")}';
- }
-}
-
-/// Maintains a cache of previously-requested data: pubspecs and version lists.
-///
-/// Used to avoid requesting the same pubspec from the server repeatedly.
-class PubspecCache {
- final SourceRegistry _sources;
-
- /// The already-requested cached version lists.
- final _versions = new Map<PackageRef, List<PackageId>>();
-
- /// The errors from failed version list requests.
- final _versionErrors = new Map<PackageRef, Pair<Object, Chain>>();
-
- /// The already-requested cached pubspecs.
- final _pubspecs = new Map<PackageId, Pubspec>();
-
- /// The type of version resolution that was run.
- final SolveType _type;
-
- /// The number of times a version list was requested and it wasn't cached and
- /// had to be requested from the source.
- int _versionCacheMisses = 0;
-
- /// The number of times a version list was requested and the cached version
- /// was returned.
- int _versionCacheHits = 0;
-
- /// The number of times a pubspec was requested and it wasn't cached and had
- /// to be requested from the source.
- int _pubspecCacheMisses = 0;
-
- /// The number of times a pubspec was requested and the cached version was
- /// returned.
- int _pubspecCacheHits = 0;
-
- PubspecCache(this._type, this._sources);
-
- /// Caches [pubspec] as the [Pubspec] for the package identified by [id].
- void cache(PackageId id, Pubspec pubspec) {
- _pubspecs[id] = pubspec;
- }
-
- /// Loads the pubspec for the package identified by [id].
- Future<Pubspec> getPubspec(PackageId id) {
- // Complete immediately if it's already cached.
- if (_pubspecs.containsKey(id)) {
- _pubspecCacheHits++;
- return new Future<Pubspec>.value(_pubspecs[id]);
- }
-
- _pubspecCacheMisses++;
-
- var source = _sources[id.source];
- return source.describe(id).then((pubspec) {
- _pubspecs[id] = pubspec;
- return pubspec;
- });
- }
-
- /// Returns the previously cached pubspec for the package identified by [id]
- /// or returns `null` if not in the cache.
- Pubspec getCachedPubspec(PackageId id) => _pubspecs[id];
-
- /// Gets the list of versions for [package].
- ///
- /// Packages are sorted in descending version order with all "stable"
- /// versions (i.e. ones without a prerelease suffix) before pre-release
- /// versions. This ensures that the solver prefers stable packages over
- /// unstable ones.
- Future<List<PackageId>> getVersions(PackageRef package) {
- if (package.isRoot) {
- throw new StateError("Cannot get versions for root package $package.");
- }
-
- // See if we have it cached.
- var versions = _versions[package];
- if (versions != null) {
- _versionCacheHits++;
- return new Future.value(versions);
- }
-
- // See if we cached a failure.
- var error = _versionErrors[package];
- if (error != null) {
- _versionCacheHits++;
- return new Future.error(error.first, error.last);
- }
-
- _versionCacheMisses++;
-
- var source = _sources[package.source];
- return source.getVersions(
- package.name,
- package.description).then((versions) {
- // Sort by priority so we try preferred versions first.
- versions.sort(
- _type == SolveType.DOWNGRADE ? Version.antiprioritize : Version.prioritize);
-
- var ids =
- versions.reversed.map((version) => package.atVersion(version)).toList();
- _versions[package] = ids;
- return ids;
- }).catchError((error, trace) {
- // If an error occurs, cache that too. We only want to do one request
- // for any given package, successful or not.
- log.solver("Could not get versions for $package:\n$error\n\n$trace");
- _versionErrors[package] = new Pair(error, new Chain.forTrace(trace));
- throw error;
- });
- }
-
- /// Returns the previously cached list of versions for the package identified
- /// by [package] or returns `null` if not in the cache.
- List<PackageId> getCachedVersions(PackageRef package) => _versions[package];
-
- /// Returns a user-friendly output string describing metrics of the solve.
- String describeResults() {
- var results = '''- Requested $_versionCacheMisses version lists
-- Looked up $_versionCacheHits cached version lists
-- Requested $_pubspecCacheMisses pubspecs
-- Looked up $_pubspecCacheHits cached pubspecs
-''';
-
- // Uncomment this to dump the visited package graph to JSON.
- //results += _debugWritePackageGraph();
-
- return results;
- }
-
- /// This dumps the set of packages that were looked at by the solver to a
- /// JSON map whose format matches the map passed to [testResolve] in the
- /// version solver unit tests.
- ///
- /// If a real-world version solve is failing, this can be used to mirror that
- /// data to build a regression test using mock packages.
- String _debugDescribePackageGraph() {
- var packages = {};
- _pubspecs.forEach((id, pubspec) {
- var deps = {};
- packages["${id.name} ${id.version}"] = deps;
-
- for (var dep in pubspec.dependencies) {
- deps[dep.name] = dep.constraint.toString();
- }
- });
-
- // Add in the packages that we know of but didn't need their pubspecs.
- _versions.forEach((ref, versions) {
- for (var id in versions) {
- packages.putIfAbsent("${id.name} ${id.version}", () => {});
- }
- });
-
- // TODO(rnystrom): Include dev dependencies and dependency overrides.
-
- return JSON.encode(packages);
- }
-}
-
-/// A reference from a depending package to a package that it depends on.
-class Dependency {
- /// The name of the package that has this dependency.
- final String depender;
-
- /// The version of the depender that has this dependency.
- final Version dependerVersion;
-
- /// The package being depended on.
- final PackageDep dep;
-
- /// Whether [depender] is a magic dependency (e.g. "pub itself" or "pub global
- /// activate").
- bool get isMagic => depender.contains(" ");
-
-
- Dependency(this.depender, this.dependerVersion, this.dep);
-
- String toString() => '$depender $dependerVersion -> $dep';
-}
-
-/// An enum for types of version resolution.
-class SolveType {
- /// As few changes to the lockfile as possible to be consistent with the
- /// pubspec.
- static const GET = const SolveType._("get");
-
- /// Upgrade all packages or specific packages to the highest versions
- /// possible, regardless of the lockfile.
- static const UPGRADE = const SolveType._("upgrade");
-
- /// Downgrade all packages or specific packages to the lowest versions
- /// possible, regardless of the lockfile.
- static const DOWNGRADE = const SolveType._("downgrade");
-
- final String _name;
-
- const SolveType._(this._name);
-
- String toString() => _name;
-}
-
-/// Base class for all failures that can occur while trying to resolve versions.
-abstract class SolveFailure implements ApplicationException {
- /// The name of the package whose version could not be solved.
- ///
- /// Will be `null` if the failure is not specific to one package.
- final String package;
-
- /// The known dependencies on [package] at the time of the failure.
- ///
- /// Will be an empty collection if the failure is not specific to one package.
- final Iterable<Dependency> dependencies;
-
- String get message => toString();
-
- /// A message describing the specific kind of solve failure.
- String get _message {
- throw new UnimplementedError("Must override _message or toString().");
- }
-
- SolveFailure(this.package, Iterable<Dependency> dependencies)
- : dependencies = dependencies != null ? dependencies : <Dependency>[];
-
- String toString() {
- if (dependencies.isEmpty) return _message;
-
- var buffer = new StringBuffer();
- buffer.write("$_message:");
-
- var sorted = dependencies.toList();
- sorted.sort((a, b) => a.depender.compareTo(b.depender));
-
- for (var dep in sorted) {
- buffer.writeln();
- buffer.write("- ${log.bold(dep.depender)}");
- if (!dep.isMagic) buffer.write(" ${dep.dependerVersion}");
- buffer.write(" ${_describeDependency(dep.dep)}");
- }
-
- return buffer.toString();
- }
-
- /// Describes a dependency's reference in the output message.
- ///
- /// Override this to highlight which aspect of [dep] led to the failure.
- String _describeDependency(PackageDep dep) =>
- "depends on version ${dep.constraint}";
-}
-
-/// Exception thrown when the current SDK's version does not match a package's
-/// constraint on it.
-class BadSdkVersionException extends SolveFailure {
- final String _message;
-
- BadSdkVersionException(String package, String message)
- : super(package, null),
- _message = message;
-}
-
-/// Exception thrown when the [VersionConstraint] used to match a package is
-/// valid (i.e. non-empty), but there are no available versions of the package
-/// that fit that constraint.
-class NoVersionException extends SolveFailure {
- final VersionConstraint constraint;
-
- /// The last selected version of the package that failed to meet the new
- /// constraint.
- ///
- /// This will be `null` when the failure occurred because there are no
- /// versions of the package *at all* that match the constraint. It will be
- /// non-`null` when a version was selected, but then the solver tightened a
- /// constraint such that that version was no longer allowed.
- final Version version;
-
- NoVersionException(String package, this.version, this.constraint,
- Iterable<Dependency> dependencies)
- : super(package, dependencies);
-
- String get _message {
- if (version == null) {
- return "Package $package has no versions that match $constraint derived "
- "from";
- }
-
- return "Package $package $version does not match $constraint derived from";
- }
-}
-
-// TODO(rnystrom): Report the list of depending packages and their constraints.
-/// Exception thrown when the most recent version of [package] must be selected,
-/// but doesn't match the [VersionConstraint] imposed on the package.
-class CouldNotUpgradeException extends SolveFailure {
- final VersionConstraint constraint;
- final Version best;
-
- CouldNotUpgradeException(String package, this.constraint, this.best)
- : super(package, null);
-
- String get _message =>
- "The latest version of $package, $best, does not match $constraint.";
-}
-
-/// Exception thrown when the [VersionConstraint] used to match a package is
-/// the empty set: in other words, multiple packages depend on it and have
-/// conflicting constraints that have no overlap.
-class DisjointConstraintException extends SolveFailure {
- DisjointConstraintException(String package, Iterable<Dependency> dependencies)
- : super(package, dependencies);
-
- String get _message => "Incompatible version constraints on $package";
-}
-
-/// Exception thrown when two packages with the same name but different sources
-/// are depended upon.
-class SourceMismatchException extends SolveFailure {
- String get _message => "Incompatible dependencies on $package";
-
- SourceMismatchException(String package, Iterable<Dependency> dependencies)
- : super(package, dependencies);
-
- String _describeDependency(PackageDep dep) =>
- "depends on it from source ${dep.source}";
-}
-
-/// Exception thrown when a dependency on an unknown source name is found.
-class UnknownSourceException extends SolveFailure {
- UnknownSourceException(String package, Iterable<Dependency> dependencies)
- : super(package, dependencies);
-
- String toString() {
- var dep = dependencies.single;
- return 'Package ${dep.depender} depends on ${dep.dep.name} from unknown '
- 'source "${dep.dep.source}".';
- }
-}
-
-/// Exception thrown when two packages with the same name and source but
-/// different descriptions are depended upon.
-class DescriptionMismatchException extends SolveFailure {
- String get _message => "Incompatible dependencies on $package";
-
- DescriptionMismatchException(String package,
- Iterable<Dependency> dependencies)
- : super(package, dependencies);
-
- String _describeDependency(PackageDep dep) {
- // TODO(nweiz): Dump descriptions to YAML when that's supported.
- return "depends on it with description ${JSON.encode(dep.description)}";
- }
-}
-
-/// Exception thrown when a dependency could not be found in its source.
-///
-/// Unlike [PackageNotFoundException], this includes information about the
-/// dependent packages requesting the missing one.
-class DependencyNotFoundException extends SolveFailure {
- final PackageNotFoundException _innerException;
- String get _message => "${_innerException.message}\nDepended on by";
-
- DependencyNotFoundException(String package, this._innerException,
- Iterable<Dependency> dependencies)
- : super(package, dependencies);
-
- /// The failure isn't because of the version of description of the package,
- /// it's the package itself that can't be found, so just show the name and no
- /// descriptive details.
- String _describeDependency(PackageDep dep) => "";
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/source.dart b/sdk/lib/_internal/pub_generated/lib/src/source.dart
deleted file mode 100644
index d7b00f1..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/source.dart
+++ /dev/null
@@ -1,187 +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 pub.source;
-
-import 'dart:async';
-
-import 'package:pub_semver/pub_semver.dart';
-
-import 'package.dart';
-import 'pubspec.dart';
-import 'system_cache.dart';
-
-/// A source from which to get packages.
-///
-/// Each source has many packages that it looks up using [PackageId]s. Sources
-/// that inherit this directly (currently just [PathSource]) are *uncached*
-/// sources. They deliver a package directly to the package that depends on it.
-///
-/// Other sources are *cached* sources. These extend [CachedSource]. When a
-/// package needs a dependency from a cached source, it is first installed in
-/// the [SystemCache] and then acquired from there.
-abstract class Source {
- /// The name of the source.
- ///
- /// Should be lower-case, suitable for use in a filename, and unique accross
- /// all sources.
- String get name;
-
- /// Whether this source can choose between multiple versions of the same
- /// package during version solving.
- ///
- /// Defaults to `false`.
- final bool hasMultipleVersions = false;
-
- /// Whether or not this source is the default source.
- bool get isDefault => systemCache.sources.defaultSource == this;
-
- /// The system cache with which this source is registered.
- SystemCache get systemCache {
- assert(_systemCache != null);
- return _systemCache;
- }
-
- /// The system cache variable.
- ///
- /// Set by [_bind].
- SystemCache _systemCache;
-
- /// Records the system cache to which this source belongs.
- ///
- /// This should only be called once for each source, by
- /// [SystemCache.register]. It should not be overridden by base classes.
- void bind(SystemCache systemCache) {
- assert(_systemCache == null);
- this._systemCache = systemCache;
- }
-
- /// Get the list of all versions that exist for the package described by
- /// [description].
- ///
- /// [name] is the expected name of the package.
- ///
- /// Note that this does *not* require the packages to be downloaded locally,
- /// which is the point. This is used during version resolution to determine
- /// which package versions are available to be downloaded (or already
- /// downloaded).
- ///
- /// By default, this assumes that each description has a single version and
- /// uses [describe] to get that version.
- Future<List<Version>> getVersions(String name, description) {
- var id = new PackageId(name, this.name, Version.none, description);
- return describe(id).then((pubspec) => [pubspec.version]);
- }
-
- /// Loads the (possibly remote) pubspec for the package version identified by
- /// [id].
- ///
- /// This may be called for packages that have not yet been downloaded during
- /// the version resolution process.
- ///
- /// Sources should not override this. Instead, they implement [doDescribe].
- Future<Pubspec> describe(PackageId id) {
- if (id.isRoot) throw new ArgumentError("Cannot describe the root package.");
- if (id.source != name) {
- throw new ArgumentError("Package $id does not use source $name.");
- }
-
- // Delegate to the overridden one.
- return doDescribe(id);
- }
-
- /// Loads the (possibly remote) pubspec for the package version identified by
- /// [id].
- ///
- /// This may be called for packages that have not yet been downloaded during
- /// the version resolution process.
- ///
- /// This method is effectively protected: subclasses must implement it, but
- /// external code should not call this. Instead, call [describe].
- Future<Pubspec> doDescribe(PackageId id);
-
- /// Ensures [id] is available locally and creates a symlink at [symlink]
- /// pointing it.
- Future get(PackageId id, String symlink);
-
- /// Returns the directory where this package can (or could) be found locally.
- ///
- /// If the source is cached, this will be a path in the system cache. In that
- /// case, this will return a directory even if the package has not been
- /// installed into the cache yet.
- Future<String> getDirectory(PackageId id);
-
- /// Gives the source a chance to interpret and validate the description for
- /// a package coming from this source.
- ///
- /// When a [Pubspec] or [LockFile] is parsed, it reads in the description for
- /// each dependency. It is up to the dependency's [Source] to determine how
- /// that should be interpreted. This will be called during parsing to validate
- /// that the given [description] is well-formed according to this source, and
- /// to give the source a chance to canonicalize the description.
- ///
- /// [containingPath] is the path to the local file (pubspec or lockfile)
- /// where this description appears. It may be `null` if the description is
- /// coming from some in-memory source (such as pulling down a pubspec from
- /// pub.dartlang.org).
- ///
- /// It should return if a (possibly modified) valid description, or throw a
- /// [FormatException] if not valid.
- ///
- /// [fromLockFile] is true when the description comes from a [LockFile], to
- /// allow the source to use lockfile-specific descriptions via [resolveId].
- dynamic parseDescription(String containingPath, description,
- {bool fromLockFile: false});
-
- /// When a [LockFile] is serialized, it uses this method to get the
- /// [description] in the right format.
- ///
- /// [containingPath] is the containing directory of the root package.
- dynamic serializeDescription(String containingPath, description) {
- return description;
- }
-
- /// When a package [description] is shown to the user, this is called to
- /// convert it into a human-friendly form.
- ///
- /// By default, it just converts the description to a string, but sources
- /// may customize this. [containingPath] is the containing directory of the
- /// root package.
- String formatDescription(String containingPath, description) {
- return description.toString();
- }
-
- /// Returns whether or not [description1] describes the same package as
- /// [description2] for this source.
- ///
- /// This method should be light-weight. It doesn't need to validate that
- /// either package exists.
- bool descriptionsEqual(description1, description2);
-
- /// Resolves [id] to a more possibly more precise that will uniquely identify
- /// a package regardless of when the package is requested.
- ///
- /// For some sources, [PackageId]s can point to different chunks of code at
- /// different times. This takes such an [id] and returns a future that
- /// completes to a [PackageId] that will uniquely specify a single chunk of
- /// code forever.
- ///
- /// For example, [GitSource] might take an [id] with description
- /// `http://github.com/dart-lang/some-lib.git` and return an id with a
- /// description that includes the current commit of the Git repository.
- ///
- /// Pub calls this after getting a package, so the source can use the local
- /// package to determine information about the resolved id.
- ///
- /// The returned [PackageId] may have a description field that's invalid
- /// according to [parseDescription], although it must still be serializable
- /// to JSON and YAML. It must also be equal to [id] according to
- /// [descriptionsEqual].
- ///
- /// By default, this just returns [id].
- Future<PackageId> resolveId(PackageId id) => new Future.value(id);
-
- /// Returns the source's name.
- String toString() => name;
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/cached.dart b/sdk/lib/_internal/pub_generated/lib/src/source/cached.dart
deleted file mode 100644
index 9521471..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/source/cached.dart
+++ /dev/null
@@ -1,75 +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.
-
-library pub.source.cached;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-import '../io.dart';
-import '../package.dart';
-import '../pubspec.dart';
-import '../source.dart';
-import '../utils.dart';
-
-/// Base class for a [Source] that installs packages into pub's [SystemCache].
-///
-/// A source should be cached if it requires network access to retrieve
-/// packages or the package needs to be "frozen" at the point in time that it's
-/// installed. (For example, Git packages are cached because installing from
-/// the same repo over time may yield different commits.)
-abstract class CachedSource extends Source {
- /// The root directory of this source's cache within the system cache.
- ///
- /// This shouldn't be overridden by subclasses.
- String get systemCacheRoot => path.join(systemCache.rootDir, name);
-
- /// If [id] is already in the system cache, just loads it from there.
- ///
- /// Otherwise, defers to the subclass.
- Future<Pubspec> doDescribe(PackageId id) {
- return getDirectory(id).then((packageDir) {
- if (fileExists(path.join(packageDir, "pubspec.yaml"))) {
- return new Pubspec.load(
- packageDir,
- systemCache.sources,
- expectedName: id.name);
- }
-
- return describeUncached(id);
- });
- }
-
- /// Loads the (possibly remote) pubspec for the package version identified by
- /// [id].
- ///
- /// This will only be called for packages that have not yet been installed in
- /// the system cache.
- Future<Pubspec> describeUncached(PackageId id);
-
- Future get(PackageId id, String symlink) {
- return downloadToSystemCache(id).then((pkg) {
- createPackageSymlink(id.name, pkg.dir, symlink);
- });
- }
-
- /// Determines if the package with [id] is already downloaded to the system
- /// cache.
- Future<bool> isInSystemCache(PackageId id) =>
- getDirectory(id).then(dirExists);
-
- /// Downloads the package identified by [id] to the system cache.
- Future<Package> downloadToSystemCache(PackageId id);
-
- /// Returns the [Package]s that have been downloaded to the system cache.
- List<Package> getCachedPackages();
-
- /// Reinstalls all packages that have been previously installed into the
- /// system cache by this source.
- ///
- /// Returns a [Pair] whose first element is the number of packages
- /// successfully repaired and the second is the number of failures.
- Future<Pair<int, int>> repairCachedPackages();
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/git.dart b/sdk/lib/_internal/pub_generated/lib/src/source/git.dart
deleted file mode 100644
index 7edaac2..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/source/git.dart
+++ /dev/null
@@ -1,400 +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 pub.source.git;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-import '../git.dart' as git;
-import '../io.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../pubspec.dart';
-import '../utils.dart';
-import 'cached.dart';
-
-/// A package source that gets packages from Git repos.
-class GitSource extends CachedSource {
- /// Given a valid git package description, returns the URL of the repository
- /// it pulls from.
- static String urlFromDescription(description) => description["url"];
-
- final name = "git";
-
- /// The paths to the canonical clones of repositories for which "git fetch"
- /// has already been run during this run of pub.
- final _updatedRepos = new Set<String>();
-
- /// Given a Git repo that contains a pub package, gets the name of the pub
- /// package.
- Future<String> getPackageNameFromRepo(String repo) {
- // Clone the repo to a temp directory.
- return withTempDir((tempDir) {
- return _clone(repo, tempDir, shallow: true).then((_) {
- var pubspec = new Pubspec.load(tempDir, systemCache.sources);
- return pubspec.name;
- });
- });
- }
-
- /// Since we don't have an easy way to read from a remote Git repo, this
- /// just installs [id] into the system cache, then describes it from there.
- Future<Pubspec> describeUncached(PackageId id) {
- return downloadToSystemCache(id).then((package) => package.pubspec);
- }
-
- /// Clones a Git repo to the local filesystem.
- ///
- /// The Git cache directory is a little idiosyncratic. At the top level, it
- /// contains a directory for each commit of each repository, named `<package
- /// name>-<commit hash>`. These are the canonical package directories that are
- /// linked to from the `packages/` directory.
- ///
- /// In addition, the Git system cache contains a subdirectory named `cache/`
- /// which contains a directory for each separate repository URL, named
- /// `<package name>-<url hash>`. These are used to check out the repository
- /// itself; each of the commit-specific directories are clones of a directory
- /// in `cache/`.
- Future<Package> downloadToSystemCache(PackageId id) {
- var revisionCachePath;
-
- if (!git.isInstalled) {
- fail(
- "Cannot get ${id.name} from Git (${_getUrl(id)}).\n"
- "Please ensure Git is correctly installed.");
- }
-
- ensureDir(path.join(systemCacheRoot, 'cache'));
- return _ensureRevision(id).then((_) => getDirectory(id)).then((path) {
- revisionCachePath = path;
- if (entryExists(revisionCachePath)) return null;
- return _clone(_repoCachePath(id), revisionCachePath, mirror: false);
- }).then((_) {
- var ref = _getEffectiveRef(id);
- if (ref == 'HEAD') return null;
- return _checkOut(revisionCachePath, ref);
- }).then((_) {
- return new Package.load(id.name, revisionCachePath, systemCache.sources);
- });
- }
-
- /// Returns the path to the revision-specific cache of [id].
- Future<String> getDirectory(PackageId id) {
- return _ensureRevision(id).then((rev) {
- var revisionCacheName = '${id.name}-$rev';
- return path.join(systemCacheRoot, revisionCacheName);
- });
- }
-
- /// Ensures [description] is a Git URL.
- dynamic parseDescription(String containingPath, description,
- {bool fromLockFile: false}) {
- // TODO(rnystrom): Handle git URLs that are relative file paths (#8570).
- // TODO(rnystrom): Now that this function can modify the description, it
- // may as well canonicalize it to a map so that other code in the source
- // can assume that.
- // A single string is assumed to be a Git URL.
- if (description is String) return description;
- if (description is! Map || !description.containsKey('url')) {
- throw new FormatException(
- "The description must be a Git URL or a map " "with a 'url' key.");
- }
-
- var parsed = new Map.from(description);
- parsed.remove('url');
- parsed.remove('ref');
- if (fromLockFile) parsed.remove('resolved-ref');
-
- if (!parsed.isEmpty) {
- var plural = parsed.length > 1;
- var keys = parsed.keys.join(', ');
- throw new FormatException("Invalid key${plural ? 's' : ''}: $keys.");
- }
-
- return description;
- }
-
- /// If [description] has a resolved ref, print it out in short-form.
- ///
- /// This helps distinguish different git commits with the same pubspec
- /// version.
- String formatDescription(String containingPath, description) {
- if (description is Map && description.containsKey('resolved-ref')) {
- return "${description['url']} at "
- "${description['resolved-ref'].substring(0, 6)}";
- } else {
- return super.formatDescription(containingPath, description);
- }
- }
-
- /// Two Git descriptions are equal if both their URLs and their refs are
- /// equal.
- bool descriptionsEqual(description1, description2) {
- // TODO(nweiz): Do we really want to throw an error if you have two
- // dependencies on some repo, one of which specifies a ref and one of which
- // doesn't? If not, how do we handle that case in the version solver?
- if (_getUrl(description1) != _getUrl(description2)) return false;
- if (_getRef(description1) != _getRef(description2)) return false;
-
- if (description1 is Map &&
- description1.containsKey('resolved-ref') &&
- description2 is Map &&
- description2.containsKey('resolved-ref')) {
- return description1['resolved-ref'] == description2['resolved-ref'];
- }
-
- return true;
- }
-
- /// Attaches a specific commit to [id] to disambiguate it.
- Future<PackageId> resolveId(PackageId id) {
- return _ensureRevision(id).then((revision) {
- var description = {
- 'url': _getUrl(id),
- 'ref': _getRef(id)
- };
- description['resolved-ref'] = revision;
- return new PackageId(id.name, name, id.version, description);
- });
- }
-
- List<Package> getCachedPackages() {
- // TODO(keertip): Implement getCachedPackages().
- throw new UnimplementedError(
- "The git source doesn't support listing its cached packages yet.");
- }
-
- /// Resets all cached packages back to the pristine state of the Git
- /// repository at the revision they are pinned to.
- Future<Pair<int, int>> repairCachedPackages() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- var successes = 0;
- var failures = 0;
- var packages = listDir(systemCacheRoot).where(((entry) {
- return dirExists(path.join(entry, ".git"));
- })).map(((packageDir) {
- return new Package.load(null, packageDir, systemCache.sources);
- })).toList();
- packages.sort(Package.orderByNameAndVersion);
- var it0 = packages.iterator;
- break0() {
- completer0.complete(new Pair(successes, failures));
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var package = it0.current;
- log.message(
- "Resetting Git repository for "
- "${log.bold(package.name)} ${package.version}...");
- join1() {
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- catch0(error, stackTrace) {
- try {
- if (error is git.GitException) {
- log.error(
- "Failed to reset ${log.bold(package.name)} "
- "${package.version}. Error:\n${error}");
- log.fine(stackTrace);
- failures++;
- tryDeleteEntry(package.dir);
- join1();
- } else {
- throw error;
- }
- } catch (error, stackTrace) {
- completer0.completeError(error, stackTrace);
- }
- }
- try {
- new Future.value(
- git.run(["clean", "-d", "--force", "-x"], workingDir: package.dir)).then((x0) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- x0;
- new Future.value(
- git.run(["reset", "--hard", "HEAD"], workingDir: package.dir)).then((x1) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- x1;
- successes++;
- join1();
- } catch (e0, s0) {
- catch0(e0, s0);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: catch0);
- } catch (e1, s1) {
- catch0(e1, s1);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: catch0);
- } catch (e2, s2) {
- catch0(e2, s2);
- }
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- if (!dirExists(systemCacheRoot)) {
- completer0.complete(new Pair(0, 0));
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Ensure that the canonical clone of the repository referred to by [id] (the
- /// one in `<system cache>/git/cache`) exists and contains the revision
- /// referred to by [id].
- ///
- /// Returns a future that completes to the hash of the revision identified by
- /// [id].
- Future<String> _ensureRevision(PackageId id) {
- return new Future.sync(() {
- var path = _repoCachePath(id);
- if (!entryExists(path)) {
- return _clone(_getUrl(id), path, mirror: true).then((_) => _getRev(id));
- }
-
- // If [id] didn't come from a lockfile, it may be using a symbolic
- // reference. We want to get the latest version of that reference.
- var description = id.description;
- if (description is! Map || !description.containsKey('resolved-ref')) {
- return _updateRepoCache(id).then((_) => _getRev(id));
- }
-
- // If [id] did come from a lockfile, then we want to avoid running "git
- // fetch" if possible to avoid networking time and errors. See if the
- // revision exists in the repo cache before updating it.
- return _getRev(id).catchError((error) {
- if (error is! git.GitException) throw error;
- return _updateRepoCache(id).then((_) => _getRev(id));
- });
- });
- }
-
- /// Runs "git fetch" in the canonical clone of the repository referred to by
- /// [id].
- ///
- /// This assumes that the canonical clone already exists.
- Future _updateRepoCache(PackageId id) {
- var path = _repoCachePath(id);
- if (_updatedRepos.contains(path)) return new Future.value();
- return git.run(["fetch"], workingDir: path).then((_) {
- _updatedRepos.add(path);
- });
- }
-
- /// Runs "git rev-list" in the canonical clone of the repository referred to
- /// by [id] on the effective ref of [id].
- ///
- /// This assumes that the canonical clone already exists.
- Future<String> _getRev(PackageId id) {
- return git.run(
- ["rev-list", "--max-count=1", _getEffectiveRef(id)],
- workingDir: _repoCachePath(id)).then((result) => result.first);
- }
-
- /// Clones the repo at the URI [from] to the path [to] on the local
- /// filesystem.
- ///
- /// If [mirror] is true, creates a bare, mirrored clone. This doesn't check
- /// out the working tree, but instead makes the repository a local mirror of
- /// the remote repository. See the manpage for `git clone` for more
- /// information.
- ///
- /// If [shallow] is true, creates a shallow clone that contains no history
- /// for the repository.
- Future _clone(String from, String to, {bool mirror: false, bool shallow:
- false}) {
- return new Future.sync(() {
- // Git on Windows does not seem to automatically create the destination
- // directory.
- ensureDir(to);
- var args = ["clone", from, to];
-
- if (mirror) args.insert(1, "--mirror");
- if (shallow) args.insertAll(1, ["--depth", "1"]);
-
- return git.run(args);
- }).then((result) => null);
- }
-
- /// Checks out the reference [ref] in [repoPath].
- Future _checkOut(String repoPath, String ref) {
- return git.run(
- ["checkout", ref],
- workingDir: repoPath).then((result) => null);
- }
-
- /// Returns the path to the canonical clone of the repository referred to by
- /// [id] (the one in `<system cache>/git/cache`).
- String _repoCachePath(PackageId id) {
- var repoCacheName = '${id.name}-${sha1(_getUrl(id))}';
- return path.join(systemCacheRoot, 'cache', repoCacheName);
- }
-
- /// Returns the repository URL for [id].
- ///
- /// [description] may be a description or a [PackageId].
- String _getUrl(description) {
- description = _getDescription(description);
- if (description is String) return description;
- return description['url'];
- }
-
- /// Returns the commit ref that should be checked out for [description].
- ///
- /// This differs from [_getRef] in that it doesn't just return the ref in
- /// [description]. It will return a sensible default if that ref doesn't
- /// exist, and it will respect the "resolved-ref" parameter set by
- /// [resolveId].
- ///
- /// [description] may be a description or a [PackageId].
- String _getEffectiveRef(description) {
- description = _getDescription(description);
- if (description is Map && description.containsKey('resolved-ref')) {
- return description['resolved-ref'];
- }
-
- var ref = _getRef(description);
- return ref == null ? 'HEAD' : ref;
- }
-
- /// Returns the commit ref for [description], or null if none is given.
- ///
- /// [description] may be a description or a [PackageId].
- String _getRef(description) {
- description = _getDescription(description);
- if (description is String) return null;
- return description['ref'];
- }
-
- /// Returns [description] if it's a description, or [PackageId.description] if
- /// it's a [PackageId].
- _getDescription(description) {
- if (description is PackageId) return description.description;
- return description;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/hosted.dart b/sdk/lib/_internal/pub_generated/lib/src/source/hosted.dart
deleted file mode 100644
index 37f2799..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/source/hosted.dart
+++ /dev/null
@@ -1,450 +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 pub.source.hosted;
-
-import 'dart:async';
-import 'dart:io' as io;
-import "dart:convert";
-
-import 'package:http/http.dart' as http;
-import 'package:path/path.dart' as path;
-import 'package:pub_semver/pub_semver.dart';
-
-import '../exceptions.dart';
-import '../http.dart';
-import '../io.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../pubspec.dart';
-import '../utils.dart';
-import 'cached.dart';
-
-/// A package source that gets packages from a package hosting site that uses
-/// the same API as pub.dartlang.org.
-class HostedSource extends CachedSource {
- final name = "hosted";
- final hasMultipleVersions = true;
-
- /// Gets the default URL for the package server for hosted dependencies.
- static String get defaultUrl {
- var url = io.Platform.environment["PUB_HOSTED_URL"];
- if (url != null) return url;
-
- return "https://pub.dartlang.org";
- }
-
- /// Downloads a list of all versions of a package that are available from the
- /// site.
- Future<List<Version>> getVersions(String name, description) {
- var url =
- _makeUrl(description, (server, package) => "$server/api/packages/$package");
-
- log.io("Get versions from $url.");
- return httpClient.read(url, headers: PUB_API_HEADERS).then((body) {
- var doc = JSON.decode(body);
- return doc['versions'].map(
- (version) => new Version.parse(version['version'])).toList();
- }).catchError((ex, stackTrace) {
- var parsed = _parseDescription(description);
- _throwFriendlyError(ex, stackTrace, parsed.first, parsed.last);
- });
- }
-
- /// Downloads and parses the pubspec for a specific version of a package that
- /// is available from the site.
- Future<Pubspec> describeUncached(PackageId id) {
- // Request it from the server.
- var url = _makeVersionUrl(
- id,
- (server, package, version) =>
- "$server/api/packages/$package/versions/$version");
-
- log.io("Describe package at $url.");
- return httpClient.read(url, headers: PUB_API_HEADERS).then((version) {
- version = JSON.decode(version);
-
- // TODO(rnystrom): After this is pulled down, we could place it in
- // a secondary cache of just pubspecs. This would let us have a
- // persistent cache for pubspecs for packages that haven't actually
- // been downloaded.
- return new Pubspec.fromMap(
- version['pubspec'],
- systemCache.sources,
- expectedName: id.name,
- location: url);
- }).catchError((ex, stackTrace) {
- var parsed = _parseDescription(id.description);
- _throwFriendlyError(ex, stackTrace, id.name, parsed.last);
- });
- }
-
- /// Downloads the package identified by [id] to the system cache.
- Future<Package> downloadToSystemCache(PackageId id) {
- return isInSystemCache(id).then((inCache) {
- // Already cached so don't download it.
- if (inCache) return true;
-
- var packageDir = _getDirectory(id);
- ensureDir(path.dirname(packageDir));
- var parsed = _parseDescription(id.description);
- return _download(parsed.last, parsed.first, id.version, packageDir);
- }).then((found) {
- if (!found) fail('Package $id not found.');
- return new Package.load(id.name, _getDirectory(id), systemCache.sources);
- });
- }
-
- /// The system cache directory for the hosted source contains subdirectories
- /// for each separate repository URL that's used on the system.
- ///
- /// Each of these subdirectories then contains a subdirectory for each
- /// package downloaded from that site.
- Future<String> getDirectory(PackageId id) =>
- new Future.value(_getDirectory(id));
-
- String _getDirectory(PackageId id) {
- var parsed = _parseDescription(id.description);
- var dir = _urlToDirectory(parsed.last);
- return path.join(systemCacheRoot, dir, "${parsed.first}-${id.version}");
- }
-
- String packageName(description) => _parseDescription(description).first;
-
- bool descriptionsEqual(description1, description2) =>
- _parseDescription(description1) == _parseDescription(description2);
-
- /// Ensures that [description] is a valid hosted package description.
- ///
- /// There are two valid formats. A plain string refers to a package with the
- /// given name from the default host, while a map with keys "name" and "url"
- /// refers to a package with the given name from the host at the given URL.
- dynamic parseDescription(String containingPath, description,
- {bool fromLockFile: false}) {
- _parseDescription(description);
- return description;
- }
-
- /// Re-downloads all packages that have been previously downloaded into the
- /// system cache from any server.
- Future<Pair<int, int>> repairCachedPackages() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- join0() {
- var successes = 0;
- var failures = 0;
- var it0 = listDir(systemCacheRoot).iterator;
- break0() {
- completer0.complete(new Pair(successes, failures));
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var serverDir = it0.current;
- var url = _directoryToUrl(path.basename(serverDir));
- var packages =
- _getCachedPackagesInDirectory(path.basename(serverDir));
- packages.sort(Package.orderByNameAndVersion);
- var it1 = packages.iterator;
- break1() {
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- var trampoline1;
- continue1() {
- trampoline1 = null;
- if (it1.moveNext()) {
- var package = it1.current;
- join1() {
- trampoline1 = continue1;
- do trampoline1(); while (trampoline1 != null);
- }
- catch0(error, stackTrace) {
- try {
- failures++;
- var message =
- "Failed to repair ${log.bold(package.name)} " "${package.version}";
- join2() {
- log.error("${message}. Error:\n${error}");
- log.fine(stackTrace);
- tryDeleteEntry(package.dir);
- join1();
- }
- if (url != defaultUrl) {
- message += " from ${url}";
- join2();
- } else {
- join2();
- }
- } catch (error, stackTrace) {
- completer0.completeError(error, stackTrace);
- }
- }
- try {
- new Future.value(
- _download(url, package.name, package.version, package.dir)).then((x0) {
- trampoline1 = () {
- trampoline1 = null;
- try {
- x0;
- successes++;
- join1();
- } catch (e0, s0) {
- catch0(e0, s0);
- }
- };
- do trampoline1(); while (trampoline1 != null);
- }, onError: catch0);
- } catch (e1, s1) {
- catch0(e1, s1);
- }
- } else {
- break1();
- }
- }
- trampoline1 = continue1;
- do trampoline1(); while (trampoline1 != null);
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- if (!dirExists(systemCacheRoot)) {
- completer0.complete(new Pair(0, 0));
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Gets all of the packages that have been downloaded into the system cache
- /// from the default server.
- List<Package> getCachedPackages() {
- return _getCachedPackagesInDirectory(_urlToDirectory(defaultUrl));
- }
-
- /// Gets all of the packages that have been downloaded into the system cache
- /// into [dir].
- List<Package> _getCachedPackagesInDirectory(String dir) {
- var cacheDir = path.join(systemCacheRoot, dir);
- if (!dirExists(cacheDir)) return [];
-
- return listDir(
- cacheDir).map(
- (entry) => new Package.load(null, entry, systemCache.sources)).toList();
- }
-
- /// Downloads package [package] at [version] from [server], and unpacks it
- /// into [destPath].
- Future<bool> _download(String server, String package, Version version,
- String destPath) {
- return new Future.sync(() {
- var url = Uri.parse("$server/packages/$package/versions/$version.tar.gz");
- log.io("Get package from $url.");
- log.message('Downloading ${log.bold(package)} ${version}...');
-
- // Download and extract the archive to a temp directory.
- var tempDir = systemCache.createTempDir();
- return httpClient.send(
- new http.Request(
- "GET",
- url)).then((response) => response.stream).then((stream) {
- return timeout(
- extractTarGz(stream, tempDir),
- HTTP_TIMEOUT,
- url,
- 'downloading $url');
- }).then((_) {
- // Remove the existing directory if it exists. This will happen if
- // we're forcing a download to repair the cache.
- if (dirExists(destPath)) deleteEntry(destPath);
-
- // Now that the get has succeeded, move it to the real location in the
- // cache. This ensures that we don't leave half-busted ghost
- // directories in the user's pub cache if a get fails.
- renameDir(tempDir, destPath);
- return true;
- });
- });
- }
-
- /// When an error occurs trying to read something about [package] from [url],
- /// this tries to translate into a more user friendly error message.
- ///
- /// Always throws an error, either the original one or a better one.
- void _throwFriendlyError(error, StackTrace stackTrace, String package,
- String url) {
- if (error is PubHttpException && error.response.statusCode == 404) {
- throw new PackageNotFoundException(
- "Could not find package $package at $url.",
- error,
- stackTrace);
- }
-
- if (error is TimeoutException) {
- fail(
- "Timed out trying to find package $package at $url.",
- error,
- stackTrace);
- }
-
- if (error is io.SocketException) {
- fail(
- "Got socket error trying to find package $package at $url.",
- error,
- stackTrace);
- }
-
- // Otherwise re-throw the original exception.
- throw error;
- }
-}
-
-/// This is the modified hosted source used when pub get or upgrade are run
-/// with "--offline".
-///
-/// This uses the system cache to get the list of available packages and does
-/// no network access.
-class OfflineHostedSource extends HostedSource {
- /// Gets the list of all versions of [name] that are in the system cache.
- Future<List<Version>> getVersions(String name, description) {
- return newFuture(() {
- var parsed = _parseDescription(description);
- var server = parsed.last;
- log.io(
- "Finding versions of $name in " "$systemCacheRoot/${_urlToDirectory(server)}");
- return _getCachedPackagesInDirectory(
- _urlToDirectory(
- server)).where(
- (package) => package.name == name).map((package) => package.version).toList();
- }).then((versions) {
- // If there are no versions in the cache, report a clearer error.
- if (versions.isEmpty) fail("Could not find package $name in cache.");
-
- return versions;
- });
- }
-
- Future<bool> _download(String server, String package, Version version,
- String destPath) {
- // Since HostedSource is cached, this will only be called for uncached
- // packages.
- throw new UnsupportedError("Cannot download packages when offline.");
- }
-
- Future<Pubspec> doDescribeUncached(PackageId id) {
- // [getVersions()] will only return packages that are already cached.
- // [CachedSource] will only call [doDescribeUncached()] on a package after
- // it has failed to find it in the cache, so this code should not be
- // reached.
- throw new UnsupportedError("Cannot describe packages when offline.");
- }
-}
-
-/// Given a URL, returns a "normalized" string to be used as a directory name
-/// for packages downloaded from the server at that URL.
-///
-/// This normalization strips off the scheme (which is presumed to be HTTP or
-/// HTTPS) and *sort of* URL-encodes it. I say "sort of" because it does it
-/// incorrectly: it uses the character's *decimal* ASCII value instead of hex.
-///
-/// This could cause an ambiguity since some characters get encoded as three
-/// digits and others two. It's possible for one to be a prefix of the other.
-/// In practice, the set of characters that are encoded don't happen to have
-/// any collisions, so the encoding is reversible.
-///
-/// This behavior is a bug, but is being preserved for compatibility.
-String _urlToDirectory(String url) {
- // Normalize all loopback URLs to "localhost".
- url = url.replaceAllMapped(
- new RegExp(r"^https?://(127\.0\.0\.1|\[::1\])?"),
- (match) => match[1] == null ? '' : 'localhost');
- return replace(
- url,
- new RegExp(r'[<>:"\\/|?*%]'),
- (match) => '%${match[0].codeUnitAt(0)}');
-}
-
-/// Given a directory name in the system cache, returns the URL of the server
-/// whose packages it contains.
-///
-/// See [_urlToDirectory] for details on the mapping. Note that because the
-/// directory name does not preserve the scheme, this has to guess at it. It
-/// chooses "http" for loopback URLs (mainly to support the pub tests) and
-/// "https" for all others.
-String _directoryToUrl(String url) {
- // Decode the pseudo-URL-encoded characters.
- var chars = '<>:"\\/|?*%';
- for (var i = 0; i < chars.length; i++) {
- var c = chars.substring(i, i + 1);
- url = url.replaceAll("%${c.codeUnitAt(0)}", c);
- }
-
- // Figure out the scheme.
- var scheme = "https";
-
- // See if it's a loopback IP address.
- if (isLoopback(url.replaceAll(new RegExp(":.*"), ""))) scheme = "http";
- return "$scheme://$url";
-}
-
-/// Parses [description] into its server and package name components, then
-/// converts that to a Uri given [pattern].
-///
-/// Ensures the package name is properly URL encoded.
-Uri _makeUrl(description, String pattern(String server, String package)) {
- var parsed = _parseDescription(description);
- var server = parsed.last;
- var package = Uri.encodeComponent(parsed.first);
- return Uri.parse(pattern(server, package));
-}
-
-/// Parses [id] into its server, package name, and version components, then
-/// converts that to a Uri given [pattern].
-///
-/// Ensures the package name is properly URL encoded.
-Uri _makeVersionUrl(PackageId id, String pattern(String server, String package,
- String version)) {
- var parsed = _parseDescription(id.description);
- var server = parsed.last;
- var package = Uri.encodeComponent(parsed.first);
- var version = Uri.encodeComponent(id.version.toString());
- return Uri.parse(pattern(server, package, version));
-}
-
-/// Parses the description for a package.
-///
-/// If the package parses correctly, this returns a (name, url) pair. If not,
-/// this throws a descriptive FormatException.
-Pair<String, String> _parseDescription(description) {
- if (description is String) {
- return new Pair<String, String>(description, HostedSource.defaultUrl);
- }
-
- if (description is! Map) {
- throw new FormatException("The description must be a package name or map.");
- }
-
- if (!description.containsKey("name")) {
- throw new FormatException("The description map must contain a 'name' key.");
- }
-
- var name = description["name"];
- if (name is! String) {
- throw new FormatException("The 'name' key must have a string value.");
- }
-
- var url = description["url"];
- if (url == null) url = HostedSource.defaultUrl;
-
- return new Pair<String, String>(name, url);
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/path.dart b/sdk/lib/_internal/pub_generated/lib/src/source/path.dart
deleted file mode 100644
index d6f7b8c..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/source/path.dart
+++ /dev/null
@@ -1,162 +0,0 @@
-// Copyright (c) 2013, 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 pub.source.path;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as p;
-
-import '../exceptions.dart';
-import '../io.dart';
-import '../package.dart';
-import '../pubspec.dart';
-import '../source.dart';
-import '../utils.dart';
-
-/// A package [Source] that gets packages from a given local file path.
-class PathSource extends Source {
- /// Returns a valid description for a reference to a package at [path].
- static describePath(String path) {
- return {
- "path": path,
- "relative": p.isRelative(path)
- };
- }
-
- /// Given a valid path reference description, returns the file path it
- /// describes.
- ///
- /// This returned path may be relative or absolute and it is up to the caller
- /// to know how to interpret a relative path.
- static String pathFromDescription(description) => description["path"];
-
- final name = 'path';
-
- Future<Pubspec> doDescribe(PackageId id) {
- return new Future.sync(() {
- var dir = _validatePath(id.name, id.description);
- return new Pubspec.load(dir, systemCache.sources, expectedName: id.name);
- });
- }
-
- bool descriptionsEqual(description1, description2) {
- // Compare real paths after normalizing and resolving symlinks.
- var path1 = canonicalize(description1["path"]);
- var path2 = canonicalize(description2["path"]);
- return path1 == path2;
- }
-
- Future get(PackageId id, String symlink) {
- return new Future.sync(() {
- var dir = _validatePath(id.name, id.description);
- createPackageSymlink(
- id.name,
- dir,
- symlink,
- relative: id.description["relative"]);
- });
- }
-
- Future<String> getDirectory(PackageId id) =>
- newFuture(() => _validatePath(id.name, id.description));
-
- /// Parses a path dependency.
- ///
- /// This takes in a path string and returns a map. The "path" key will be the
- /// original path but resolved relative to the containing path. The
- /// "relative" key will be `true` if the original path was relative.
- ///
- /// A path coming from a pubspec is a simple string. From a lock file, it's
- /// an expanded {"path": ..., "relative": ...} map.
- dynamic parseDescription(String containingPath, description,
- {bool fromLockFile: false}) {
- if (fromLockFile) {
- if (description is! Map) {
- throw new FormatException("The description must be a map.");
- }
-
- if (description["path"] is! String) {
- throw new FormatException(
- "The 'path' field of the description must " "be a string.");
- }
-
- if (description["relative"] is! bool) {
- throw new FormatException(
- "The 'relative' field of the description " "must be a boolean.");
- }
-
- return description;
- }
-
- if (description is! String) {
- throw new FormatException("The description must be a path string.");
- }
-
- // Resolve the path relative to the containing file path, and remember
- // whether the original path was relative or absolute.
- var isRelative = p.isRelative(description);
- if (isRelative) {
- // Relative paths coming from pubspecs that are not on the local file
- // system aren't allowed. This can happen if a hosted or git dependency
- // has a path dependency.
- if (containingPath == null) {
- throw new FormatException(
- '"$description" is a relative path, but this ' 'isn\'t a local pubspec.');
- }
-
- description = p.normalize(p.join(p.dirname(containingPath), description));
- }
-
- return {
- "path": description,
- "relative": isRelative
- };
- }
-
- /// Serializes path dependency's [description].
- ///
- /// For the descriptions where `relative` attribute is `true`, tries to make
- /// `path` relative to the specified [containingPath].
- dynamic serializeDescription(String containingPath, description) {
- if (description["relative"]) {
- return {
- "path": p.relative(description['path'], from: containingPath),
- "relative": true
- };
- }
- return description;
- }
-
- /// Converts a parsed relative path to its original relative form.
- String formatDescription(String containingPath, description) {
- var sourcePath = description["path"];
- if (description["relative"]) {
- sourcePath = p.relative(description['path'], from: containingPath);
- }
-
- return sourcePath;
- }
-
- /// Ensures that [description] is a valid path description and returns a
- /// normalized path to the package.
- ///
- /// It must be a map, with a "path" key containing a path that points to an
- /// existing directory. Throws an [ApplicationException] if the path is
- /// invalid.
- String _validatePath(String name, description) {
- var dir = description["path"];
-
- if (dirExists(dir)) return dir;
-
- if (fileExists(dir)) {
- fail(
- 'Path dependency for package $name must refer to a directory, '
- 'not a file. Was "$dir".');
- }
-
- throw new PackageNotFoundException(
- 'Could not find package $name at "$dir".');
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/unknown.dart b/sdk/lib/_internal/pub_generated/lib/src/source/unknown.dart
deleted file mode 100644
index a3049cb..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/source/unknown.dart
+++ /dev/null
@@ -1,48 +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.
-
-library pub.source.unknown;
-
-import 'dart:async';
-
-import '../package.dart';
-import '../pubspec.dart';
-import '../source.dart';
-
-/// A [Null Object] that represents a source not recognized by pub.
-///
-/// It provides some default behavior so that pub can work with sources it
-/// doesn't recognize.
-///
-/// [null object]: http://en.wikipedia.org/wiki/Null_Object_pattern
-class UnknownSource extends Source {
- final String name;
-
- UnknownSource(this.name);
-
- /// Two unknown sources are the same if their names are the same.
- bool operator ==(other) => other is UnknownSource && other.name == name;
-
- int get hashCode => name.hashCode;
-
- Future<Pubspec> doDescribe(PackageId id) =>
- throw new UnsupportedError(
- "Cannot describe a package from unknown source '$name'.");
-
- Future get(PackageId id, String symlink) =>
- throw new UnsupportedError("Cannot get an unknown source '$name'.");
-
- /// Returns the directory where this package can be found locally.
- Future<String> getDirectory(PackageId id) =>
- throw new UnsupportedError(
- "Cannot find a package from an unknown source '$name'.");
-
- bool descriptionsEqual(description1, description2) =>
- description1 == description2;
-
- /// Unknown sources do no validation.
- dynamic parseDescription(String containingPath, description,
- {bool fromLockFile: false}) =>
- description;
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/source_registry.dart b/sdk/lib/_internal/pub_generated/lib/src/source_registry.dart
deleted file mode 100644
index fc5b4f3..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/source_registry.dart
+++ /dev/null
@@ -1,81 +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 pub.source_registry;
-
-import 'dart:collection';
-
-import 'package.dart';
-import 'source.dart';
-import 'source/unknown.dart';
-
-/// A class that keeps track of [Source]s used for getting packages.
-class SourceRegistry extends IterableBase<Source> {
- final _sources = new Map<String, Source>();
- Source _default;
-
- /// Returns the default source, which is used when no source is specified.
- Source get defaultSource => _default;
-
- /// Iterates over the registered sources in name order.
- Iterator<Source> get iterator {
- var sources = _sources.values.toList();
- sources.sort((a, b) => a.name.compareTo(b.name));
- return sources.iterator;
- }
-
- /// Returns whether [id1] and [id2] refer to the same package, including
- /// validating that their descriptions are equivalent.
- bool idsEqual(PackageId id1, PackageId id2) {
- if (id1 != id2) return false;
- if (id1 == null && id2 == null) return true;
- return idDescriptionsEqual(id1, id2);
- }
-
- /// Returns whether [id1] and [id2] have the same source and description.
- ///
- /// This doesn't check whether the name or versions are equal.
- bool idDescriptionsEqual(PackageId id1, PackageId id2) {
- if (id1.source != id2.source) return false;
- return this[id1.source].descriptionsEqual(id1.description, id2.description);
- }
-
- /// Sets the default source.
- ///
- /// This takes a string, which must be the name of a registered source.
- void setDefault(String name) {
- if (!_sources.containsKey(name)) {
- throw new StateError('Default source $name is not in the registry');
- }
-
- _default = _sources[name];
- }
-
- /// Registers a new source.
- ///
- /// This source may not have the same name as a source that's already been
- /// registered.
- void register(Source source) {
- if (_sources.containsKey(source.name)) {
- throw new StateError(
- 'Source registry already has a source named ' '${source.name}');
- }
-
- _sources[source.name] = source;
- }
-
- /// Returns the source named [name].
- ///
- /// Returns an [UnknownSource] if no source with that name has been
- /// registered. If [name] is null, returns the default source.
- Source operator [](String name) {
- if (name == null) {
- if (defaultSource != null) return defaultSource;
- throw new StateError('No default source has been registered');
- }
-
- if (_sources.containsKey(name)) return _sources[name];
- return new UnknownSource(name);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/system_cache.dart b/sdk/lib/_internal/pub_generated/lib/src/system_cache.dart
deleted file mode 100644
index 424585da..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/system_cache.dart
+++ /dev/null
@@ -1,108 +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 pub.system_cache;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-
-import 'io.dart';
-import 'io.dart' as io show createTempDir;
-import 'log.dart' as log;
-import 'package.dart';
-import 'source/cached.dart';
-import 'source/git.dart';
-import 'source/hosted.dart';
-import 'source/path.dart';
-import 'source.dart';
-import 'source_registry.dart';
-
-/// The system-wide cache of downloaded packages.
-///
-/// This cache contains all packages that are downloaded from the internet.
-/// Packages that are available locally (e.g. path dependencies) don't use this
-/// cache.
-class SystemCache {
- /// The root directory where this package cache is located.
- final String rootDir;
-
- String get tempDir => path.join(rootDir, '_temp');
-
- /// The sources from which to get packages.
- final sources = new SourceRegistry();
-
- static String defaultDir = (() {
- if (Platform.environment.containsKey('PUB_CACHE')) {
- return Platform.environment['PUB_CACHE'];
- } else if (Platform.operatingSystem == 'windows') {
- var appData = Platform.environment['APPDATA'];
- return path.join(appData, 'Pub', 'Cache');
- } else {
- return '${Platform.environment['HOME']}/.pub-cache';
- }
- })();
-
- /// Creates a new package cache which is backed by the given directory on the
- /// user's file system.
- SystemCache([String rootDir])
- : rootDir = rootDir == null ? SystemCache.defaultDir : rootDir;
-
- /// Creates a system cache and registers the standard set of sources.
- ///
- /// If [isOffline] is `true`, then the offline hosted source will be used.
- /// Defaults to `false`.
- factory SystemCache.withSources({String rootDir, bool isOffline: false}) {
- var cache = new SystemCache(rootDir);
- cache.register(new GitSource());
-
- if (isOffline) {
- cache.register(new OfflineHostedSource());
- } else {
- cache.register(new HostedSource());
- }
-
- cache.register(new PathSource());
- cache.sources.setDefault('hosted');
- return cache;
- }
-
- /// Registers a new source.
- ///
- /// This source must not have the same name as a source that's already been
- /// registered.
- void register(Source source) {
- source.bind(this);
- sources.register(source);
- }
-
- /// Determines if the system cache contains the package identified by [id].
- Future<bool> contains(PackageId id) {
- var source = sources[id.source];
-
- if (source is! CachedSource) {
- throw new ArgumentError("Package $id is not cacheable.");
- }
-
- return source.isInSystemCache(id);
- }
-
- /// Create a new temporary directory within the system cache.
- ///
- /// The system cache maintains its own temporary directory that it uses to
- /// stage packages into while downloading. It uses this instead of the OS's
- /// system temp directory to ensure that it's on the same volume as the pub
- /// system cache so that it can move the directory from it.
- String createTempDir() {
- var temp = ensureDir(tempDir);
- return io.createTempDir(temp, 'dir');
- }
-
- /// Deletes the system cache's internal temp directory.
- void deleteTempDir() {
- log.fine('Clean up system cache temp directory $tempDir.');
- if (dirExists(tempDir)) deleteEntry(tempDir);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/transcript.dart b/sdk/lib/_internal/pub_generated/lib/src/transcript.dart
deleted file mode 100644
index a2778c0..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/transcript.dart
+++ /dev/null
@@ -1,73 +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 pub.transcript;
-
-import 'dart:collection';
-
-/// A rolling transcript of entries of type [T].
-///
-/// It has a maximum number of entries. If entries are added that exceed that
-/// it discards entries from the *middle* of the transcript. Generally, in logs,
-/// the first and last entries are the most important, so it maintains those.
-class Transcript<T> {
- /// The maximum number of transcript entries.
- final int max;
-
- /// The number of entries that were discarded after reaching [max].
- int get discarded => _discarded;
- int _discarded = 0;
-
- /// The earliest half of the entries.
- ///
- /// This will be empty until the maximum number of entries is hit at which
- /// point the oldest half of the entries will be moved from [_newest] to
- /// here.
- final _oldest = new List<T>();
-
- /// The most recent half of the entries.
- final _newest = new Queue<T>();
-
- /// Creates a new [Transcript] that can hold up to [max] entries.
- Transcript(this.max);
-
- /// Adds [entry] to the transcript.
- ///
- /// If the transcript already has the maximum number of entries, discards one
- /// from the middle.
- void add(T entry) {
- if (discarded > 0) {
- // We're already in "rolling" mode.
- _newest.removeFirst();
- _discarded++;
- } else if (_newest.length == max) {
- // We are crossing the threshold where we have to discard items. Copy
- // the first half over to the oldest list.
- while (_newest.length > max ~/ 2) {
- _oldest.add(_newest.removeFirst());
- }
-
- // Discard the middle item.
- _newest.removeFirst();
- _discarded++;
- }
-
- _newest.add(entry);
- }
-
- /// Traverses the entries in the transcript from oldest to newest.
- ///
- /// Invokes [onEntry] for each item. When it reaches the point in the middle
- /// where excess entries where dropped, invokes [onGap] with the number of
- /// dropped entries. If no more than [max] entries were added, does not
- /// invoke [onGap].
- void forEach(void onEntry(T entry), [void onGap(int)]) {
- if (_oldest.isNotEmpty) {
- _oldest.forEach(onEntry);
- if (onGap != null) onGap(discarded);
- }
-
- _newest.forEach(onEntry);
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/utils.dart b/sdk/lib/_internal/pub_generated/lib/src/utils.dart
deleted file mode 100644
index d03db2a..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/utils.dart
+++ /dev/null
@@ -1,924 +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.
-
-/// Generic utility functions. Stuff that should possibly be in core.
-library pub.utils;
-
-import 'dart:async';
-import "dart:convert";
-import 'dart:io';
-
-// This is used by [libraryPath]. It must be kept up-to-date with all libraries
-// whose paths are looked up using that function.
-@MirrorsUsed(targets: const ['pub.io', 'test_pub'])
-import 'dart:mirrors';
-
-import "package:crypto/crypto.dart";
-import 'package:path/path.dart' as path;
-import "package:stack_trace/stack_trace.dart";
-
-import 'exceptions.dart';
-import 'log.dart' as log;
-
-export '../../asset/dart/utils.dart';
-
-/// A pair of values.
-class Pair<E, F> {
- E first;
- F last;
-
- Pair(this.first, this.last);
-
- String toString() => '($first, $last)';
-
- bool operator ==(other) {
- if (other is! Pair) return false;
- return other.first == first && other.last == last;
- }
-
- int get hashCode => first.hashCode ^ last.hashCode;
-}
-
-/// A completer that waits until all added [Future]s complete.
-// TODO(rnystrom): Copied from web_components. Remove from here when it gets
-// added to dart:core. (See #6626.)
-class FutureGroup<T> {
- int _pending = 0;
- Completer<List<T>> _completer = new Completer<List<T>>();
- final List<Future<T>> futures = <Future<T>>[];
- bool completed = false;
-
- final List<T> _values = <T>[];
-
- /// Wait for [task] to complete.
- Future<T> add(Future<T> task) {
- if (completed) {
- throw new StateError("The FutureGroup has already completed.");
- }
-
- _pending++;
- futures.add(task.then((value) {
- if (completed) return;
-
- _pending--;
- _values.add(value);
-
- if (_pending <= 0) {
- completed = true;
- _completer.complete(_values);
- }
- }).catchError((e, stackTrace) {
- if (completed) return;
-
- completed = true;
- _completer.completeError(e, stackTrace);
- }));
-
- return task;
- }
-
- Future<List> get future => _completer.future;
-}
-
-/// Like [new Future], but avoids around issue 11911 by using [new Future.value]
-/// under the covers.
-Future newFuture(callback()) => new Future.value().then((_) => callback());
-
-/// Runs [callback] in an error zone and pipes any unhandled error to the
-/// returned [Future].
-///
-/// If the returned [Future] produces an error, its stack trace will always be a
-/// [Chain]. By default, this chain will contain only the local stack trace, but
-/// if [captureStackChains] is passed, it will contain the full stack chain for
-/// the error.
-Future captureErrors(Future callback(), {bool captureStackChains: false}) {
- var completer = new Completer();
- var wrappedCallback = () {
- new Future.sync(
- callback).then(completer.complete).catchError((e, stackTrace) {
- // [stackTrace] can be null if we're running without [captureStackChains],
- // since dart:io will often throw errors without stack traces.
- if (stackTrace != null) {
- stackTrace = new Chain.forTrace(stackTrace);
- } else {
- stackTrace = new Chain([]);
- }
- if (!completer.isCompleted) completer.completeError(e, stackTrace);
- });
- };
-
- if (captureStackChains) {
- Chain.capture(wrappedCallback, onError: (error, stackTrace) {
- if (!completer.isCompleted) completer.completeError(error, stackTrace);
- });
- } else {
- runZoned(wrappedCallback, onError: (e, stackTrace) {
- if (stackTrace == null) {
- stackTrace = new Chain.current();
- } else {
- stackTrace = new Chain([new Trace.from(stackTrace)]);
- }
- if (!completer.isCompleted) completer.completeError(e, stackTrace);
- });
- }
-
- return completer.future;
-}
-
-/// Like [Future.wait], but prints all errors from the futures as they occur and
-/// only returns once all Futures have completed, successfully or not.
-///
-/// This will wrap the first error thrown in a [SilentException] and rethrow it.
-Future waitAndPrintErrors(Iterable<Future> futures) {
- return Future.wait(futures.map((future) {
- return future.catchError((error, stackTrace) {
- log.exception(error, stackTrace);
- throw error;
- });
- })).catchError((error, stackTrace) {
- throw new SilentException(error, stackTrace);
- });
-}
-
-/// Returns a [StreamTransformer] that will call [onDone] when the stream
-/// completes.
-///
-/// The stream will be passed through unchanged.
-StreamTransformer onDoneTransformer(void onDone()) {
- return new StreamTransformer.fromHandlers(handleDone: (sink) {
- onDone();
- sink.close();
- });
-}
-
-// TODO(rnystrom): Move into String?
-/// Pads [source] to [length] by adding spaces at the end.
-String padRight(String source, int length) {
- final result = new StringBuffer();
- result.write(source);
-
- while (result.length < length) {
- result.write(' ');
- }
-
- return result.toString();
-}
-
-/// Pads [source] to [length] by adding [char]s at the beginning.
-///
-/// If [char] is `null`, it defaults to a space.
-String padLeft(String source, int length, [String char]) {
- if (char == null) char = ' ';
- if (source.length >= length) return source;
-
- return char * (length - source.length) + source;
-}
-
-/// Returns a labelled sentence fragment starting with [name] listing the
-/// elements [iter].
-///
-/// If [iter] does not have one item, name will be pluralized by adding "s" or
-/// using [plural], if given.
-String namedSequence(String name, Iterable iter, [String plural]) {
- if (iter.length == 1) return "$name ${iter.single}";
-
- if (plural == null) plural = "${name}s";
- return "$plural ${toSentence(iter)}";
-}
-
-/// Returns a sentence fragment listing the elements of [iter].
-///
-/// This converts each element of [iter] to a string and separates them with
-/// commas and/or "and" where appropriate.
-String toSentence(Iterable iter) {
- if (iter.length == 1) return iter.first.toString();
- return iter.take(iter.length - 1).join(", ") + " and ${iter.last}";
-}
-
-/// Returns [name] if [number] is 1, or the plural of [name] otherwise.
-///
-/// By default, this just adds "s" to the end of [name] to get the plural. If
-/// [plural] is passed, that's used instead.
-String pluralize(String name, int number, {String plural}) {
- if (number == 1) return name;
- if (plural != null) return plural;
- return '${name}s';
-}
-
-/// Escapes any regex metacharacters in [string] so that using as a [RegExp]
-/// pattern will match the string literally.
-// TODO(rnystrom): Remove when #4706 is fixed.
-String quoteRegExp(String string) {
- // Note: make sure "\" is done first so that we don't escape the other
- // escaped characters. We could do all of the replaces at once with a regexp
- // but string literal for regex that matches all regex metacharacters would
- // be a bit hard to read.
- for (var metacharacter in r"\^$.*+?()[]{}|".split("")) {
- string = string.replaceAll(metacharacter, "\\$metacharacter");
- }
-
- return string;
-}
-
-/// Creates a URL string for [address]:[port].
-///
-/// Handles properly formatting IPv6 addresses.
-Uri baseUrlForAddress(InternetAddress address, int port) {
- if (address.isLoopback) {
- return new Uri(scheme: "http", host: "localhost", port: port);
- }
-
- // IPv6 addresses in URLs need to be enclosed in square brackets to avoid
- // URL ambiguity with the ":" in the address.
- if (address.type == InternetAddressType.IP_V6) {
- return new Uri(scheme: "http", host: "[${address.address}]", port: port);
- }
-
- return new Uri(scheme: "http", host: address.address, port: port);
-}
-
-/// Returns whether [host] is a host for a localhost or loopback URL.
-///
-/// Unlike [InternetAddress.isLoopback], this hostnames from URLs as well as
-/// from [InternetAddress]es, including "localhost".
-bool isLoopback(String host) {
- if (host == 'localhost') return true;
-
- // IPv6 hosts in URLs are surrounded by square brackets.
- if (host.startsWith("[") && host.endsWith("]")) {
- host = host.substring(1, host.length - 1);
- }
-
- try {
- return new InternetAddress(host).isLoopback;
- } on ArgumentError catch (_) {
- // The host isn't an IP address and isn't "localhost', so it's almost
- // certainly not a loopback host.
- return false;
- }
-}
-
-/// Flattens nested lists inside an iterable into a single list containing only
-/// non-list elements.
-List flatten(Iterable nested) {
- var result = [];
- helper(list) {
- for (var element in list) {
- if (element is List) {
- helper(element);
- } else {
- result.add(element);
- }
- }
- }
- helper(nested);
- return result;
-}
-
-/// Returns a set containing all elements in [minuend] that are not in
-/// [subtrahend].
-Set setMinus(Iterable minuend, Iterable subtrahend) {
- var minuendSet = new Set.from(minuend);
- minuendSet.removeAll(subtrahend);
- return minuendSet;
-}
-
-/// Returns whether there's any overlap between [set1] and [set2].
-bool overlaps(Set set1, Set set2) {
- // Iterate through the smaller set.
- var smaller = set1.length > set2.length ? set1 : set2;
- var larger = smaller == set1 ? set2 : set1;
- return smaller.any(larger.contains);
-}
-
-/// Returns a list containing the sorted elements of [iter].
-List ordered(Iterable<Comparable> iter) {
- var list = iter.toList();
- list.sort();
- return list;
-}
-
-/// Returns the element of [iter] for which [f] returns the minimum value.
-minBy(Iterable iter, Comparable f(element)) {
- var min = null;
- var minComparable = null;
- for (var element in iter) {
- var comparable = f(element);
- if (minComparable == null || comparable.compareTo(minComparable) < 0) {
- min = element;
- minComparable = comparable;
- }
- }
- return min;
-}
-
-/// Returns every pair of consecutive elements in [iter].
-///
-/// For example, if [iter] is `[1, 2, 3, 4]`, this will return `[(1, 2), (2, 3),
-/// (3, 4)]`.
-Iterable<Pair> pairs(Iterable iter) {
- var previous = iter.first;
- return iter.skip(1).map((element) {
- var oldPrevious = previous;
- previous = element;
- return new Pair(oldPrevious, element);
- });
-}
-
-/// Creates a new map from [map] with new keys and values.
-///
-/// The return values of [key] are used as the keys and the return values of
-/// [value] are used as the values for the new map.
-///
-/// [key] defaults to returning the original key and [value] defaults to
-/// returning the original value.
-Map mapMap(Map map, {key(key, value), value(key, value)}) {
- if (key == null) key = (key, _) => key;
- if (value == null) value = (_, value) => value;
-
- var result = {};
- map.forEach((mapKey, mapValue) {
- result[key(mapKey, mapValue)] = value(mapKey, mapValue);
- });
- return result;
-}
-
-/// Like [Map.fromIterable], but [key] and [value] may return [Future]s.
-Future<Map> mapFromIterableAsync(Iterable iter, {key(element), value(element)})
- {
- if (key == null) key = (element) => element;
- if (value == null) value = (element) => element;
-
- var map = new Map();
- return Future.wait(iter.map((element) {
- return Future.wait(
- [
- new Future.sync(() => key(element)),
- new Future.sync(() => value(element))]).then((results) {
- map[results[0]] = results[1];
- });
- })).then((_) => map);
-}
-
-/// Returns the transitive closure of [graph].
-///
-/// This assumes [graph] represents a graph with a vertex for each key and an
-/// edge betweek each key and the values for that key.
-Map<dynamic, Set> transitiveClosure(Map<dynamic, Iterable> graph) {
- // This uses the Floyd-Warshall algorithm
- // (https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm).
- var result = {};
- graph.forEach((vertex, edges) {
- result[vertex] = new Set.from(edges)..add(vertex);
- });
-
- for (var vertex1 in graph.keys) {
- for (var vertex2 in graph.keys) {
- for (var vertex3 in graph.keys) {
- if (result[vertex2].contains(vertex1) &&
- result[vertex1].contains(vertex3)) {
- result[vertex2].add(vertex3);
- }
- }
- }
- }
-
- return result;
-}
-
-/// Given a list of filenames, returns a set of patterns that can be used to
-/// filter for those filenames.
-///
-/// For a given path, that path ends with some string in the returned set if
-/// and only if that path's basename is in [files].
-Set<String> createFileFilter(Iterable<String> files) {
- return files.expand((file) {
- var result = ["/$file"];
- if (Platform.operatingSystem == 'windows') result.add("\\$file");
- return result;
- }).toSet();
-}
-
-/// Given a blacklist of directory names, returns a set of patterns that can
-/// be used to filter for those directory names.
-///
-/// For a given path, that path contains some string in the returned set if
-/// and only if one of that path's components is in [dirs].
-Set<String> createDirectoryFilter(Iterable<String> dirs) {
- return dirs.expand((dir) {
- var result = ["/$dir/"];
- if (Platform.operatingSystem == 'windows') {
- result
- ..add("/$dir\\")
- ..add("\\$dir/")
- ..add("\\$dir\\");
- }
- return result;
- }).toSet();
-}
-
-/// Returns the maximum value in [iter] by [compare].
-///
-/// [compare] defaults to [Comparable.compare].
-maxAll(Iterable iter, [int compare(element1, element2)]) {
- if (compare == null) compare = Comparable.compare;
- return iter.reduce(
- (max, element) => compare(element, max) > 0 ? element : max);
-}
-
-/// Returns the minimum value in [iter] by [compare].
-///
-/// [compare] defaults to [Comparable.compare].
-minAll(Iterable iter, [int compare(element1, element2)]) {
- if (compare == null) compare = Comparable.compare;
- return iter.reduce(
- (max, element) => compare(element, max) < 0 ? element : max);
-}
-
-/// Replace each instance of [matcher] in [source] with the return value of
-/// [fn].
-String replace(String source, Pattern matcher, String fn(Match)) {
- var buffer = new StringBuffer();
- var start = 0;
- for (var match in matcher.allMatches(source)) {
- buffer.write(source.substring(start, match.start));
- start = match.end;
- buffer.write(fn(match));
- }
- buffer.write(source.substring(start));
- return buffer.toString();
-}
-
-/// Returns whether or not [str] ends with [matcher].
-bool endsWithPattern(String str, Pattern matcher) {
- for (var match in matcher.allMatches(str)) {
- if (match.end == str.length) return true;
- }
- return false;
-}
-
-/// Returns the hex-encoded sha1 hash of [source].
-String sha1(String source) {
- var sha = new SHA1();
- sha.add(source.codeUnits);
- return CryptoUtils.bytesToHex(sha.close());
-}
-
-/// Configures [future] so that its result (success or exception) is passed on
-/// to [completer].
-void chainToCompleter(Future future, Completer completer) {
- future.then(completer.complete, onError: completer.completeError);
-}
-
-/// Ensures that [stream] can emit at least one value successfully (or close
-/// without any values).
-///
-/// For example, reading asynchronously from a non-existent file will return a
-/// stream that fails on the first chunk. In order to handle that more
-/// gracefully, you may want to check that the stream looks like it's working
-/// before you pipe the stream to something else.
-///
-/// This lets you do that. It returns a [Future] that completes to a [Stream]
-/// emitting the same values and errors as [stream], but only if at least one
-/// value can be read successfully. If an error occurs before any values are
-/// emitted, the returned Future completes to that error.
-Future<Stream> validateStream(Stream stream) {
- var completer = new Completer<Stream>();
- var controller = new StreamController(sync: true);
-
- StreamSubscription subscription;
- subscription = stream.listen((value) {
- // We got a value, so the stream is valid.
- if (!completer.isCompleted) completer.complete(controller.stream);
- controller.add(value);
- }, onError: (error, [stackTrace]) {
- // If the error came after values, it's OK.
- if (completer.isCompleted) {
- controller.addError(error, stackTrace);
- return;
- }
-
- // Otherwise, the error came first and the stream is invalid.
- completer.completeError(error, stackTrace);
-
- // We don't be returning the stream at all in this case, so unsubscribe
- // and swallow the error.
- subscription.cancel();
- }, onDone: () {
- // It closed with no errors, so the stream is valid.
- if (!completer.isCompleted) completer.complete(controller.stream);
- controller.close();
- });
-
- return completer.future;
-}
-
-// TODO(nweiz): remove this when issue 7964 is fixed.
-/// Returns a [Future] that will complete to the first element of [stream].
-///
-/// Unlike [Stream.first], this is safe to use with single-subscription streams.
-Future streamFirst(Stream stream) {
- var completer = new Completer();
- var subscription;
- subscription = stream.listen((value) {
- subscription.cancel();
- completer.complete(value);
- }, onError: (e, [stackTrace]) {
- completer.completeError(e, stackTrace);
- }, onDone: () {
- completer.completeError(new StateError("No elements"), new Chain.current());
- }, cancelOnError: true);
- return completer.future;
-}
-
-/// Returns a wrapped version of [stream] along with a [StreamSubscription] that
-/// can be used to control the wrapped stream.
-Pair<Stream, StreamSubscription> streamWithSubscription(Stream stream) {
- var controller = stream.isBroadcast ?
- new StreamController.broadcast(sync: true) :
- new StreamController(sync: true);
- var subscription = stream.listen(
- controller.add,
- onError: controller.addError,
- onDone: controller.close);
- return new Pair<Stream, StreamSubscription>(controller.stream, subscription);
-}
-
-// TODO(nweiz): remove this when issue 7787 is fixed.
-/// Creates two single-subscription [Stream]s that each emit all values and
-/// errors from [stream].
-///
-/// This is useful if [stream] is single-subscription but multiple subscribers
-/// are necessary.
-Pair<Stream, Stream> tee(Stream stream) {
- var controller1 = new StreamController(sync: true);
- var controller2 = new StreamController(sync: true);
- stream.listen((value) {
- controller1.add(value);
- controller2.add(value);
- }, onError: (error, [stackTrace]) {
- controller1.addError(error, stackTrace);
- controller2.addError(error, stackTrace);
- }, onDone: () {
- controller1.close();
- controller2.close();
- });
- return new Pair<Stream, Stream>(controller1.stream, controller2.stream);
-}
-
-/// Merges [stream1] and [stream2] into a single stream that emits events from
-/// both sources.
-Stream mergeStreams(Stream stream1, Stream stream2) {
- var doneCount = 0;
- var controller = new StreamController(sync: true);
-
- for (var stream in [stream1, stream2]) {
- stream.listen(controller.add, onError: controller.addError, onDone: () {
- doneCount++;
- if (doneCount == 2) controller.close();
- });
- }
-
- return controller.stream;
-}
-
-/// A regular expression matching a trailing CR character.
-final _trailingCR = new RegExp(r"\r$");
-
-// TODO(nweiz): Use `text.split(new RegExp("\r\n?|\n\r?"))` when issue 9360 is
-// fixed.
-/// Splits [text] on its line breaks in a Windows-line-break-friendly way.
-List<String> splitLines(String text) =>
- text.split("\n").map((line) => line.replaceFirst(_trailingCR, "")).toList();
-
-/// Converts a stream of arbitrarily chunked strings into a line-by-line stream.
-///
-/// The lines don't include line termination characters. A single trailing
-/// newline is ignored.
-Stream<String> streamToLines(Stream<String> stream) {
- var buffer = new StringBuffer();
- return stream.transform(
- new StreamTransformer.fromHandlers(handleData: (chunk, sink) {
- var lines = splitLines(chunk);
- var leftover = lines.removeLast();
- for (var line in lines) {
- if (!buffer.isEmpty) {
- buffer.write(line);
- line = buffer.toString();
- buffer = new StringBuffer();
- }
-
- sink.add(line);
- }
- buffer.write(leftover);
- }, handleDone: (sink) {
- if (!buffer.isEmpty) sink.add(buffer.toString());
- sink.close();
- }));
-}
-
-/// Like [Iterable.where], but allows [test] to return [Future]s and uses the
-/// results of those [Future]s as the test.
-Future<Iterable> futureWhere(Iterable iter, test(value)) {
- return Future.wait(iter.map((e) {
- var result = test(e);
- if (result is! Future) result = new Future.value(result);
- return result.then((result) => new Pair(e, result));
- })).then(
- (pairs) =>
- pairs.where(
- (pair) => pair.last)).then((pairs) => pairs.map((pair) => pair.first));
-}
-
-// TODO(nweiz): unify the following functions with the utility functions in
-// pkg/http.
-
-/// Like [String.split], but only splits on the first occurrence of the pattern.
-///
-/// This always returns an array of two elements or fewer.
-List<String> split1(String toSplit, String pattern) {
- if (toSplit.isEmpty) return <String>[];
-
- var index = toSplit.indexOf(pattern);
- if (index == -1) return [toSplit];
- return [
- toSplit.substring(0, index),
- toSplit.substring(index + pattern.length)];
-}
-
-/// Adds additional query parameters to [url], overwriting the original
-/// parameters if a name conflict occurs.
-Uri addQueryParameters(Uri url, Map<String, String> parameters) {
- var queryMap = queryToMap(url.query);
- queryMap.addAll(parameters);
- return url.resolve("?${mapToQuery(queryMap)}");
-}
-
-/// Convert a URL query string (or `application/x-www-form-urlencoded` body)
-/// into a [Map] from parameter names to values.
-Map<String, String> queryToMap(String queryList) {
- var map = {};
- for (var pair in queryList.split("&")) {
- var split = split1(pair, "=");
- if (split.isEmpty) continue;
- var key = urlDecode(split[0]);
- var value = split.length > 1 ? urlDecode(split[1]) : "";
- map[key] = value;
- }
- return map;
-}
-
-/// Convert a [Map] from parameter names to values to a URL query string.
-String mapToQuery(Map<String, String> map) {
- var pairs = <List<String>>[];
- map.forEach((key, value) {
- key = Uri.encodeQueryComponent(key);
- value =
- (value == null || value.isEmpty) ? null : Uri.encodeQueryComponent(value);
- pairs.add([key, value]);
- });
- return pairs.map((pair) {
- if (pair[1] == null) return pair[0];
- return "${pair[0]}=${pair[1]}";
- }).join("&");
-}
-
-/// Returns the union of all elements in each set in [sets].
-Set unionAll(Iterable<Set> sets) =>
- sets.fold(new Set(), (union, set) => union.union(set));
-
-// TODO(nweiz): remove this when issue 9068 has been fixed.
-/// Whether [uri1] and [uri2] are equal.
-///
-/// This consider HTTP URIs to default to port 80, and HTTPs URIs to default to
-/// port 443.
-bool urisEqual(Uri uri1, Uri uri2) =>
- canonicalizeUri(uri1) == canonicalizeUri(uri2);
-
-/// Return [uri] with redundant port information removed.
-Uri canonicalizeUri(Uri uri) {
- return uri;
-}
-
-/// Returns a human-friendly representation of [inputPath].
-///
-/// If [inputPath] isn't too distant from the current working directory, this
-/// will return the relative path to it. Otherwise, it will return the absolute
-/// path.
-String nicePath(String inputPath) {
- var relative = path.relative(inputPath);
- var split = path.split(relative);
- if (split.length > 1 && split[0] == '..' && split[1] == '..') {
- return path.absolute(inputPath);
- }
- return relative;
-}
-
-/// Returns a human-friendly representation of [duration].
-String niceDuration(Duration duration) {
- var result = duration.inMinutes > 0 ? "${duration.inMinutes}:" : "";
-
- var s = duration.inSeconds % 59;
- var ms = duration.inMilliseconds % 1000;
-
- // If we're using verbose logging, be more verbose but more accurate when
- // reporting timing information.
- if (log.verbosity.isLevelVisible(log.Level.FINE)) {
- ms = padLeft(ms.toString(), 3, '0');
- } else {
- ms ~/= 100;
- }
-
- return "$result$s.${ms}s";
-}
-
-/// Decodes a URL-encoded string.
-///
-/// Unlike [Uri.decodeComponent], this includes replacing `+` with ` `.
-String urlDecode(String encoded) =>
- Uri.decodeComponent(encoded.replaceAll("+", " "));
-
-/// Takes a simple data structure (composed of [Map]s, [Iterable]s, scalar
-/// objects, and [Future]s) and recursively resolves all the [Future]s contained
-/// within.
-///
-/// Completes with the fully resolved structure.
-Future awaitObject(object) {
- // Unroll nested futures.
- if (object is Future) return object.then(awaitObject);
- if (object is Iterable) {
- return Future.wait(object.map(awaitObject).toList());
- }
- if (object is! Map) return new Future.value(object);
-
- var pairs = <Future<Pair>>[];
- object.forEach((key, value) {
- pairs.add(awaitObject(value).then((resolved) => new Pair(key, resolved)));
- });
- return Future.wait(pairs).then((resolvedPairs) {
- var map = {};
- for (var pair in resolvedPairs) {
- map[pair.first] = pair.last;
- }
- return map;
- });
-}
-
-/// Returns the path to the library named [libraryName].
-///
-/// The library name must be globally unique, or the wrong library path may be
-/// returned. Any libraries accessed must be added to the [MirrorsUsed]
-/// declaration in the import above.
-String libraryPath(String libraryName) {
- var lib = currentMirrorSystem().findLibrary(new Symbol(libraryName));
- return path.fromUri(lib.uri);
-}
-
-/// Whether "special" strings such as Unicode characters or color escapes are
-/// safe to use.
-///
-/// On Windows or when not printing to a terminal, only printable ASCII
-/// characters should be used.
-bool get canUseSpecialChars =>
- !runningAsTest &&
- Platform.operatingSystem != 'windows' &&
- stdioType(stdout) == StdioType.TERMINAL;
-
-/// Gets a "special" string (ANSI escape or Unicode).
-///
-/// On Windows or when not printing to a terminal, returns something else since
-/// those aren't supported.
-String getSpecial(String special, [String onWindows = '']) =>
- canUseSpecialChars ? special : onWindows;
-
-/// Prepends each line in [text] with [prefix].
-///
-/// If [firstPrefix] is passed, the first line is prefixed with that instead.
-String prefixLines(String text, {String prefix: '| ', String firstPrefix}) {
- var lines = text.split('\n');
- if (firstPrefix == null) {
- return lines.map((line) => '$prefix$line').join('\n');
- }
-
- var firstLine = "$firstPrefix${lines.first}";
- lines = lines.skip(1).map((line) => '$prefix$line').toList();
- lines.insert(0, firstLine);
- return lines.join('\n');
-}
-
-/// Whether pub is running as a subprocess in an integration test or in a unit
-/// test that has explicitly set this.
-bool runningAsTest = Platform.environment.containsKey('_PUB_TESTING');
-
-/// Whether today is April Fools' day.
-bool get isAprilFools {
- // Tests should never see April Fools' output.
- if (runningAsTest) return false;
-
- var date = new DateTime.now();
- return date.month == 4 && date.day == 1;
-}
-
-/// Wraps [fn] to guard against several different kinds of stack overflow
-/// exceptions:
-///
-/// * A sufficiently long [Future] chain can cause a stack overflow if there are
-/// no asynchronous operations in it (issue 9583).
-/// * A recursive function that recurses too deeply without an asynchronous
-/// operation can cause a stack overflow.
-/// * Even if the former is guarded against by adding asynchronous operations,
-/// returning a value through the [Future] chain can still cause a stack
-/// overflow.
-Future resetStack(fn()) {
- // Using a [Completer] breaks the [Future] chain for the return value and
- // avoids the third case described above.
- var completer = new Completer();
-
- // Using [new Future] adds an asynchronous operation that works around the
- // first and second cases described above.
- newFuture(fn).then((val) {
- scheduleMicrotask(() => completer.complete(val));
- }).catchError((err, stackTrace) {
- scheduleMicrotask(() => completer.completeError(err, stackTrace));
- });
- return completer.future;
-}
-
-/// The subset of strings that don't need quoting in YAML.
-///
-/// This pattern does not strictly follow the plain scalar grammar of YAML,
-/// which means some strings may be unnecessarily quoted, but it's much simpler.
-final _unquotableYamlString = new RegExp(r"^[a-zA-Z_-][a-zA-Z_0-9-]*$");
-
-/// Converts [data], which is a parsed YAML object, to a pretty-printed string,
-/// using indentation for maps.
-String yamlToString(data) {
- var buffer = new StringBuffer();
-
- _stringify(bool isMapValue, String indent, data) {
- // TODO(nweiz): Serialize using the YAML library once it supports
- // serialization.
-
- // Use indentation for (non-empty) maps.
- if (data is Map && !data.isEmpty) {
- if (isMapValue) {
- buffer.writeln();
- indent += ' ';
- }
-
- // Sort the keys. This minimizes deltas in diffs.
- var keys = data.keys.toList();
- keys.sort((a, b) => a.toString().compareTo(b.toString()));
-
- var first = true;
- for (var key in keys) {
- if (!first) buffer.writeln();
- first = false;
-
- var keyString = key;
- if (key is! String || !_unquotableYamlString.hasMatch(key)) {
- keyString = JSON.encode(key);
- }
-
- buffer.write('$indent$keyString:');
- _stringify(true, indent, data[key]);
- }
-
- return;
- }
-
- // Everything else we just stringify using JSON to handle escapes in
- // strings and number formatting.
- var string = data;
-
- // Don't quote plain strings if not needed.
- if (data is! String || !_unquotableYamlString.hasMatch(data)) {
- string = JSON.encode(data);
- }
-
- if (isMapValue) {
- buffer.write(' $string');
- } else {
- buffer.write('$indent$string');
- }
- }
-
- _stringify(false, '', data);
- return buffer.toString();
-}
-
-/// Throw a [ApplicationException] with [message].
-void fail(String message, [innerError, StackTrace innerTrace]) {
- if (innerError != null) {
- throw new WrappedException(message, innerError, innerTrace);
- } else {
- throw new ApplicationException(message);
- }
-}
-
-/// Throw a [DataException] with [message] to indicate that the command has
-/// failed because of invalid input data.
-///
-/// This will report the error and cause pub to exit with [exit_codes.DATA].
-void dataError(String message) => throw new DataException(message);
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator.dart b/sdk/lib/_internal/pub_generated/lib/src/validator.dart
deleted file mode 100644
index 25e6843..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator.dart
+++ /dev/null
@@ -1,99 +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 pub.validator;
-
-import 'dart:async';
-
-import 'entrypoint.dart';
-import 'log.dart' as log;
-import 'utils.dart';
-import 'validator/compiled_dartdoc.dart';
-import 'validator/dependency.dart';
-import 'validator/dependency_override.dart';
-import 'validator/directory.dart';
-import 'validator/executable.dart';
-import 'validator/license.dart';
-import 'validator/name.dart';
-import 'validator/pubspec_field.dart';
-import 'validator/sdk_constraint.dart';
-import 'validator/size.dart';
-import 'validator/utf8_readme.dart';
-
-/// The base class for validators that check whether a package is fit for
-/// uploading.
-///
-/// Each validator should override [errors], [warnings], or both to return
-/// lists of errors or warnings to display to the user. Errors will cause the
-/// package not to be uploaded; warnings will require the user to confirm the
-/// upload.
-abstract class Validator {
- /// The entrypoint that's being validated.
- final Entrypoint entrypoint;
-
- /// The accumulated errors for this validator.
- ///
- /// Filled by calling [validate].
- final errors = <String>[];
-
- /// The accumulated warnings for this validator.
- ///
- /// Filled by calling [validate].
- final warnings = <String>[];
-
- Validator(this.entrypoint);
-
- /// Validates the entrypoint, adding any errors and warnings to [errors] and
- /// [warnings], respectively.
- Future validate();
-
- /// Run all validators on the [entrypoint] package and print their results.
- ///
- /// The future completes with the error and warning messages, respectively.
- ///
- /// [packageSize], if passed, should complete to the size of the tarred
- /// package, in bytes. This is used to validate that it's not too big to
- /// upload to the server.
- static Future<Pair<List<String>, List<String>>> runAll(Entrypoint entrypoint,
- [Future<int> packageSize]) {
- var validators = [
- new LicenseValidator(entrypoint),
- new NameValidator(entrypoint),
- new PubspecFieldValidator(entrypoint),
- new DependencyValidator(entrypoint),
- new DependencyOverrideValidator(entrypoint),
- new DirectoryValidator(entrypoint),
- new ExecutableValidator(entrypoint),
- new CompiledDartdocValidator(entrypoint),
- new Utf8ReadmeValidator(entrypoint),
- new SdkConstraintValidator(entrypoint)];
- if (packageSize != null) {
- validators.add(new SizeValidator(entrypoint, packageSize));
- }
-
- return Future.wait(
- validators.map((validator) => validator.validate())).then((_) {
- var errors = flatten(validators.map((validator) => validator.errors));
- var warnings = flatten(validators.map((validator) => validator.warnings));
-
- if (!errors.isEmpty) {
- log.error("Missing requirements:");
- for (var error in errors) {
- log.error("* ${error.split('\n').join('\n ')}");
- }
- log.error("");
- }
-
- if (!warnings.isEmpty) {
- log.warning("Suggestions:");
- for (var warning in warnings) {
- log.warning("* ${warning.split('\n').join('\n ')}");
- }
- log.warning("");
- }
-
- return new Pair<List<String>, List<String>>(errors, warnings);
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/compiled_dartdoc.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/compiled_dartdoc.dart
deleted file mode 100644
index 99900d8..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/compiled_dartdoc.dart
+++ /dev/null
@@ -1,43 +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 pub.validator.compiled_dartdoc;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-import '../entrypoint.dart';
-import '../io.dart';
-import '../validator.dart';
-
-/// Validates that a package doesn't contain compiled Dartdoc
-/// output.
-class CompiledDartdocValidator extends Validator {
- CompiledDartdocValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- return new Future.sync(() {
- for (var entry in entrypoint.root.listFiles(useGitIgnore: true)) {
- if (path.basename(entry) != "nav.json") continue;
- var dir = path.dirname(entry);
-
- // Look for tell-tale Dartdoc output files all in the same directory.
- var files = [
- entry,
- path.join(dir, "index.html"),
- path.join(dir, "styles.css"),
- path.join(dir, "dart-logo-small.png"),
- path.join(dir, "client-live-nav.js")];
-
- if (files.every((val) => fileExists(val))) {
- warnings.add(
- "Avoid putting generated documentation in " "${path.relative(dir)}.\n"
- "Generated documentation bloats the package with redundant " "data.");
- }
- }
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/dependency.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/dependency.dart
deleted file mode 100644
index e57b096..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/dependency.dart
+++ /dev/null
@@ -1,273 +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 pub.validator.dependency;
-
-import 'dart:async';
-
-import 'package:pub_semver/pub_semver.dart';
-
-import '../entrypoint.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../utils.dart';
-import '../validator.dart';
-
-/// The range of all pub versions that don't support `^` version constraints.
-final _preCaretPubVersions = new VersionConstraint.parse("<1.8.0-dev.3.0");
-
-// TODO(nweiz): replace this with "^1.8.0" for the 1.8 release.
-/// The range of all pub versions that do support `^` version constraints.
-///
-/// This is intersected with the user's SDK constraint to provide a suggested
-/// constraint.
-final _postCaretPubVersions = new VersionConstraint.parse("^1.8.0-dev.3.0");
-
-/// A validator that validates a package's dependencies.
-class DependencyValidator extends Validator {
- /// Whether the SDK constraint guarantees that `^` version constraints are
- /// safe.
- bool get _caretAllowed =>
- entrypoint.root.pubspec.environment.sdkVersion.intersect(
- _preCaretPubVersions).isEmpty;
-
- DependencyValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var caretDeps = [];
- var it0 = entrypoint.root.pubspec.dependencies.iterator;
- break0() {
- join0() {
- completer0.complete();
- }
- if (caretDeps.isNotEmpty && !_caretAllowed) {
- _errorAboutCaretConstraints(caretDeps);
- join0();
- } else {
- join0();
- }
- }
- var trampoline0;
- continue0() {
- trampoline0 = null;
- if (it0.moveNext()) {
- var dependency = it0.current;
- join1() {
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- }
- if (dependency.source != "hosted") {
- new Future.value(_warnAboutSource(dependency)).then((x0) {
- trampoline0 = () {
- trampoline0 = null;
- try {
- x0;
- join1();
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- };
- do trampoline0(); while (trampoline0 != null);
- }, onError: completer0.completeError);
- } else {
- join2() {
- join1();
- }
- if (dependency.constraint.isAny) {
- _warnAboutNoConstraint(dependency);
- join2();
- } else {
- join3() {
- join2();
- }
- if (dependency.constraint is Version) {
- _warnAboutSingleVersionConstraint(dependency);
- join3();
- } else {
- join4() {
- join3();
- }
- if (dependency.constraint is VersionRange) {
- join5() {
- join6() {
- join4();
- }
- if (dependency.constraint.toString().startsWith("^")) {
- caretDeps.add(dependency);
- join6();
- } else {
- join6();
- }
- }
- if (dependency.constraint.min == null) {
- _warnAboutNoConstraintLowerBound(dependency);
- join5();
- } else {
- join7() {
- join5();
- }
- if (dependency.constraint.max == null) {
- _warnAboutNoConstraintUpperBound(dependency);
- join7();
- } else {
- join7();
- }
- }
- } else {
- join4();
- }
- }
- }
- }
- } else {
- break0();
- }
- }
- trampoline0 = continue0;
- do trampoline0(); while (trampoline0 != null);
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-
- /// Warn that dependencies should use the hosted source.
- Future _warnAboutSource(PackageDep dep) {
- return entrypoint.cache.sources['hosted'].getVersions(
- dep.name,
- dep.name).catchError((e) => <Version>[]).then((versions) {
- var constraint;
- var primary = Version.primary(versions);
- if (primary != null) {
- constraint = _constraintForVersion(primary);
- } else {
- constraint = dep.constraint.toString();
- if (!dep.constraint.isAny && dep.constraint is! Version) {
- constraint = '"$constraint"';
- }
- }
-
- // Path sources are errors. Other sources are just warnings.
- var messages = warnings;
- if (dep.source == "path") {
- messages = errors;
- }
-
- messages.add(
- 'Don\'t depend on "${dep.name}" from the ${dep.source} '
- 'source. Use the hosted source instead. For example:\n' '\n' 'dependencies:\n'
- ' ${dep.name}: $constraint\n' '\n'
- 'Using the hosted source ensures that everyone can download your '
- 'package\'s dependencies along with your package.');
- });
- }
-
- /// Warn that dependencies should have version constraints.
- void _warnAboutNoConstraint(PackageDep dep) {
- var message =
- 'Your dependency on "${dep.name}" should have a version ' 'constraint.';
- var locked = entrypoint.lockFile.packages[dep.name];
- if (locked != null) {
- message =
- '$message For example:\n' '\n' 'dependencies:\n'
- ' ${dep.name}: ${_constraintForVersion(locked.version)}\n';
- }
- warnings.add(
- "$message\n"
- 'Without a constraint, you\'re promising to support ${log.bold("all")} '
- 'future versions of "${dep.name}".');
- }
-
- /// Warn that dependencies should allow more than a single version.
- void _warnAboutSingleVersionConstraint(PackageDep dep) {
- warnings.add(
- 'Your dependency on "${dep.name}" should allow more than one version. '
- 'For example:\n' '\n' 'dependencies:\n'
- ' ${dep.name}: ${_constraintForVersion(dep.constraint)}\n' '\n'
- 'Constraints that are too tight will make it difficult for people to '
- 'use your package\n'
- 'along with other packages that also depend on "${dep.name}".');
- }
-
- /// Warn that dependencies should have lower bounds on their constraints.
- void _warnAboutNoConstraintLowerBound(PackageDep dep) {
- var message = 'Your dependency on "${dep.name}" should have a lower bound.';
- var locked = entrypoint.lockFile.packages[dep.name];
- if (locked != null) {
- var constraint;
- if (locked.version == (dep.constraint as VersionRange).max) {
- constraint = _constraintForVersion(locked.version);
- } else {
- constraint = '">=${locked.version} ${dep.constraint}"';
- }
-
- message =
- '$message For example:\n' '\n' 'dependencies:\n' ' ${dep.name}: $constraint\n';
- }
- warnings.add(
- "$message\n"
- 'Without a constraint, you\'re promising to support ${log.bold("all")} '
- 'previous versions of "${dep.name}".');
- }
-
- /// Warn that dependencies should have upper bounds on their constraints.
- void _warnAboutNoConstraintUpperBound(PackageDep dep) {
- var constraint;
- if ((dep.constraint as VersionRange).includeMin) {
- constraint = _constraintForVersion((dep.constraint as VersionRange).min);
- } else {
- constraint =
- '"${dep.constraint} ' '<${(dep.constraint as VersionRange).min.nextBreaking}"';
- }
-
- warnings.add(
- 'Your dependency on "${dep.name}" should have an upper bound. For ' 'example:\n'
- '\n' 'dependencies:\n' ' ${dep.name}: $constraint\n' '\n'
- 'Without an upper bound, you\'re promising to support '
- '${log.bold("all")} future versions of ${dep.name}.');
- }
-
- /// Emits an error for any version constraints that use `^` without an
- /// appropriate SDK constraint.
- void _errorAboutCaretConstraints(List<PackageDep> caretDeps) {
- var newSdkConstraint =
- entrypoint.root.pubspec.environment.sdkVersion.intersect(_postCaretPubVersions);
-
- if (newSdkConstraint.isEmpty) newSdkConstraint = _postCaretPubVersions;
-
- var buffer = new StringBuffer(
- "Older versions of pub don't support ^ version constraints.\n"
- "Make sure your SDK constraint excludes those old versions:\n" "\n"
- "environment:\n" " sdk: \"$newSdkConstraint\"\n" "\n");
-
- if (caretDeps.length == 1) {
- buffer.writeln("Or use a fully-expanded constraint:");
- } else {
- buffer.writeln("Or use fully-expanded constraints:");
- }
-
- buffer.writeln();
- buffer.writeln("dependencies:");
-
- caretDeps.forEach((dep) {
- VersionRange constraint = dep.constraint;
- buffer.writeln(
- " ${dep.name}: \">=${constraint.min} <${constraint.max}\"");
- });
-
- errors.add(buffer.toString().trim());
- }
-
- /// Returns the suggested version constraint for a dependency that was tested
- /// against [version].
- String _constraintForVersion(Version version) {
- if (_caretAllowed) return "^$version";
- return '">=$version <${version.nextBreaking}"';
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/dependency_override.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/dependency_override.dart
deleted file mode 100644
index c01b270..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/dependency_override.dart
+++ /dev/null
@@ -1,27 +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 pub.validator.dependency_override;
-
-import 'dart:async';
-
-import '../entrypoint.dart';
-import '../validator.dart';
-
-/// A validator that validates a package's dependencies overrides (or the
-/// absence thereof).
-class DependencyOverrideValidator extends Validator {
- DependencyOverrideValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- if (entrypoint.root.dependencyOverrides.isNotEmpty) {
- errors.add(
- 'Your pubspec.yaml must not have a "dependency_overrides" field.\n'
- 'This ensures you test your package against the same versions of '
- 'its dependencies\n' 'that users will have when they use it.');
- }
- return new Future.value();
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/directory.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/directory.dart
deleted file mode 100644
index a9935e8..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/directory.dart
+++ /dev/null
@@ -1,51 +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 pub.validator.directory;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-import '../entrypoint.dart';
-import '../io.dart';
-import '../validator.dart';
-
-/// A validator that validates a package's top-level directories.
-class DirectoryValidator extends Validator {
- DirectoryValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- static final _PLURAL_NAMES = [
- "benchmarks",
- "docs",
- "examples",
- "tests",
- "tools"];
-
- Future validate() {
- return new Future.sync(() {
- for (var dir in listDir(entrypoint.root.dir)) {
- if (!dirExists(dir)) continue;
-
- dir = path.basename(dir);
- if (_PLURAL_NAMES.contains(dir)) {
- // Cut off the "s"
- var singularName = dir.substring(0, dir.length - 1);
- warnings.add(
- 'Rename the top-level "$dir" directory to ' '"$singularName".\n'
- 'The Pub layout convention is to use singular directory ' 'names.\n'
- 'Plural names won\'t be correctly identified by Pub and other ' 'tools.');
- }
-
- if (dir.contains(new RegExp(r"^samples?$"))) {
- warnings.add(
- 'Rename the top-level "$dir" directory to "example".\n'
- 'This allows Pub to find your examples and create "packages" '
- 'directories for them.\n');
- }
- }
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/executable.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/executable.dart
deleted file mode 100644
index 537edc4..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/executable.dart
+++ /dev/null
@@ -1,42 +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 pub.validator.executable;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as p;
-
-import '../entrypoint.dart';
-import '../validator.dart';
-
-/// Validates that a package's pubspec doesn't contain executables that
-/// reference non-existent scripts.
-class ExecutableValidator extends Validator {
- ExecutableValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var binFiles =
- entrypoint.root.listFiles(beneath: "bin", recursive: false).map(((path) {
- return entrypoint.root.relative(path);
- })).toList();
- entrypoint.root.pubspec.executables.forEach(((executable, script) {
- var scriptPath = p.join("bin", "$script.dart");
- if (binFiles.contains(scriptPath)) return;
- warnings.add(
- 'Your pubspec.yaml lists an executable "$executable" that '
- 'points to a script "$scriptPath" that does not exist.');
- }));
- completer0.complete();
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/license.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/license.dart
deleted file mode 100644
index 944b587..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/license.dart
+++ /dev/null
@@ -1,34 +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 pub.validator.license;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-import '../entrypoint.dart';
-import '../utils.dart';
-import '../validator.dart';
-
-/// A validator that checks that a LICENSE-like file exists.
-class LicenseValidator extends Validator {
- LicenseValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- return new Future.sync(() {
- var licenseLike =
- new RegExp(r"^([a-zA-Z0-9]+[-_])?(LICENSE|COPYING)(\..*)?$");
- if (entrypoint.root.listFiles(
- recursive: false).map(path.basename).any(licenseLike.hasMatch)) {
- return;
- }
-
- errors.add(
- "You must have a COPYING or LICENSE file in the root directory.\n"
- "An open-source license helps ensure people can legally use your " "code.");
- });
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/name.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/name.dart
deleted file mode 100644
index 8b55884..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/name.dart
+++ /dev/null
@@ -1,133 +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 pub.validator.name;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-import '../entrypoint.dart';
-import '../utils.dart';
-import '../validator.dart';
-
-/// Dart reserved words, from the Dart spec.
-final _RESERVED_WORDS = [
- "assert",
- "break",
- "case",
- "catch",
- "class",
- "const",
- "continue",
- "default",
- "do",
- "else",
- "extends",
- "false",
- "final",
- "finally",
- "for",
- "if",
- "in",
- "is",
- "new",
- "null",
- "return",
- "super",
- "switch",
- "this",
- "throw",
- "true",
- "try",
- "var",
- "void",
- "while",
- "with"];
-
-/// A validator that validates the name of the package and its libraries.
-class NameValidator extends Validator {
- NameValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- return new Future.sync(() {
- _checkName(
- entrypoint.root.name,
- 'Package name "${entrypoint.root.name}"',
- isPackage: true);
-
- var libraries = _libraries;
- for (var library in libraries) {
- var libName = path.basenameWithoutExtension(library);
- _checkName(
- libName,
- 'The name of "$library", "$libName",',
- isPackage: false);
- }
-
- if (libraries.length == 1) {
- var libName = path.basenameWithoutExtension(libraries[0]);
- if (libName == entrypoint.root.name) return;
- warnings.add(
- 'The name of "${libraries[0]}", "$libName", should match '
- 'the name of the package, "${entrypoint.root.name}".\n'
- 'This helps users know what library to import.');
- }
- });
- }
-
- /// Returns a list of all libraries in the current package as paths relative
- /// to the package's root directory.
- List<String> get _libraries {
- var libDir = entrypoint.root.path("lib");
- return entrypoint.root.listFiles(
- beneath: "lib").map(
- (file) =>
- path.relative(
- file,
- from: path.dirname(
- libDir))).where(
- (file) =>
- !path.split(file).contains("src") && path.extension(file) == '.dart').toList();
- }
-
- void _checkName(String name, String description, {bool isPackage}) {
- // Packages names are more stringent than libraries.
- var messages = isPackage ? errors : warnings;
-
- if (name == "") {
- errors.add("$description may not be empty.");
- } else if (!new RegExp(r"^[a-zA-Z0-9_]*$").hasMatch(name)) {
- messages.add(
- "$description may only contain letters, numbers, and " "underscores.\n"
- "Using a valid Dart identifier makes the name usable in Dart code.");
- } else if (!new RegExp(r"^[a-zA-Z_]").hasMatch(name)) {
- messages.add(
- "$description must begin with a letter or underscore.\n"
- "Using a valid Dart identifier makes the name usable in Dart code.");
- } else if (_RESERVED_WORDS.contains(name.toLowerCase())) {
- messages.add(
- "$description may not be a reserved word in Dart.\n"
- "Using a valid Dart identifier makes the name usable in Dart code.");
- } else if (new RegExp(r"[A-Z]").hasMatch(name)) {
- warnings.add(
- '$description should be lower-case. Maybe use ' '"${_unCamelCase(name)}"?');
- }
- }
-
- String _unCamelCase(String source) {
- var builder = new StringBuffer();
- var lastMatchEnd = 0;
- for (var match in new RegExp(r"[a-z]([A-Z])").allMatches(source)) {
- builder
- ..write(source.substring(lastMatchEnd, match.start + 1))
- ..write("_")
- ..write(match.group(1).toLowerCase());
- lastMatchEnd = match.end;
- }
- builder.write(source.substring(lastMatchEnd));
- return builder.toString().toLowerCase();
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/pubspec_field.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/pubspec_field.dart
deleted file mode 100644
index d0f55b7..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/pubspec_field.dart
+++ /dev/null
@@ -1,111 +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 pub.validator.pubspec_field;
-
-import 'dart:async';
-
-import '../entrypoint.dart';
-import '../validator.dart';
-
-/// A validator that checks that the pubspec has valid "author" and "homepage"
-/// fields.
-class PubspecFieldValidator extends Validator {
- PubspecFieldValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- _validateAuthors();
- _validateFieldIsString('description');
- _validateFieldIsString('homepage');
- _validateFieldUrl('homepage');
- _validateFieldUrl('documentation');
-
- // Any complex parsing errors in version will be exposed through
- // [Pubspec.allErrors].
- _validateFieldIsString('version');
-
- // Pubspec errors are detected lazily, so we make sure there aren't any
- // here.
- for (var error in entrypoint.root.pubspec.allErrors) {
- errors.add('In your pubspec.yaml, ${error.message}');
- }
-
- return new Future.value();
- }
-
- /// Adds an error if the "author" or "authors" field doesn't exist or has the
- /// wrong type.
- void _validateAuthors() {
- var pubspec = entrypoint.root.pubspec;
- var author = pubspec.fields['author'];
- var authors = pubspec.fields['authors'];
- if (author == null && authors == null) {
- errors.add('Your pubspec.yaml must have an "author" or "authors" field.');
- return;
- }
-
- if (author != null && author is! String) {
- errors.add(
- 'Your pubspec.yaml\'s "author" field must be a string, but it '
- 'was "$author".');
- return;
- }
-
- if (authors != null &&
- (authors is! List || authors.any((author) => author is! String))) {
- errors.add(
- 'Your pubspec.yaml\'s "authors" field must be a list, but '
- 'it was "$authors".');
- return;
- }
-
- if (authors == null) authors = [author];
-
- var hasName = new RegExp(r"^ *[^< ]");
- var hasEmail = new RegExp(r"<[^>]+> *$");
- for (var authorName in authors) {
- if (!hasName.hasMatch(authorName)) {
- warnings.add(
- 'Author "$authorName" in pubspec.yaml should have a ' 'name.');
- }
- if (!hasEmail.hasMatch(authorName)) {
- warnings.add(
- 'Author "$authorName" in pubspec.yaml should have an '
- 'email address\n(e.g. "name <email>").');
- }
- }
- }
-
- /// Adds an error if [field] doesn't exist or isn't a string.
- void _validateFieldIsString(String field) {
- var value = entrypoint.root.pubspec.fields[field];
- if (value == null) {
- errors.add('Your pubspec.yaml is missing a "$field" field.');
- } else if (value is! String) {
- errors.add(
- 'Your pubspec.yaml\'s "$field" field must be a string, but '
- 'it was "$value".');
- }
- }
-
- /// Adds an error if the URL for [field] is invalid.
- void _validateFieldUrl(String field) {
- var url = entrypoint.root.pubspec.fields[field];
- if (url == null) return;
-
- if (url is! String) {
- errors.add(
- 'Your pubspec.yaml\'s "$field" field must be a string, but ' 'it was "$url".');
- return;
- }
-
- var goodScheme = new RegExp(r'^https?:');
- if (!goodScheme.hasMatch(url)) {
- errors.add(
- 'Your pubspec.yaml\'s "$field" field must be an "http:" or '
- '"https:" URL, but it was "$url".');
- }
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/sdk_constraint.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/sdk_constraint.dart
deleted file mode 100644
index 0fe9ac8..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/sdk_constraint.dart
+++ /dev/null
@@ -1,45 +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.
-
-library pub.validator.sdk_constraint;
-
-import 'dart:async';
-
-import 'package:pub_semver/pub_semver.dart';
-
-import '../entrypoint.dart';
-import '../log.dart' as log;
-import '../package.dart';
-import '../validator.dart';
-
-/// A validator that validates that a package's SDK constraint doesn't use the
-/// "^" syntax.
-class SdkConstraintValidator extends Validator {
- SdkConstraintValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var constraint = entrypoint.root.pubspec.environment.sdkVersion;
- join0() {
- errors.add(
- "^ version constraints aren't allowed for SDK constraints since "
- "older versions of pub don't support them.\n" "Expand it manually instead:\n"
- "\n" "environment:\n" " sdk: \">=${constraint.min} <${constraint.max}\"");
- completer0.complete();
- }
- if (!constraint.toString().startsWith("^")) {
- completer0.complete(null);
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/size.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/size.dart
deleted file mode 100644
index 129fea9..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/size.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2013, 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 pub.validator.size;
-
-import 'dart:async';
-import 'dart:math' as math;
-
-import '../entrypoint.dart';
-import '../validator.dart';
-
-/// The maximum size of the package to upload (10 MB).
-const _MAX_SIZE = 10 * 1024 * 1024;
-
-/// A validator that validates that a package isn't too big.
-class SizeValidator extends Validator {
- final Future<int> packageSize;
-
- SizeValidator(Entrypoint entrypoint, this.packageSize)
- : super(entrypoint);
-
- Future validate() {
- return packageSize.then((size) {
- if (size <= _MAX_SIZE) return;
- var sizeInMb = (size / math.pow(2, 20)).toStringAsPrecision(4);
- errors.add(
- "Your package is $sizeInMb MB. Hosted packages must be " "smaller than 10 MB.");
- });
- }
-}
-
diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/utf8_readme.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/utf8_readme.dart
deleted file mode 100644
index c3e2bf7..0000000
--- a/sdk/lib/_internal/pub_generated/lib/src/validator/utf8_readme.dart
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) 2013, 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 pub.validator.utf8_readme;
-
-import 'dart:async';
-import 'dart:convert';
-
-import '../entrypoint.dart';
-import '../io.dart';
-import '../validator.dart';
-
-/// Validates that a package's README is valid utf-8.
-class Utf8ReadmeValidator extends Validator {
- Utf8ReadmeValidator(Entrypoint entrypoint)
- : super(entrypoint);
-
- Future validate() {
- return new Future.sync(() {
- var readme = entrypoint.root.readmePath;
- if (readme == null) return;
- var bytes = readBinaryFile(readme);
- try {
- // UTF8.decode doesn't allow invalid UTF-8.
- UTF8.decode(bytes);
- } on FormatException catch (_) {
- warnings.add(
- "$readme contains invalid UTF-8.\n"
- "This will cause it to be displayed incorrectly on " "pub.dartlang.org.");
- }
- });
- }
-}
-
diff --git a/sdk/lib/_internal/pub_generated/test/ascii_tree_test.dart b/sdk/lib/_internal/pub_generated/test/ascii_tree_test.dart
deleted file mode 100644
index 04cf1f7..0000000
--- a/sdk/lib/_internal/pub_generated/test/ascii_tree_test.dart
+++ /dev/null
@@ -1,244 +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 lock_file_test;
-
-import 'package:unittest/unittest.dart';
-
-import '../lib/src/ascii_tree.dart' as tree;
-import '../lib/src/utils.dart';
-
-main() {
- runningAsTest = true;
-
- group('tree.fromFiles', () {
- test('no files', () {
- expect(tree.fromFiles([]), equals(""));
- });
-
- test('up to ten files in one directory are shown', () {
- var files = [
- "dir/a.dart",
- "dir/b.dart",
- "dir/c.dart",
- "dir/d.dart",
- "dir/e.dart",
- "dir/f.dart",
- "dir/g.dart",
- "dir/h.dart",
- "dir/i.dart",
- "dir/j.dart"];
- expect(tree.fromFiles(files), equals("""
-'-- dir
- |-- a.dart
- |-- b.dart
- |-- c.dart
- |-- d.dart
- |-- e.dart
- |-- f.dart
- |-- g.dart
- |-- h.dart
- |-- i.dart
- '-- j.dart
-"""));
- });
-
- test('files are elided if there are more than ten', () {
- var files = [
- "dir/a.dart",
- "dir/b.dart",
- "dir/c.dart",
- "dir/d.dart",
- "dir/e.dart",
- "dir/f.dart",
- "dir/g.dart",
- "dir/h.dart",
- "dir/i.dart",
- "dir/j.dart",
- "dir/k.dart"];
- expect(tree.fromFiles(files), equals("""
-'-- dir
- |-- a.dart
- |-- b.dart
- |-- c.dart
- | (5 more...)
- |-- i.dart
- |-- j.dart
- '-- k.dart
-"""));
- });
-
- test('files are not elided at the top level', () {
- var files = [
- "a.dart",
- "b.dart",
- "c.dart",
- "d.dart",
- "e.dart",
- "f.dart",
- "g.dart",
- "h.dart",
- "i.dart",
- "j.dart",
- "k.dart"];
- expect(tree.fromFiles(files), equals("""
-|-- a.dart
-|-- b.dart
-|-- c.dart
-|-- d.dart
-|-- e.dart
-|-- f.dart
-|-- g.dart
-|-- h.dart
-|-- i.dart
-|-- j.dart
-'-- k.dart
-"""));
- });
-
- test('a complex example', () {
- var files = [
- "TODO",
- "example/console_example.dart",
- "example/main.dart",
- "example/web copy/web_example.dart",
- "test/absolute_test.dart",
- "test/basename_test.dart",
- "test/dirname_test.dart",
- "test/extension_test.dart",
- "test/is_absolute_test.dart",
- "test/is_relative_test.dart",
- "test/join_test.dart",
- "test/normalize_test.dart",
- "test/relative_test.dart",
- "test/split_test.dart",
- ".gitignore",
- "README.md",
- "lib/path.dart",
- "pubspec.yaml",
- "test/all_test.dart",
- "test/path_posix_test.dart",
- "test/path_windows_test.dart"];
-
- expect(tree.fromFiles(files), equals("""
-|-- .gitignore
-|-- README.md
-|-- TODO
-|-- example
-| |-- console_example.dart
-| |-- main.dart
-| '-- web copy
-| '-- web_example.dart
-|-- lib
-| '-- path.dart
-|-- pubspec.yaml
-'-- test
- |-- absolute_test.dart
- |-- all_test.dart
- |-- basename_test.dart
- | (7 more...)
- |-- path_windows_test.dart
- |-- relative_test.dart
- '-- split_test.dart
-"""));
- });
- });
-
- group('treeFromMap', () {
- test('empty map', () {
- expect(tree.fromMap({}), equals(""));
- });
-
- test('a complex example', () {
- var map = {
- ".gitignore": {},
- "README.md": {},
- "TODO": {},
- "example": {
- "console_example.dart": {},
- "main.dart": {},
- "web copy": {
- "web_example.dart": {}
- },
- },
- "lib": {
- "path.dart": {}
- },
- "pubspec.yaml": {},
- "test": {
- "absolute_test.dart": {},
- "basename_test.dart": {},
- "dirname_test.dart": {},
- "extension_test.dart": {},
- "is_absolute_test.dart": {},
- "is_relative_test.dart": {},
- "join_test.dart": {},
- "normalize_test.dart": {},
- "relative_test.dart": {},
- "split_test.dart": {}
- }
- };
-
- expect(tree.fromMap(map), equals("""
-|-- .gitignore
-|-- README.md
-|-- TODO
-|-- example
-| |-- console_example.dart
-| |-- main.dart
-| '-- web copy
-| '-- web_example.dart
-|-- lib
-| '-- path.dart
-|-- pubspec.yaml
-'-- test
- |-- absolute_test.dart
- |-- basename_test.dart
- |-- dirname_test.dart
- |-- extension_test.dart
- |-- is_absolute_test.dart
- |-- is_relative_test.dart
- |-- join_test.dart
- |-- normalize_test.dart
- |-- relative_test.dart
- '-- split_test.dart
-"""));
- });
- });
-
- test('does not elide children if showAllChildren is true', () {
- var map = {
- 'dir': {
- 'a.dart': {},
- 'b.dart': {},
- 'c.dart': {},
- 'd.dart': {},
- 'e.dart': {},
- 'f.dart': {},
- 'g.dart': {},
- 'h.dart': {},
- 'i.dart': {},
- 'j.dart': {},
- 'k.dart': {},
- 'l.dart': {},
- }
- };
- expect(tree.fromMap(map, showAllChildren: true), equals("""
-'-- dir
- |-- a.dart
- |-- b.dart
- |-- c.dart
- |-- d.dart
- |-- e.dart
- |-- f.dart
- |-- g.dart
- |-- h.dart
- |-- i.dart
- |-- j.dart
- |-- k.dart
- '-- l.dart
-"""));
- });
-
-}
diff --git a/sdk/lib/_internal/pub_generated/test/async_compile_test.dart b/sdk/lib/_internal/pub_generated/test/async_compile_test.dart
deleted file mode 100644
index 6c0af59..0000000
--- a/sdk/lib/_internal/pub_generated/test/async_compile_test.dart
+++ /dev/null
@@ -1,30 +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 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/descriptor.dart' as d;
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_process.dart';
-
-import 'test_pub.dart';
-import '../lib/src/io.dart';
-
-void main() {
- integration("the generated pub source is up to date", () {
- var compilerArgs = Platform.executableArguments.toList()..addAll(
- [
- p.join(pubRoot, 'bin', 'async_compile.dart'),
- '--force',
- '--verbose',
- p.join(sandboxDir, "pub_generated")]);
-
- new ScheduledProcess.start(Platform.executable, compilerArgs).shouldExit(0);
-
- new d.DirectoryDescriptor.fromFilesystem(
- "pub_generated",
- p.join(pubRoot, "..", "pub_generated")).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/all_includes_all_default_directories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/all_includes_all_default_directories_test.dart
deleted file mode 100644
index 6fd966c..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/all_includes_all_default_directories_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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../serve/utils.dart';
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir('benchmark', [d.file('file.txt', 'benchmark')]),
- d.dir('bin', [d.file('file.txt', 'bin')]),
- d.dir('example', [d.file('file.txt', 'example')]),
- d.dir('test', [d.file('file.txt', 'test')]),
- d.dir('web', [d.file('file.txt', 'web')]),
- d.dir('unknown', [d.file('file.txt', 'unknown')])]).create();
- });
-
- integration("build --all finds assets in default source directories", () {
- schedulePub(
- args: ["build", "--all"],
- output: new RegExp(r'Built 5 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir('benchmark', [d.file('file.txt', 'benchmark')]),
- d.dir('bin', [d.file('file.txt', 'bin')]),
- d.dir('example', [d.file('file.txt', 'example')]),
- d.dir('test', [d.file('file.txt', 'test')]),
- d.dir('web', [d.file('file.txt', 'web')]),
- // Only includes default source directories.
- d.nothing('unknown')])]).validate();
- });
-
- integration("serve --all finds assets in default source directories", () {
- pubServe(args: ["--all"]);
-
- requestShouldSucceed("file.txt", "benchmark", root: "benchmark");
- requestShouldSucceed("file.txt", "bin", root: "bin");
- requestShouldSucceed("file.txt", "example", root: "example");
- requestShouldSucceed("file.txt", "test", root: "test");
- requestShouldSucceed("file.txt", "web", root: "web");
-
- expectNotServed("unknown");
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/directory_args_test.dart b/sdk/lib/_internal/pub_generated/test/barback/directory_args_test.dart
deleted file mode 100644
index 44ecc99..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/directory_args_test.dart
+++ /dev/null
@@ -1,52 +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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir('bar', [d.file('file.txt', 'bar')]),
- d.dir('foo', [d.file('file.txt', 'foo')]),
- d.dir('test', [d.file('file.txt', 'test')]),
- d.dir('web', [d.file('file.txt', 'web')])]).create();
- });
-
- integration("builds only the given directories", () {
- schedulePub(
- args: ["build", "foo", "bar"],
- output: new RegExp(r'Built 2 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir('bar', [d.file('file.txt', 'bar')]),
- d.dir('foo', [d.file('file.txt', 'foo')]),
- d.nothing('test'),
- d.nothing('web')])]).validate();
- });
-
- integration("serves only the given directories", () {
- pubServe(args: ["foo", "bar"]);
-
- requestShouldSucceed("file.txt", "bar", root: "bar");
- requestShouldSucceed("file.txt", "foo", root: "foo");
- expectNotServed("test");
- expectNotServed("web");
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_if_args_with_all_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_if_args_with_all_test.dart
deleted file mode 100644
index 939b122..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/fails_if_args_with_all_test.dart
+++ /dev/null
@@ -1,24 +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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.appDir().create();
- });
-
- pubBuildAndServeShouldFail(
- "if a directory is passed with --all",
- args: ["example", "--all"],
- error: 'Directory names are not allowed if "--all" is passed.',
- exitCode: exit_codes.USAGE);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_arg_does_not_exist_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_arg_does_not_exist_test.dart
deleted file mode 100644
index 3e31c5a..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_arg_does_not_exist_test.dart
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("bar", [d.file("file.txt", "contents")])]).create();
- });
-
- pubBuildAndServeShouldFail(
- "if a specified directory doesn't exist",
- args: ["foo", "bar", "baz"],
- error: 'Directories "foo" and "baz" do not exist.',
- exitCode: exit_codes.DATA);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_outside_package_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_outside_package_test.dart
deleted file mode 100644
index 840f7d4..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_outside_package_test.dart
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.appDir().create();
- });
-
- pubBuildAndServeShouldFail(
- "if source directory reaches outside the package",
- args: [".."],
- error: 'Directory ".." isn\'t in this package.',
- exitCode: exit_codes.USAGE);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_if_no_default_dirs_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_if_no_default_dirs_test.dart
deleted file mode 100644
index fb3e607..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/fails_if_no_default_dirs_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.appDir().create();
- });
-
- pubBuildAndServeShouldFail(
- "if no directories were passed and no default " "ones exist",
- args: [],
- buildError: 'Your package must have a "web" directory,\n'
- 'or you must specify the source directories.',
- serveError: 'Your package must have "web" and/or "test" directories,\n'
- 'or you must specify the source directories.',
- exitCode: exit_codes.DATA);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_on_all_with_no_buildable_directories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_on_all_with_no_buildable_directories_test.dart
deleted file mode 100644
index d88fc96..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/fails_on_all_with_no_buildable_directories_test.dart
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.appDir().create();
- });
-
- pubBuildAndServeShouldFail(
- "on --all with no default source directories",
- args: ["--all"],
- error: 'There are no source directories present.\n'
- 'The default directories are "benchmark", "bin", "example", '
- '"test" and "web".',
- exitCode: exit_codes.DATA);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_on_disallowed_directories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_on_disallowed_directories_test.dart
deleted file mode 100644
index 507ac4d..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/fails_on_disallowed_directories_test.dart
+++ /dev/null
@@ -1,26 +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:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.appDir().create();
- });
-
- var libSub = path.join("lib", "sub");
- pubBuildAndServeShouldFail(
- "if given directories are not allowed",
- args: [libSub, "lib"],
- error: 'Directories "$libSub" and "lib" are not allowed.',
- exitCode: exit_codes.USAGE);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_on_overlapping_directories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_on_overlapping_directories_test.dart
deleted file mode 100644
index a66e87e..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/fails_on_overlapping_directories_test.dart
+++ /dev/null
@@ -1,54 +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:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.dir(
- "sub1",
- [
- d.file("file.txt", "contents"),
- d.dir("sub2", [d.file("file.txt", "contents")]),
- d.dir("sub3", [d.file("file.txt", "contents")])])])]).create();
- });
-
- var webSub1 = path.join("web", "sub1");
- var webSub1Sub2 = path.join("web", "sub1", "sub2");
- var webSub1Sub3 = path.join("web", "sub1", "sub3");
-
- pubBuildAndServeShouldFail(
- "if a superdirectory follows a subdirectory",
- args: [webSub1Sub2, webSub1],
- error: 'Directories "$webSub1Sub2" and "$webSub1" cannot overlap.',
- exitCode: exit_codes.USAGE);
-
- pubBuildAndServeShouldFail(
- "if a subdirectory follows a superdirectory",
- args: [webSub1, webSub1Sub2],
- error: 'Directories "$webSub1" and "$webSub1Sub2" cannot overlap.',
- exitCode: exit_codes.USAGE);
-
- pubBuildAndServeShouldFail(
- "if multiple directories overlap",
- args: [webSub1, webSub1Sub2, webSub1Sub3],
- error: 'Directories "$webSub1", "$webSub1Sub2" and "$webSub1Sub3" '
- 'cannot overlap.',
- exitCode: exit_codes.USAGE);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/subdirectories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/subdirectories_test.dart
deleted file mode 100644
index 393030a..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/subdirectories_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:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../serve/utils.dart';
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.dir("one", [d.dir("inner", [d.file("file.txt", "one")])]),
- d.dir("two", [d.dir("inner", [d.file("file.txt", "two")])]),
- d.dir("nope", [d.dir("inner", [d.file("file.txt", "nope")])])])]).create();
- });
-
- var webOne = p.join("web", "one");
- var webTwoInner = p.join("web", "two", "inner");
-
- integration("builds subdirectories", () {
- schedulePub(
- args: ["build", webOne, webTwoInner],
- output: new RegExp(r'Built 2 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- "build",
- [
- d.dir(
- "web",
- [
- d.dir("one", [d.dir("inner", [d.file("file.txt", "one")])]),
- d.dir("two", [d.dir("inner", [d.file("file.txt", "two")])]),
- d.nothing("nope")])])]).validate();
- });
-
- integration("serves subdirectories", () {
- pubServe(args: [webOne, webTwoInner]);
-
- requestShouldSucceed("inner/file.txt", "one", root: webOne);
- requestShouldSucceed("file.txt", "two", root: webTwoInner);
- expectNotServed("web");
- expectNotServed(p.join("web", "three"));
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/barback/utils.dart b/sdk/lib/_internal/pub_generated/test/barback/utils.dart
deleted file mode 100644
index ebdfd42..0000000
--- a/sdk/lib/_internal/pub_generated/test/barback/utils.dart
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../test_pub.dart';
-
-/// Runs separate integration tests for "pub build", "pub serve", and
-/// "pub build --format json" and validates that in all cases, it fails with
-/// an expected error message and exits with [exitCode].
-///
-/// The integrations assume set up is already done, so you will likely want to
-/// call [setUp] before this.
-///
-/// If [error] is provided, then both pub build and pub serve should exit with
-/// that message. Otherwise, [buildError] is the expected error from pub build
-/// and [serveError] from pub serve.
-void pubBuildAndServeShouldFail(String description, {List<String> args,
- String error, String buildError, String serveError, int exitCode}) {
-
- if (error != null) {
- assert(buildError == null);
- buildError = error;
-
- assert(serveError == null);
- serveError = error;
- }
-
- // Usage errors also print the usage, so validate that.
- var buildExpectation = buildError;
- var serveExpectation = serveError;
- if (exitCode == exit_codes.USAGE) {
- buildExpectation =
- allOf(startsWith(buildExpectation), contains("Usage: pub build"));
- serveExpectation =
- allOf(startsWith(serveExpectation), contains("Usage: pub serve"));
- }
-
- integration("build fails $description", () {
- schedulePub(
- args: ["build"]..addAll(args),
- error: buildExpectation,
- exitCode: exitCode);
- });
-
- integration("build --format json fails $description", () {
- schedulePub(args: ["build", "--format", "json"]..addAll(args), outputJson: {
- "error": buildError // No usage in JSON output.
- }, exitCode: exitCode);
- });
-
- integration("serve fails $description", () {
- schedulePub(
- args: ["serve"]..addAll(args),
- error: serveExpectation,
- exitCode: exitCode);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/allows_arbitrary_modes_test.dart b/sdk/lib/_internal/pub_generated/test/build/allows_arbitrary_modes_test.dart
deleted file mode 100644
index ef8fd72..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/allows_arbitrary_modes_test.dart
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class ModeTransformer extends Transformer {
- final BarbackSettings settings;
- ModeTransformer.asPlugin(this.settings);
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return new Future.value().then((_) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, settings.mode.toString()));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("allows user-defined mode names", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- schedulePub(args: ["build", "--mode", "depeche"]);
-
- d.dir(
- appPath,
- [d.dir('build', [d.dir('web', [d.file('foo.out', 'depeche')])])]).validate();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/can_specify_output_directory_test.dart b/sdk/lib/_internal/pub_generated/test/build/can_specify_output_directory_test.dart
deleted file mode 100644
index fac7003..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/can_specify_output_directory_test.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("can specify the output directory to build into", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir('web', [d.file('file.txt', 'web')])]).create();
-
- var outDir = path.join("out", "dir");
- schedulePub(
- args: ["build", "-o", outDir],
- output: contains('Built 1 file to "$outDir".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- "out",
- [d.dir("dir", [d.dir("web", [d.file("file.txt", "web")]),])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/cleans_entire_build_directory_test.dart b/sdk/lib/_internal/pub_generated/test/build/cleans_entire_build_directory_test.dart
deleted file mode 100644
index 6a2548b..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/cleans_entire_build_directory_test.dart
+++ /dev/null
@@ -1,38 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- integration("cleans entire build directory before a build", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir('example', [d.file('file.txt', 'example')]),
- d.dir('test', [d.file('file.txt', 'test')])]).create();
-
- // Make a build directory containing "example".
- schedulePub(
- args: ["build", "example"],
- output: new RegExp(r'Built 1 file to "build".'));
-
- // Now build again with just "test". Should wipe out "example".
- schedulePub(
- args: ["build", "test"],
- output: new RegExp(r'Built 1 file to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.nothing('example'),
- d.dir('test', [d.file('file.txt', 'test')]),])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_next_to_entrypoints_test.dart b/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_next_to_entrypoints_test.dart
deleted file mode 100644
index d05ef15..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_next_to_entrypoints_test.dart
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
-
- integration("compiles dart.js and interop.js next to entrypoints", () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- serveBrowserPackage();
-
- d.dir(appPath, [d.appPubspec({
- "browser": "1.0.0"
- }),
- d.dir(
- 'foo',
- [
- d.file('file.dart', 'void main() => print("hello");'),
- d.dir(
- 'subdir',
- [d.file('subfile.dart', 'void main() => print("subhello");')])]),
- d.dir(
- 'web',
- [
- d.file('file.dart', 'void main() => print("hello");'),
- d.dir(
- 'subweb',
- [d.file('subfile.dart', 'void main() => print("subhello");')])])]).create();
-
- pubGet();
-
- schedulePub(
- args: ["build", "foo", "web"],
- output: new RegExp(r'Built 12 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'foo',
- [
- d.matcherFile('file.dart.js', isNot(isEmpty)),
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])]),
- d.dir(
- 'subdir',
- [
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])]),
- d.matcherFile('subfile.dart.js', isNot(isEmpty)),])]),
- d.dir(
- 'web',
- [
- d.matcherFile('file.dart.js', isNot(isEmpty)),
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])]),
- d.dir(
- 'subweb',
- [
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])]),
- d.matcherFile('subfile.dart.js', isNot(isEmpty))])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dependency_override_test.dart b/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dependency_override_test.dart
deleted file mode 100644
index de98aaa..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dependency_override_test.dart
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- // This is a regression test for http://dartbug.com/16617.
-
- initConfig();
-
- integration(
- "compiles dart.js and interop.js next to entrypoints when "
- "browser is a dependency_override",
- () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- serveBrowserPackage();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependency_overrides": {
- "browser": "any"
- }
- }),
- d.dir(
- 'web',
- [d.file('file.dart', 'void main() => print("hello");')])]).create();
-
- pubGet();
-
- schedulePub(
- args: ["build", "--all"],
- output: new RegExp(r'Built 3 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dev_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dev_dependency_test.dart
deleted file mode 100644
index 26184aa..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dev_dependency_test.dart
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- // This is a regression test for http://dartbug.com/16617.
-
- initConfig();
-
- integration(
- "compiles dart.js and interop.js next to entrypoints when "
- "browser is a dev dependency",
- () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- serveBrowserPackage();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dev_dependencies": {
- "browser": "any"
- }
- }),
- d.dir(
- 'web',
- [d.file('file.dart', 'void main() => print("hello");')])]).create();
-
- pubGet();
-
- schedulePub(
- args: ["build", "--all"],
- output: new RegExp(r'Built 3 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/copies_non_dart_files_to_build_test.dart b/sdk/lib/_internal/pub_generated/test/build/copies_non_dart_files_to_build_test.dart
deleted file mode 100644
index ab808b7..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/copies_non_dart_files_to_build_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, 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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- integration("copies non-Dart files to build/", () {
- servePackages((builder) => builder.serve("browser", "1.0.0"));
-
- d.dir(
- appPath,
- [// A browser dependency with no entrypoints shouldn't cause dart.js to be
- // copied in.
- d.appPubspec({
- "browser": "1.0.0"
- }),
- d.dir(
- 'web',
- [
- d.file('file.txt', 'contents'),
- d.dir('subdir', [d.file('subfile.txt', 'subcontents')])])]).create();
-
- schedulePub(
- args: ["build"],
- output: new RegExp(r'Built 2 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.nothing('packages'),
- d.file('file.txt', 'contents'),
- d.dir('subdir', [d.file('subfile.txt', 'subcontents')])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/defaults_to_release_mode_test.dart b/sdk/lib/_internal/pub_generated/test/build/defaults_to_release_mode_test.dart
deleted file mode 100644
index 86e3146..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/defaults_to_release_mode_test.dart
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class ModeTransformer extends Transformer {
- final BarbackSettings settings;
- ModeTransformer.asPlugin(this.settings);
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return new Future.value().then((_) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, settings.mode.toString()));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("defaults to release mode", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- schedulePub(args: ["build"]);
-
- d.dir(
- appPath,
- [d.dir('build', [d.dir('web', [d.file('foo.out', 'release')])])]).validate();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/handles_long_paths_test.dart b/sdk/lib/_internal/pub_generated/test/build/handles_long_paths_test.dart
deleted file mode 100644
index 094938e..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/handles_long_paths_test.dart
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import 'package:path/path.dart' as path;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- // This is a regression test for dartbug.com/14442.
- //
- // If you have a long chain of path dependencies with long relative paths,
- // you can end up with a combined path that is longer than the OS can handle.
- // For example, the path that revealed this bug was:
- //
- // C:\jenkins-slave\workspace\mSEE-Dev\ozone\dart\portfolio-manager\src\main\
- // portfolio-manager\..\..\..\..\portfolio-common\src\main\portfolio-common\
- // ../../../../dart-visualization/src/main/dart-visualization\lib\src\vega\
- // data\transform\visual
- //
- // This test ensures that we're normalizing at some point before we throw the
- // path at the OS to choke on.
-
- integration("handles long relative paths", () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- d.dir(
- "some_long_dependency_name",
- [
- d.libPubspec("foo", "0.0.1"),
- d.dir("lib", [d.file("foo.txt", "foo")])]).create();
-
- // Build a 2,800 character (non-canonicalized) path.
- var longPath = "";
- for (var i = 0; i < 100; i++) {
- longPath = path.join(longPath, "..", "some_long_dependency_name");
- }
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": longPath
- }
- }), d.dir("web", [d.file("index.html", "html"),])]).create();
-
- schedulePub(
- args: ["build"],
- output: new RegExp(r'Built 2 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.file("index.html", "html"),
- d.dir('packages', [d.dir('foo', [d.file('foo.txt', 'foo')])])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/includes_assets_from_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/build/includes_assets_from_dependencies_test.dart
deleted file mode 100644
index d244e17..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/includes_assets_from_dependencies_test.dart
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- integration("includes assets from the 'lib' directory of dependencies", () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "0.0.1"),
- d.dir(
- "lib",
- [
- d.file("foo.txt", "foo"),
- d.dir("sub", [d.file("bar.txt", "bar"),])])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }),
- d.dir("example", [d.file("index.html", "html"),]),
- d.dir(
- "web",
- [
- d.file("index.html", "html"),
- d.dir("sub", [d.file("index.html", "html")])])]).create();
-
- schedulePub(
- args: ["build", "--all"],
- output: new RegExp(r'Built 7 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'example',
- [
- d.file("index.html", "html"),
- d.dir(
- 'packages',
- [
- d.dir(
- 'foo',
- [d.file('foo.txt', 'foo'), d.dir('sub', [d.file('bar.txt', 'bar'),]),])])]),
- d.dir(
- 'web',
- [
- d.file("index.html", "html"),
- d.dir(
- 'packages',
- [
- d.dir(
- 'foo',
- [d.file('foo.txt', 'foo'), d.dir('sub', [d.file('bar.txt', 'bar'),]),])]),
- d.dir(
- "sub",
- [
- d.file("index.html", "html"),
- // "packages" should *only* be created in the top-level directory.
- d.nothing("packages")])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_from_dependencies_in_debug_test.dart b/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_from_dependencies_in_debug_test.dart
deleted file mode 100644
index a1dff8a..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_from_dependencies_in_debug_test.dart
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- integration("includes .dart files from dependencies in debug mode", () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "0.0.1"),
- d.dir(
- "lib",
- [
- d.file('foo.dart', 'foo() => print("hello");'),
- d.dir("sub", [d.file('bar.dart', 'bar() => print("hello");'),])])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }),
- d.dir(
- "example",
- [
- d.file("main.dart", 'myapp() => print("not entrypoint");'),
- d.dir(
- "sub",
- [d.file("main.dart", 'myapp() => print("not entrypoint");')])])]).create();
-
- schedulePub(
- args: ["build", "--mode", "debug", "example"],
- output: new RegExp(r'Built \d+ files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'example',
- [
- d.file("main.dart", 'myapp() => print("not entrypoint");'),
- d.dir(
- 'packages',
- [
- d.dir(
- 'foo',
- [
- d.file('foo.dart', 'foo() => print("hello");'),
- d.dir("sub", [d.file('bar.dart', 'bar() => print("hello");'),])])]),
- d.dir(
- "sub",
- [
- d.file("main.dart", 'myapp() => print("not entrypoint");'),
- // Does *not* copy packages into subdirectories.
- d.nothing("packages")])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_in_debug_mode_test.dart b/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_in_debug_mode_test.dart
deleted file mode 100644
index ac7a293..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_in_debug_mode_test.dart
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- integration("includes Dart files in debug mode", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- 'web',
- [
- d.file('file1.dart', 'var main = () => print("hello");'),
- d.file('file2.dart', 'void main(arg1, arg2, arg3) => print("hello");'),
- d.file('file3.dart', 'class Foo { void main() => print("hello"); }'),
- d.file('file4.dart', 'var foo;')])]).create();
-
- schedulePub(
- args: ["build", "--mode", "debug"],
- output: new RegExp(r'Built \d+ files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.nothing('file1.dart.js'),
- d.matcherFile('file1.dart', isNot(isEmpty)),
- d.nothing('file2.dart.js'),
- d.matcherFile('file2.dart', isNot(isEmpty)),
- d.nothing('file3.dart.js'),
- d.matcherFile('file3.dart', isNot(isEmpty)),
- d.nothing('file4.dart.js'),
- d.matcherFile('file4.dart', isNot(isEmpty))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/outputs_error_to_json_test.dart b/sdk/lib/_internal/pub_generated/test/build/outputs_error_to_json_test.dart
deleted file mode 100644
index 38f42bd..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/outputs_error_to_json_test.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) => throw new Exception('oh no!');
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("outputs error to JSON in a failed build", () {
- // Loading transformers takes several seconds, so make sure we don't
- // timeout.
- currentSchedule.timeout *= 2;
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp"]
- }),
- d.dir("lib", [d.file("transformer.dart", TRANSFORMER)]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- schedulePub(args: ["build", "--format", "json"], outputJson: {
- "buildResult": "failure",
- "errors": [{
- "error": startsWith(
- "Transform Rewrite on myapp|web/foo.txt " "threw error: oh no!")
- }],
- "log": []
- }, exitCode: exit_codes.DATA);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/outputs_results_to_json_test.dart b/sdk/lib/_internal/pub_generated/test/build/outputs_results_to_json_test.dart
deleted file mode 100644
index 8eff17d..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/outputs_results_to_json_test.dart
+++ /dev/null
@@ -1,75 +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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- integration("outputs results to JSON in a successful build", () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- 'web',
- [d.file('main.dart', 'void main() => print("hello");')])]).create();
-
- schedulePub(args: ["build", "--format", "json"], outputJson: {
- 'buildResult': 'success',
- 'outputDirectory': 'build',
- 'numFiles': 1,
- 'log': [{
- 'level': 'Info',
- 'transformer': {
- 'name': 'Dart2JS',
- 'primaryInput': {
- 'package': 'myapp',
- 'path': 'web/main.dart'
- }
- },
- 'assetId': {
- 'package': 'myapp',
- 'path': 'web/main.dart'
- },
- 'message': 'Compiling myapp|web/main.dart...'
- }, {
- 'level': 'Info',
- 'transformer': {
- 'name': 'Dart2JS',
- 'primaryInput': {
- 'package': 'myapp',
- 'path': 'web/main.dart'
- }
- },
- 'assetId': {
- 'package': 'myapp',
- 'path': 'web/main.dart'
- },
- 'message': contains(r'to compile myapp|web/main.dart.')
- }, {
- 'level': 'Fine',
- 'transformer': {
- 'name': 'Dart2JS',
- 'primaryInput': {
- 'package': 'myapp',
- 'path': 'web/main.dart'
- }
- },
- 'assetId': {
- 'package': 'myapp',
- 'path': 'web/main.dart'
- },
- 'message': contains(r'Took')
- }]
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/preserves_htaccess_test.dart b/sdk/lib/_internal/pub_generated/test/build/preserves_htaccess_test.dart
deleted file mode 100644
index 7453adf..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/preserves_htaccess_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2013, 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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- integration("preserves .htaccess as a special case", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- 'web',
- [d.file('.htaccess', 'fblthp'), d.file('.hidden', 'asdfgh')])]).create();
-
- schedulePub(
- args: ["build"],
- output: new RegExp(r'Built \d+ files? to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [d.file('.htaccess', 'fblthp'), d.nothing('.hidden')])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/build/utils.dart b/sdk/lib/_internal/pub_generated/test/build/utils.dart
deleted file mode 100644
index 6160c5e..0000000
--- a/sdk/lib/_internal/pub_generated/test/build/utils.dart
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-/// Runs the hosted test server and serves a valid "browser" package that
-/// contains the same files (but not their contents) as the real browser
-/// package.
-void serveBrowserPackage() {
- serve([d.dir('api', [d.dir('packages', [d.file('browser', JSON.encode({
- 'versions': [packageVersionApiMap(packageMap('browser', '1.0.0'))]
- })),
- d.dir(
- 'browser',
- [
- d.dir(
- 'versions',
- [
- d.file(
- '1.0.0',
- JSON.encode(
- packageVersionApiMap(packageMap('browser', '1.0.0'), full: true)))])])])]),
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.dir(
- 'versions',
- [
- d.tar(
- '1.0.0.tar.gz',
- [
- d.file('pubspec.yaml', yaml(packageMap("browser", "1.0.0"))),
- d.dir(
- 'lib',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])])])])])]);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_matching_version_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_matching_version_test.dart
deleted file mode 100644
index cea5e2c..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_matching_version_test.dart
+++ /dev/null
@@ -1,35 +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.
-
-library pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'adds the latest version of the package matching the ' 'version constraint',
- () {
- servePackages((builder) {
- builder.serve("foo", "1.2.2");
- builder.serve("foo", "1.2.3");
- builder.serve("foo", "2.0.0-dev");
- builder.serve("foo", "2.0.0");
- });
-
- schedulePub(
- args: ["cache", "add", "foo", "-v", ">=1.0.0 <2.0.0"],
- output: 'Downloading foo 1.2.3...');
-
- d.cacheDir({
- "foo": "1.2.3"
- }).validate();
- d.hostedCache(
- [
- d.nothing("foo-1.2.2"),
- d.nothing("foo-2.0.0-dev"),
- d.nothing("foo-2.0.0")]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_version_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_version_test.dart
deleted file mode 100644
index 8d27b95..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_version_test.dart
+++ /dev/null
@@ -1,27 +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.
-
-library pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('adds the latest stable version of the package', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.2");
- builder.serve("foo", "1.2.3");
- builder.serve("foo", "1.2.4-dev");
- });
-
- schedulePub(
- args: ["cache", "add", "foo"],
- output: 'Downloading foo 1.2.3...');
-
- d.cacheDir({
- "foo": "1.2.3"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/all_adds_all_matching_versions_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/all_adds_all_matching_versions_test.dart
deleted file mode 100644
index 9d29936..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/all_adds_all_matching_versions_test.dart
+++ /dev/null
@@ -1,37 +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.
-
-library pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('"--all" adds all matching versions of the package', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.2");
- builder.serve("foo", "1.2.3-dev");
- builder.serve("foo", "1.2.3");
- builder.serve("foo", "2.0.0");
- });
-
- schedulePub(
- args: ["cache", "add", "foo", "-v", ">=1.0.0 <2.0.0", "--all"],
- output: '''
- Downloading foo 1.2.2...
- Downloading foo 1.2.3-dev...
- Downloading foo 1.2.3...''');
-
- d.cacheDir({
- "foo": "1.2.2"
- }).validate();
- d.cacheDir({
- "foo": "1.2.3-dev"
- }).validate();
- d.cacheDir({
- "foo": "1.2.3"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/all_with_some_versions_present_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/all_with_some_versions_present_test.dart
deleted file mode 100644
index bdfd5eb..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/all_with_some_versions_present_test.dart
+++ /dev/null
@@ -1,49 +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.
-
-library pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('"--all" adds all non-installed versions of the package', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.1");
- builder.serve("foo", "1.2.2");
- builder.serve("foo", "1.2.3");
- builder.serve("foo", "2.0.0");
- });
-
- // Install a couple of versions first.
- schedulePub(
- args: ["cache", "add", "foo", "-v", "1.2.1"],
- output: 'Downloading foo 1.2.1...');
-
- schedulePub(
- args: ["cache", "add", "foo", "-v", "1.2.3"],
- output: 'Downloading foo 1.2.3...');
-
- // They should show up as already installed now.
- schedulePub(args: ["cache", "add", "foo", "--all"], output: '''
- Already cached foo 1.2.1.
- Downloading foo 1.2.2...
- Already cached foo 1.2.3.
- Downloading foo 2.0.0...''');
-
- d.cacheDir({
- "foo": "1.2.1"
- }).validate();
- d.cacheDir({
- "foo": "1.2.2"
- }).validate();
- d.cacheDir({
- "foo": "1.2.3"
- }).validate();
- d.cacheDir({
- "foo": "2.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/already_cached_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/already_cached_test.dart
deleted file mode 100644
index dad15da..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/already_cached_test.dart
+++ /dev/null
@@ -1,31 +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.
-
-library pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('does nothing if the package is already cached', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3");
- });
-
- // Run once to put it in the cache.
- schedulePub(
- args: ["cache", "add", "foo"],
- output: 'Downloading foo 1.2.3...');
-
- // Should be in the cache now.
- schedulePub(
- args: ["cache", "add", "foo"],
- output: 'Already cached foo 1.2.3.');
-
- d.cacheDir({
- "foo": "1.2.3"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/bad_version_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/bad_version_test.dart
deleted file mode 100644
index 322aefe..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/bad_version_test.dart
+++ /dev/null
@@ -1,25 +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.
-
-library pub_tests;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if the version constraint cannot be parsed', () {
- schedulePub(args: ["cache", "add", "foo", "-v", "1.0"], error: """
- Could not parse version "1.0". Unknown text at "1.0".
-
- Usage: pub cache add <package> [--version <constraint>] [--all]
- -h, --help Print this usage information.
- --all Install all matching versions.
- -v, --version Version constraint.
-
- Run "pub help" to see global options.
- See http://dartlang.org/tools/pub/cmd/pub-cache.html for detailed documentation.
- """, exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/missing_package_arg_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/missing_package_arg_test.dart
deleted file mode 100644
index d2a593d..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/missing_package_arg_test.dart
+++ /dev/null
@@ -1,25 +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.
-
-library pub_tests;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if no package was given', () {
- schedulePub(args: ["cache", "add"], error: """
- No package to add given.
-
- Usage: pub cache add <package> [--version <constraint>] [--all]
- -h, --help Print this usage information.
- --all Install all matching versions.
- -v, --version Version constraint.
-
- Run "pub help" to see global options.
- See http://dartlang.org/tools/pub/cmd/pub-cache.html for detailed documentation.
- """, exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/no_matching_version_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/no_matching_version_test.dart
deleted file mode 100644
index dba517a..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/no_matching_version_test.dart
+++ /dev/null
@@ -1,22 +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.
-
-library pub_tests;
-
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if no version matches the version constraint', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.2");
- builder.serve("foo", "1.2.3");
- });
-
- schedulePub(
- args: ["cache", "add", "foo", "-v", ">2.0.0"],
- error: 'Package foo has no versions that match >2.0.0.',
- exitCode: 1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/package_not_found_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/package_not_found_test.dart
deleted file mode 100644
index 1a6b87b..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/package_not_found_test.dart
+++ /dev/null
@@ -1,20 +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.
-
-library pub_tests;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if the package cound not be found on the source', () {
- serveNoPackages();
-
- schedulePub(
- args: ["cache", "add", "foo"],
- error: new RegExp(r"Could not find package foo at http://.*"),
- exitCode: exit_codes.UNAVAILABLE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/unexpected_arguments_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/unexpected_arguments_test.dart
deleted file mode 100644
index add07de..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/add/unexpected_arguments_test.dart
+++ /dev/null
@@ -1,25 +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.
-
-library pub_tests;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if there are extra arguments', () {
- schedulePub(args: ["cache", "add", "foo", "bar", "baz"], error: """
- Unexpected arguments "bar" and "baz".
-
- Usage: pub cache add <package> [--version <constraint>] [--all]
- -h, --help Print this usage information.
- --all Install all matching versions.
- -v, --version Version constraint.
-
- Run "pub help" to see global options.
- See http://dartlang.org/tools/pub/cmd/pub-cache.html for detailed documentation.
- """, exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/list_test.dart b/sdk/lib/_internal/pub_generated/test/cache/list_test.dart
deleted file mode 100644
index b3e4459..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/list_test.dart
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright (c) 2013, 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 pub_cache_test;
-
-import 'package:path/path.dart' as path;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- hostedDir(package) {
- return path.join(
- sandboxDir,
- cachePath,
- "hosted",
- "pub.dartlang.org",
- package);
- }
-
- integration('running pub cache list when there is no cache', () {
- schedulePub(args: ['cache', 'list'], output: '{"packages":{}}');
- });
-
- integration('running pub cache list on empty cache', () {
- // Set up a cache.
- d.dir(
- cachePath,
- [d.dir('hosted', [d.dir('pub.dartlang.org', [])])]).create();
-
- schedulePub(args: ['cache', 'list'], outputJson: {
- "packages": {}
- });
- });
-
- integration('running pub cache list', () {
- // Set up a cache.
- d.dir(
- cachePath,
- [
- d.dir(
- 'hosted',
- [
- d.dir(
- 'pub.dartlang.org',
- [
- d.dir("foo-1.2.3", [d.libPubspec("foo", "1.2.3"), d.libDir("foo")]),
- d.dir(
- "bar-2.0.0",
- [d.libPubspec("bar", "2.0.0"), d.libDir("bar")])])])]).create();
-
- schedulePub(args: ['cache', 'list'], outputJson: {
- "packages": {
- "bar": {
- "2.0.0": {
- "location": hostedDir('bar-2.0.0')
- }
- },
- "foo": {
- "1.2.3": {
- "location": hostedDir('foo-1.2.3')
- }
- }
- }
- });
- });
-
- integration('includes packages containing deps with bad sources', () {
- // Set up a cache.
- d.dir(
- cachePath,
- [
- d.dir(
- 'hosted',
- [
- d.dir(
- 'pub.dartlang.org',
- [d.dir("foo-1.2.3", [d.libPubspec("foo", "1.2.3", deps: {
- "bar": {
- "bad": "bar"
- }
- }), d.libDir("foo")])])])]).create();
-
- schedulePub(args: ['cache', 'list'], outputJson: {
- "packages": {
- "foo": {
- "1.2.3": {
- "location": hostedDir('foo-1.2.3')
- }
- }
- }
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/empty_cache_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/empty_cache_test.dart
deleted file mode 100644
index 3588ea1..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/empty_cache_test.dart
+++ /dev/null
@@ -1,17 +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.
-
-library pub_tests;
-
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('does nothing if the cache is empty', () {
- // Repair them.
- schedulePub(
- args: ["cache", "repair"],
- output: "No packages in cache, so nothing to repair.");
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_binstub_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_binstub_test.dart
deleted file mode 100644
index 51c4deb..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_binstub_test.dart
+++ /dev/null
@@ -1,35 +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.
-
-library pub_tests;
-
-import 'dart:io';
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('handles a corrupted binstub script', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [d.dir('bin', [d.file(binStubName('script'), 'junk')])]).create();
-
- schedulePub(
- args: ["cache", "repair"],
- error: contains('Error reading binstub for "script":'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_global_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_global_lockfile_test.dart
deleted file mode 100644
index 9839e64..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_global_lockfile_test.dart
+++ /dev/null
@@ -1,24 +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.
-
-library pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('handles a corrupted global lockfile', () {
- d.dir(
- cachePath,
- [d.dir('global_packages/foo', [d.file('pubspec.lock', 'junk')])]).create();
-
- schedulePub(
- args: ["cache", "repair"],
- error: contains('Failed to reactivate foo:'),
- output: contains('Failed to reactivate 1 package.'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_failure_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/handles_failure_test.dart
deleted file mode 100644
index 54f953a..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_failure_test.dart
+++ /dev/null
@@ -1,56 +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.
-
-library pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('handles failure to reinstall some packages', () {
- // Only serve two packages so repairing will have a failure.
- servePackages((builder) {
- builder.serve("foo", "1.2.3");
- builder.serve("foo", "1.2.5");
- });
-
- // Set up a cache with some packages.
- d.dir(
- cachePath,
- [
- d.dir(
- 'hosted',
- [
- d.async(
- port.then(
- (p) =>
- d.dir(
- 'localhost%58$p',
- [
- d.dir("foo-1.2.3", [d.libPubspec("foo", "1.2.3"), d.file("broken.txt")]),
- d.dir("foo-1.2.4", [d.libPubspec("foo", "1.2.4"), d.file("broken.txt")]),
- d.dir(
- "foo-1.2.5",
- [d.libPubspec("foo", "1.2.5"), d.file("broken.txt")])])))])]).create();
-
- // Repair them.
- var pub = startPub(args: ["cache", "repair"]);
-
- pub.stdout.expect("Downloading foo 1.2.3...");
- pub.stdout.expect("Downloading foo 1.2.4...");
- pub.stdout.expect("Downloading foo 1.2.5...");
-
- pub.stderr.expect(startsWith("Failed to repair foo 1.2.4. Error:"));
- pub.stderr.expect("HTTP error 404: Not Found");
-
- pub.stdout.expect("Reinstalled 2 packages.");
- pub.stdout.expect("Failed to reinstall 1 package.");
-
- pub.shouldExit(exit_codes.UNAVAILABLE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_orphaned_binstub_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/handles_orphaned_binstub_test.dart
deleted file mode 100644
index 56f48ad..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_orphaned_binstub_test.dart
+++ /dev/null
@@ -1,36 +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.
-
-library pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-const _ORPHANED_BINSTUB = """
-#!/usr/bin/env sh
-# This file was created by pub v0.1.2-3.
-# Package: foo
-# Version: 1.0.0
-# Executable: foo-script
-# Script: script
-dart "/path/to/.pub-cache/global_packages/foo/bin/script.dart.snapshot" "\$@"
-""";
-
-main() {
- initConfig();
- integration('handles an orphaned binstub script', () {
- d.dir(
- cachePath,
- [d.dir('bin', [d.file(binStubName('script'), _ORPHANED_BINSTUB)])]).create();
-
- schedulePub(
- args: ["cache", "repair"],
- error: allOf(
- [
- contains('Binstubs exist for non-activated packages:'),
- contains('From foo: foo-script')]));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/recompiles_snapshots_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/recompiles_snapshots_test.dart
deleted file mode 100644
index bb8f6c8..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/recompiles_snapshots_test.dart
+++ /dev/null
@@ -1,45 +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.
-
-library pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('recompiles activated executable snapshots', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages/foo/bin',
- [d.file('script.dart.snapshot', 'junk')])]).create();
-
- schedulePub(args: ["cache", "repair"], output: '''
- Downloading foo 1.0.0...
- Reinstalled 1 package.
- Reactivating foo 1.0.0...
- Precompiling executables...
- Loading source assets...
- Precompiled foo:script.
- Reactivated 1 package.''');
-
- var pub = pubRun(global: true, args: ["foo:script"]);
- pub.stdout.expect("ok");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_git_packages_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_git_packages_test.dart
deleted file mode 100644
index a71e10d..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_git_packages_test.dart
+++ /dev/null
@@ -1,63 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('reinstalls previously cached git packages', () {
- // Create two cached revisions of foo.
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
- pubGet();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.1')]).commit();
-
- pubUpgrade();
-
- // Break them.
- var fooDirs;
- schedule(() {
- // Find the cached foo packages for each revision.
- var gitCacheDir = path.join(sandboxDir, cachePath, "git");
- fooDirs = listDir(
- gitCacheDir).where((dir) => path.basename(dir).startsWith("foo-")).toList();
-
- // Delete "foo.dart" from them.
- for (var dir in fooDirs) {
- deleteEntry(path.join(dir, "lib", "foo.dart"));
- }
- });
-
- // Repair them.
- schedulePub(args: ["cache", "repair"], output: '''
- Resetting Git repository for foo 1.0.0...
- Resetting Git repository for foo 1.0.1...
- Reinstalled 2 packages.''');
-
- // The missing libraries should have been replaced.
- schedule(() {
- var fooLibs = fooDirs.map((dir) {
- var fooDirName = path.basename(dir);
- return d.dir(
- fooDirName,
- [d.dir("lib", [d.file("foo.dart", 'main() => "foo";')])]);
- }).toList();
-
- d.dir(cachePath, [d.dir("git", fooLibs)]).validate();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_hosted_packages_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_hosted_packages_test.dart
deleted file mode 100644
index ddac6de..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_hosted_packages_test.dart
+++ /dev/null
@@ -1,54 +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.
-
-library pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('reinstalls previously cached hosted packages', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3");
- builder.serve("foo", "1.2.4");
- builder.serve("foo", "1.2.5");
- builder.serve("bar", "1.2.3");
- builder.serve("bar", "1.2.4");
- });
-
- // Set up a cache with some broken packages.
- d.dir(
- cachePath,
- [
- d.dir(
- 'hosted',
- [
- d.async(
- port.then(
- (p) =>
- d.dir(
- 'localhost%58$p',
- [
- d.dir("foo-1.2.3", [d.libPubspec("foo", "1.2.3"), d.file("broken.txt")]),
- d.dir("foo-1.2.5", [d.libPubspec("foo", "1.2.5"), d.file("broken.txt")]),
- d.dir(
- "bar-1.2.4",
- [d.libPubspec("bar", "1.2.4"), d.file("broken.txt")])])))])]).create();
-
- // Repair them.
- schedulePub(args: ["cache", "repair"], output: '''
- Downloading bar 1.2.4...
- Downloading foo 1.2.3...
- Downloading foo 1.2.5...
- Reinstalled 3 packages.''');
-
- // The broken versions should have been replaced.
- d.hostedCache(
- [
- d.dir("bar-1.2.4", [d.nothing("broken.txt")]),
- d.dir("foo-1.2.3", [d.nothing("broken.txt")]),
- d.dir("foo-1.2.5", [d.nothing("broken.txt")])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/updates_binstubs_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/updates_binstubs_test.dart
deleted file mode 100644
index 874796e..0000000
--- a/sdk/lib/_internal/pub_generated/test/cache/repair/updates_binstubs_test.dart
+++ /dev/null
@@ -1,61 +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.
-
-library pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-const _OUTDATED_BINSTUB = """
-#!/usr/bin/env sh
-# This file was created by pub v0.1.2-3.
-# Package: foo
-# Version: 1.0.0
-# Executable: foo-script
-# Script: script
-dart "/path/to/.pub-cache/global_packages/foo/bin/script.dart.snapshot" "\$@"
-""";
-
-main() {
- initConfig();
- integration('updates an outdated binstub script', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "foo-script": "script"
- }
- },
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir('bin', [d.file(binStubName('foo-script'), _OUTDATED_BINSTUB)])]).create();
-
- // Repair them.
- schedulePub(args: ["cache", "repair"], output: '''
- Downloading foo 1.0.0...
- Reinstalled 1 package.
- Reactivating foo 1.0.0...
- Precompiling executables...
- Loading source assets...
- Precompiled foo:script.
- Installed executable foo-script.
- Reactivated 1 package.''');
-
- // The broken versions should have been replaced.
- d.dir(
- cachePath,
- [d.dir('bin', [// 255 is the VM's exit code upon seeing an out-of-date snapshot.
- d.matcherFile(
- binStubName('foo-script'),
- contains('255'))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/allows_import_in_dart_code_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/allows_import_in_dart_code_test.dart
deleted file mode 100644
index 5f8cadc..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/allows_import_in_dart_code_test.dart
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("handles imports in the Dart code", () {
- d.dir(
- "foo",
- [d.libPubspec("foo", "0.0.1"), d.dir("lib", [d.file("foo.dart", """
-library foo;
-foo() => 'footext';
-""")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }), d.dir("lib", [d.file("lib.dart", """
-library lib;
-lib() => 'libtext';
-""")]), d.dir("web", [d.file("main.dart", """
-import 'package:foo/foo.dart';
-import 'package:myapp/lib.dart';
-void main() {
- print(foo());
- print(lib());
-}
-""")])]).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("main.dart.js", contains("footext"));
- requestShouldSucceed("main.dart.js", contains("libtext"));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_entrypoints_in_root_package_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_entrypoints_in_root_package_test.dart
deleted file mode 100644
index 6fb2e5e..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_entrypoints_in_root_package_test.dart
+++ /dev/null
@@ -1,86 +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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("compiles Dart entrypoints in root package to JS", () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- 'benchmark',
- [
- d.file('file.dart', 'void main() => print("hello");'),
- d.file('lib.dart', 'void foo() => print("hello");'),
- d.dir('subdir', [d.file('subfile.dart', 'void main() => print("ping");')])]),
- d.dir(
- 'foo',
- [
- d.file('file.dart', 'void main() => print("hello");'),
- d.file('lib.dart', 'void foo() => print("hello");'),
- d.dir('subdir', [d.file('subfile.dart', 'void main() => print("ping");')])]),
- d.dir(
- 'web',
- [
- d.file('file.dart', 'void main() => print("hello");'),
- d.file('lib.dart', 'void foo() => print("hello");'),
- d.dir(
- 'subdir',
- [d.file('subfile.dart', 'void main() => print("ping");')])])]).create();
-
- schedulePub(
- args: ["build", "benchmark", "foo", "web"],
- output: new RegExp(r'Built 6 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'benchmark',
- [
- d.matcherFile('file.dart.js', isNot(isEmpty)),
- d.nothing('file.dart'),
- d.nothing('lib.dart'),
- d.dir(
- 'subdir',
- [
- d.matcherFile('subfile.dart.js', isNot(isEmpty)),
- d.nothing('subfile.dart')])]),
- d.dir(
- 'foo',
- [
- d.matcherFile('file.dart.js', isNot(isEmpty)),
- d.nothing('file.dart'),
- d.nothing('lib.dart'),
- d.dir(
- 'subdir',
- [
- d.matcherFile('subfile.dart.js', isNot(isEmpty)),
- d.nothing('subfile.dart')])]),
- d.dir(
- 'web',
- [
- d.matcherFile('file.dart.js', isNot(isEmpty)),
- d.nothing('file.dart'),
- d.nothing('lib.dart'),
- d.dir(
- 'subdir',
- [
- d.matcherFile('subfile.dart.js', isNot(isEmpty)),
- d.nothing('subfile.dart')])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_dart_file_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_dart_file_test.dart
deleted file mode 100644
index 0354e43..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_dart_file_test.dart
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("compiles a generated Dart file to JS", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "version": "0.0.1",
- "transformers": ["myapp/transformer"]
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer("munge"))]),
- d.dir("web", [d.file("main.dart", """
-const TOKEN = "before";
-void main() => print(TOKEN);
-""")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("main.dart.js", contains("(before, munge)"));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_outside_web_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_outside_web_test.dart
deleted file mode 100644
index 494e7ad..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_outside_web_test.dart
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- // This is a regression test for issue #17198.
- initConfig();
- withBarbackVersions("any", () {
- integration(
- "compiles a Dart file that imports a generated file to JS " "outside web/",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "version": "0.0.1",
- "transformers": ["myapp/transformer"]
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer("munge"))]),
- d.dir("test", [d.file("main.dart", """
-import "other.dart";
-void main() => print(TOKEN);
-"""), d.file("other.dart", """
-library other;
-const TOKEN = "before";
-""")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe(args: ["test"]);
- requestShouldSucceed(
- "main.dart.js",
- contains("(before, munge)"),
- root: "test");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_test.dart
deleted file mode 100644
index 36416ec..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration(
- "compiles a Dart file that imports a generated file in another "
- "package to JS",
- () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "0.0.1",
- "transformers": ["foo/transformer"]
- }), d.dir("lib", [d.file("foo.dart", """
-library foo;
-const TOKEN = "before";
-foo() => TOKEN;
-"""), d.file("transformer.dart", dartTransformer("munge"))])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }), d.dir("web", [d.file("main.dart", """
-import "package:foo/foo.dart";
-main() => print(foo());
-""")])]).create();
-
- createLockFile("myapp", sandbox: ["foo"], pkg: ["barback"]);
-
- pubServe();
- requestShouldSucceed("main.dart.js", contains("(before, munge)"));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_imported_generated_file_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_imported_generated_file_test.dart
deleted file mode 100644
index d86c91c..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_imported_generated_file_test.dart
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("compiles a Dart file that imports a generated file to JS", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "version": "0.0.1",
- "transformers": ["myapp/transformer"]
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer("munge"))]),
- d.dir("web", [d.file("main.dart", """
-import "other.dart";
-void main() => print(TOKEN);
-"""), d.file("other.dart", """
-library other;
-const TOKEN = "before";
-""")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("main.dart.js", contains("(before, munge)"));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/converts_isolate_entrypoint_in_web_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/converts_isolate_entrypoint_in_web_test.dart
deleted file mode 100644
index 941add5..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/converts_isolate_entrypoint_in_web_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("converts a Dart isolate entrypoint in web to JS", () {
- // Increase the timeout because dart2js takes a lot longer than usual to
- // compile isolate entrypoints.
- currentSchedule.timeout *= 2;
-
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.file(
- "isolate.dart",
- "void main(List<String> args, SendPort "
- "sendPort) => print('hello');")])]).create();
-
- pubServe();
- requestShouldSucceed("isolate.dart.js", contains("hello"));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_if_disabled_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_if_disabled_test.dart
deleted file mode 100644
index 6de1fdc..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_if_disabled_test.dart
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("does not compile if dart2js is disabled", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('hello');")])]).create();
-
- pubServe(args: ["--no-dart2js"]);
- requestShould404("main.dart.js");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_until_its_output_is_requested_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_until_its_output_is_requested_test.dart
deleted file mode 100644
index 54dadb2..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_until_its_output_is_requested_test.dart
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_stream.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("does not compile until its output is requested", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "version": "0.0.1",
- }),
- d.dir("web", [d.file("syntax-error.dart", "syntax error")])]).create();
-
- var server = pubServe();
- server.stdout.expect("Build completed successfully");
-
- // Once we request the output, it should start compiling and fail.
- requestShould404("syntax-error.dart.js");
- server.stdout.expect(
- emitsLines(
- "[Info from Dart2JS]:\n" "Compiling myapp|web/syntax-error.dart..."));
- server.stdout.expect(consumeThrough("Build completed with 1 errors."));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_command_line_options_type_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_command_line_options_type_test.dart
deleted file mode 100644
index 0bcc372..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_command_line_options_type_test.dart
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("doesn't support invalid commandLineOptions type", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "\$dart2js": {
- "commandLineOptions": "foo",
- }
- }]
- }), d.dir("web", [d.file("main.dart", "void main() {}")])]).create();
-
- var server = pubServe();
- // Make a request first to trigger compilation.
- requestShould404("main.dart.js");
- server.stderr.expect(
- emitsLines(
- 'Build error:\n' 'Transform Dart2JS on myapp|web/main.dart threw error: '
- 'Invalid value for \$dart2js.commandLineOptions: '
- '"foo" (expected list of strings).'));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_environment_type_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_environment_type_test.dart
deleted file mode 100644
index 7cb55fb..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_environment_type_test.dart
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("doesn't support invalid environment type", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "\$dart2js": {
- "environment": "foo",
- }
- }]
- }), d.dir("web", [d.file("main.dart", "void main() {}")])]).create();
-
- var server = pubServe();
- // Make a request first to trigger compilation.
- requestShould404("main.dart.js");
- server.stderr.expect(
- emitsLines(
- 'Build error:\n' 'Transform Dart2JS on myapp|web/main.dart threw error: '
- 'Invalid value for \$dart2js.environment: "foo" '
- '(expected map from strings to strings).'));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_option_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_option_test.dart
deleted file mode 100644
index 6d3fb7e..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_option_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("doesn't support an invalid dart2js option", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "\$dart2js": {
- "invalidOption": true
- }
- }]
- })]).create();
-
- // TODO(nweiz): This should provide more context about how the option got
- // passed to dart2js. See issue 16008.
- var pub = startPubServe();
- pub.stderr.expect('Unrecognized dart2js option "invalidOption".');
- pub.shouldExit(exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/doesnt_support_invalid_type_for_boolean_option_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/doesnt_support_invalid_type_for_boolean_option_test.dart
deleted file mode 100644
index 61f5cc9..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/doesnt_support_invalid_type_for_boolean_option_test.dart
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("doesn't support invalid type for boolean option", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "\$dart2js": {
- "checked": "foo",
- }
- }]
- }), d.dir("web", [d.file("main.dart", "void main() {}")])]).create();
-
- var server = pubServe();
- requestShould404("main.dart.js");
- server.stderr.expect(
- emitsLines(
- 'Build error:\n' 'Transform Dart2JS on myapp|web/main.dart threw error: '
- 'Invalid value for \$dart2js.checked: "foo" ' '(expected true or false).'));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoint_in_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoint_in_dependency_test.dart
deleted file mode 100644
index 43ff042..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoint_in_dependency_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("ignores a Dart entrypoint in a dependency", () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "0.0.1"),
- d.dir("lib", [d.file("lib.dart", "main() => print('foo');")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubServe(shouldGetFirst: true);
- requestShould404("web/packages/foo/lib.dart.js");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoints_in_lib_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoints_in_lib_test.dart
deleted file mode 100644
index 4c1a880..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoints_in_lib_test.dart
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- setUp(() {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir('lib', [d.file('file.dart', 'void main() => print("hello");'),]),
- d.dir('web', [d.file('index.html', 'html'),])]).create();
- });
-
- integration("build ignores Dart entrypoints in lib", () {
- schedulePub(
- args: ["build", "--all"],
- output: new RegExp(r'Built 1 file to "build".'));
-
- d.dir(appPath, [d.dir('build', [d.nothing('lib')])]).validate();
- });
-
- integration("serve ignores Dart entrypoints in lib", () {
- pubServe();
- requestShould404("packages/myapp/main.dart.js");
- endPubServe();
- });
-
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_non_entrypoint_dart_files_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/ignores_non_entrypoint_dart_files_test.dart
deleted file mode 100644
index bf2bdb9..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_non_entrypoint_dart_files_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- setUp(() {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- 'web',
- [
- d.file('file1.dart', 'var main = () => print("hello");'),
- d.file('file2.dart', 'void main(arg1, arg2, arg3) => print("hello");'),
- d.file('file3.dart', 'class Foo { void main() => print("hello"); }'),
- d.file('file4.dart', 'var foo;')])]).create();
- });
-
- integration("build ignores non-entrypoint Dart files", () {
- schedulePub(
- args: ["build"],
- output: new RegExp(r'Built 0 files to "build".'));
-
- d.dir(appPath, [d.dir('build', [d.nothing('web')])]).validate();
- });
-
- integration("serve ignores non-entrypoint Dart files", () {
- pubServe();
- requestShould404("file1.dart.js");
- requestShould404("file2.dart.js");
- requestShould404("file3.dart.js");
- requestShould404("file4.dart.js");
- endPubServe();
- });
-
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_if_sourceMaps_true_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_if_sourceMaps_true_test.dart
deleted file mode 100644
index f8ebaec..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_if_sourceMaps_true_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("includes source maps in a release build if sourceMaps true", () {
- d.dir(appPath, [d.pubspec({
- 'name': 'myapp',
- 'transformers': [{
- '\$dart2js': {
- 'sourceMaps': true
- }
- }]
- }),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('hello');")])]).create();
-
- schedulePub(
- args: ["build"],
- output: new RegExp(r'Built \d+ files to "build".'),
- exitCode: 0);
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.matcherFile('main.dart.js', contains("# sourceMappingURL=main.dart.js.map")),
- d.matcherFile(
- 'main.dart.js.map',
- contains('"file": "main.dart.js"'))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_in_debug_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_in_debug_test.dart
deleted file mode 100644
index 4e5d9e8..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_in_debug_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("includes source map URLs in a debug build", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('hello');")])]).create();
-
- schedulePub(
- args: ["build", "--mode", "debug"],
- output: new RegExp(r'Built \d+ files to "build".'),
- exitCode: 0);
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.matcherFile('main.dart.js', contains("# sourceMappingURL=main.dart.js.map")),
- d.matcherFile(
- 'main.dart.js.map',
- contains('"file": "main.dart.js"'))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/minifies_in_release_mode_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/minifies_in_release_mode_test.dart
deleted file mode 100644
index 147c41f..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/minifies_in_release_mode_test.dart
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("generates minified JS in release mode", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('hello');")])]).create();
-
- pubServe(args: ["--mode", "release"]);
- requestShouldSucceed("main.dart.js", isMinifiedDart2JSOutput);
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/minify_configuration_overrides_mode_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/minify_configuration_overrides_mode_test.dart
deleted file mode 100644
index eca9f08..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/minify_configuration_overrides_mode_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("minify configuration overrides the mode", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "\$dart2js": {
- "minify": true
- }
- }]
- }),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('Hello!');")])]).create();
-
- pubServe();
- requestShouldSucceed("main.dart.js", isMinifiedDart2JSOutput);
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_if_sourceMaps_false_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_if_sourceMaps_false_test.dart
deleted file mode 100644
index f777b91..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_if_sourceMaps_false_test.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("omits source maps from a debug build if sourceMaps false", () {
- d.dir(appPath, [d.pubspec({
- 'name': 'myapp',
- 'transformers': [{
- '\$dart2js': {
- 'sourceMaps': false
- }
- }]
- }),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('hello');")])]).create();
-
- schedulePub(
- args: ["build", "--mode", "debug"],
- output: new RegExp(r'Built \d+ files to "build".'),
- exitCode: 0);
-
- d.dir(
- appPath,
- [d.dir('build', [d.dir('web', [d.nothing('main.dart.js.map')])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_in_release_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_in_release_test.dart
deleted file mode 100644
index 248d2a2..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_in_release_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("omits source maps from a release build", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('hello');")])]).create();
-
- schedulePub(
- args: ["build"],
- output: new RegExp(r'Built 1 file to "build".'),
- exitCode: 0);
-
- d.dir(
- appPath,
- [d.dir('build', [d.dir('web', [d.nothing('main.dart.js.map')])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/output_can_be_consumed_by_successive_phases.dart b/sdk/lib/_internal/pub_generated/test/dart2js/output_can_be_consumed_by_successive_phases.dart
deleted file mode 100644
index 76953f6..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/output_can_be_consumed_by_successive_phases.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-/// The code for a transformer that renames ".js" files to ".out".
-const JS_REWRITE_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.js';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, contents));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("output can be consumed by successive phases", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["\$dart2js", "myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [d.dir("src", [d.file("transformer.dart", JS_REWRITE_TRANSFORMER)])]),
- d.dir("web", [d.file("main.dart", "void main() {}")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("main.dart.out", isUnminifiedDart2JSOutput);
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/outputs_deferred_libraries_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/outputs_deferred_libraries_test.dart
deleted file mode 100644
index fc1ac70..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/outputs_deferred_libraries_test.dart
+++ /dev/null
@@ -1,71 +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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const MAIN = """
-import 'dart:async';
-
-import 'a.dart' deferred as a;
-import 'b.dart' deferred as b;
-
-void main() {
- Future.wait([lazyA.loadLibrary(), lazyB.loadLibrary()]).then((_) {
- a.fn();
- b.fn();
- });
-}
-""";
-
-const A = """
-library a;
-
-fn() => print("a");
-""";
-
-const B = """
-library b;
-
-fn() => print("b");
-""";
-
-main() {
- initConfig();
- integration("compiles deferred libraries to separate outputs", () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- 'web',
- [
- d.file('main.dart', MAIN),
- d.file('a.dart', A),
- d.file('b.dart', B)])]).create();
-
- schedulePub(
- args: ["build"],
- output: new RegExp(r'Built 3 files to "build".'));
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.matcherFile('main.dart.js', isNot(isEmpty)),
- d.matcherFile('main.dart.js_1.part.js', isNot(isEmpty)),
- d.matcherFile('main.dart.js_2.part.js', isNot(isEmpty)),])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/passes_along_environment_constants_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/passes_along_environment_constants_test.dart
deleted file mode 100644
index 5245f86..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/passes_along_environment_constants_test.dart
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("passes along environment constants", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "\$dart2js": {
- "environment": {
- 'CONSTANT': 'true'
- }
- }
- }]
- }), d.dir("web", [d.file("main.dart", """
-void main() {
- if (const bool.fromEnvironment('CONSTANT')) {
- print("hello");
- }
-}
-""")])]).create();
-
- pubServe();
- requestShouldSucceed("main.dart.js", contains("hello"));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/reports_dart_parse_errors_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/reports_dart_parse_errors_test.dart
deleted file mode 100644
index 1c17de5..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/reports_dart_parse_errors_test.dart
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) 2013, 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:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("reports Dart parse errors", () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- 'web',
- [
- d.file('file.txt', 'contents'),
- d.file('file.dart', 'void void;'),
- d.dir('subdir', [d.file('subfile.dart', 'void void;')])])]).create();
-
- var pub = startPub(args: ["build"]);
- pub.stdout.expect(startsWith("Loading source assets..."));
- pub.stdout.expect(startsWith("Building myapp..."));
-
- var consumeFile = consumeThrough(
- inOrder(
- ["[Error from Dart2JS]:", startsWith(p.join("web", "file.dart") + ":")]));
- var consumeSubfile = consumeThrough(
- inOrder(
- [
- "[Error from Dart2JS]:",
- startsWith(p.join("web", "subdir", "subfile.dart") + ":")]));
-
- // It's nondeterministic what order the dart2js transformers start running,
- // so we allow the error messages to be emitted in either order.
- pub.stderr.expect(
- either(
- inOrder([consumeFile, consumeSubfile]),
- inOrder([consumeSubfile, consumeFile])));
-
- pub.shouldExit(exit_codes.DATA);
-
- // Doesn't output anything if an error occurred.
- d.dir(appPath, [d.dir('build', [d.nothing('web')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_in_subdirectory_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_in_subdirectory_test.dart
deleted file mode 100644
index 3a040fb..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_in_subdirectory_test.dart
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../serve/utils.dart';
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- // This test is a bit shaky. Since dart2js is free to inline things, it's
- // not precise as to which source libraries will actually be referenced in
- // the source map. But this tries to use a type in the core library
- // (StringBuffer) and validate that its source ends up in the source map.
- integration(
- "Dart core libraries are available to source maps when the "
- "build directory is a subdirectory",
- () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.dir(
- "sub",
- [
- d.file(
- "main.dart",
- "main() => new StringBuffer().writeAll(['s']);")])])]).create();
-
- var webSub = path.join("web", "sub");
- pubServe(args: [webSub]);
-
- requestShouldSucceed(
- "main.dart.js.map",
- contains(r"packages/$sdk/lib/core/string_buffer.dart"),
- root: webSub);
- requestShouldSucceed(
- r"packages/$sdk/lib/core/string_buffer.dart",
- contains("class StringBuffer"),
- root: webSub);
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_test.dart
deleted file mode 100644
index 6e0647f..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_test.dart
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- // This test is a bit shaky. Since dart2js is free to inline things, it's
- // not precise as to which source libraries will actually be referenced in
- // the source map. But this tries to use a type in the core library
- // (StringBuffer) and validate that its source ends up in the source map.
- integration("Dart core libraries are available to source maps", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.file("main.dart", "main() => new StringBuffer().writeAll(['s']);"),
- d.dir(
- "sub",
- [
- d.file(
- "main.dart",
- "main() => new StringBuffer().writeAll(['s']);")])])]).create();
-
- schedulePub(
- args: ["build", "--mode", "debug"],
- output: new RegExp(r'Built \d+ files to "build".'),
- exitCode: 0);
-
- d.dir(
- appPath,
- [
- d.dir(
- "build",
- [
- d.dir(
- "web",
- [
- d.matcherFile(
- "main.dart.js.map",
- contains(r"packages/$sdk/lib/core/string_buffer.dart")),
- d.dir(
- "sub",
- [
- d.matcherFile(
- "main.dart.js.map",
- contains(r"../packages/$sdk/lib/core/string_buffer.dart"))]),
- d.dir(
- "packages",
- [
- d.dir(
- r"$sdk",
- [
- d.dir(
- "lib",
- [
- d.dir(
- r"core",
- [
- d.matcherFile(
- "string_buffer.dart",
- contains("class StringBuffer"))])])])])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/supports_configuration_with_build_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/supports_configuration_with_build_test.dart
deleted file mode 100644
index 1c46412..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/supports_configuration_with_build_test.dart
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "compiles dart.js and interop.js next to entrypoints when "
- "dartjs is explicitly configured",
- () {
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 3;
-
- serve([d.dir('api', [d.dir('packages', [d.file('browser', JSON.encode({
- 'versions': [packageVersionApiMap(packageMap('browser', '1.0.0'))]
- })),
- d.dir(
- 'browser',
- [
- d.dir(
- 'versions',
- [
- d.file(
- '1.0.0',
- JSON.encode(
- packageVersionApiMap(packageMap('browser', '1.0.0'), full: true)))])])])]),
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.dir(
- 'versions',
- [
- d.tar(
- '1.0.0.tar.gz',
- [
- d.file('pubspec.yaml', yaml(packageMap("browser", "1.0.0"))),
- d.dir(
- 'lib',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])])])])])]);
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "browser": "1.0.0"
- },
- "transformers": [{
- "\$dart2js": {
- "minify": true
- }
- }]
- }),
- d.dir(
- 'web',
- [d.file('file.dart', 'void main() => print("hello");'),])]).create();
-
- pubGet();
-
- schedulePub(
- args: ["build"],
- output: new RegExp(r'Built 3 files to "build".'),
- exitCode: 0);
-
- d.dir(
- appPath,
- [
- d.dir(
- 'build',
- [
- d.dir(
- 'web',
- [
- d.matcherFile('file.dart.js', isMinifiedDart2JSOutput),
- d.dir(
- 'packages',
- [
- d.dir(
- 'browser',
- [
- d.file('dart.js', 'contents of dart.js'),
- d.file('interop.js', 'contents of interop.js')])]),])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/supports_valid_options_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/supports_valid_options_test.dart
deleted file mode 100644
index 1c43421..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/supports_valid_options_test.dart
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("supports most dart2js command-line options", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "\$dart2js": {
- "commandLineOptions": ["--enable-diagnostic-colors"],
- "checked": true,
- "csp": true,
- "minify": true,
- "verbose": true,
- "environment": {
- "name": "value"
- },
- "suppressWarnings": true,
- "suppressHints": true,
- "suppressPackageWarnings": false,
- "terse": true,
- "sourceMaps": false
- }
- }]
- }),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('Hello!');")])]).create();
-
- // None of these options should be rejected, either by pub or by dart2js.
- pubServe();
- requestShouldSucceed("main.dart.js", isNot(isEmpty));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/unminified_in_nonrelease_mode_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/unminified_in_nonrelease_mode_test.dart
deleted file mode 100644
index e312193..0000000
--- a/sdk/lib/_internal/pub_generated/test/dart2js/unminified_in_nonrelease_mode_test.dart
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- integration("generates unminified JS when not in release mode", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [d.file("main.dart", "void main() => print('hello');")])]).create();
-
- pubServe(args: ["--mode", "whatever"]);
- requestShouldSucceed("main.dart.js", isUnminifiedDart2JSOutput);
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/conservative_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/conservative_dependencies_test.dart
deleted file mode 100644
index 2e8cca0..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_computer/conservative_dependencies_test.dart
+++ /dev/null
@@ -1,522 +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.
-
-library pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-void main() {
- initConfig();
-
- integration(
- "reports previous transformers as dependencies if the "
- "transformer is transformed",
- () {
- // The root app just exists so that something is transformed by pkg and qux.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "version": "1.0.0",
- "dependencies": {
- "pkg": {
- "path": "../pkg"
- },
- "qux": {
- "path": "../qux"
- }
- },
- "transformers": ["pkg", "qux"]
- })]).create();
-
- d.dir("pkg", [d.pubspec({
- "name": "pkg",
- "version": "1.0.0",
- "dependencies": {
- "foo": {
- "path": "../foo"
- },
- "bar": {
- "path": "../bar"
- },
- "baz": {
- "path": "../baz"
- },
- },
- "transformers": [{
- "foo": {
- "\$include": "lib/pkg.dart"
- }
- }, {
- "bar": {
- "\$exclude": "lib/transformer.dart"
- }
- }, "baz"]
- }),
- d.dir(
- "lib",
- [d.file("pkg.dart", ""), d.file("transformer.dart", transformer())])]).create();
-
- // Even though foo and bar don't modify pkg/lib/transformer.dart themselves,
- // it may be modified to import a library that they modify or generate, so
- // pkg will depend on them.
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- d.dir(
- "bar",
- [
- d.libPubspec("bar", "1.0.0"),
- d.dir("lib", [d.file("bar.dart", transformer())])]).create();
-
- // baz transforms pkg/lib/transformer.dart, so pkg will obviously
- // depend on it.
- d.dir(
- "baz",
- [
- d.libPubspec("baz", "1.0.0"),
- d.dir("lib", [d.file("baz.dart", transformer())])]).create();
-
- // qux doesn't transform anything in pkg, so pkg won't depend on it.
- d.dir(
- "qux",
- [
- d.libPubspec("qux", "1.0.0"),
- d.dir("lib", [d.file("qux.dart", transformer())])]).create();
-
- expectDependencies({
- 'pkg': ['foo', 'bar', 'baz'],
- 'foo': [],
- 'bar': [],
- 'baz': [],
- 'qux': []
- });
- });
-
- integration(
- "reports all transitive package dependencies' transformers as "
- "dependencies if the transformer is transformed",
- () {
- // The root app just exists so that something is transformed by pkg and qux.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "pkg": {
- "path": "../pkg"
- },
- "qux": {
- "path": "../qux"
- }
- },
- "transformers": ["pkg"]
- })]).create();
-
- d.dir("pkg", [d.pubspec({
- "name": "pkg",
- "version": "1.0.0",
- "dependencies": {
- "foo": {
- "path": "../foo"
- },
- "baz": {
- "path": "../baz"
- }
- },
- "transformers": ["baz"]
- }), d.dir("lib", [d.file("pkg.dart", transformer())])]).create();
-
- // pkg depends on foo. Even though it's not transformed by foo, its
- // transformed transformer could import foo, so it has to depend on foo.
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "dependencies": {
- "bar": {
- "path": "../bar"
- }
- },
- "transformers": ["foo"]
- }), d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- // foo depends on bar, and like pkg's dependency on foo, the transformed
- // version of foo's transformer could import bar, so foo has to depend on
- // bar.
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "version": "1.0.0",
- "transformers": ["bar"]
- }), d.dir("lib", [d.file("bar.dart", transformer())])]).create();
-
- /// foo is transformed by baz.
- d.dir(
- "baz",
- [
- d.libPubspec("baz", "1.0.0"),
- d.dir("lib", [d.file("baz.dart", transformer())])]).create();
-
- /// qux is not part of pkg's transitive dependency tree, so pkg shouldn't
- /// depend on it.
- d.dir("qux", [d.pubspec({
- "name": "qux",
- "version": "1.0.0",
- "transformers": ["qux"]
- }), d.dir("lib", [d.file("qux.dart", transformer())])]).create();
-
- expectDependencies({
- 'pkg': ['foo', 'bar', 'baz'],
- 'foo': [],
- 'bar': [],
- 'baz': [],
- 'qux': []
- });
- });
-
- integration(
- "reports previous transformers as dependencies if a "
- "nonexistent local file is imported",
- () {
- // The root app just exists so that something is transformed by pkg and bar.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "pkg": {
- "path": "../pkg"
- },
- "bar": {
- "path": "../bar"
- }
- },
- "transformers": ["pkg", "bar"]
- })]).create();
-
- d.dir("pkg", [d.pubspec({
- "name": "pkg",
- "version": "1.0.0",
- "dependencies": {
- "foo": {
- "path": "../foo"
- },
- "bar": {
- "path": "../bar"
- }
- },
- "transformers": [{
- "foo": {
- "\$include": "lib/pkg.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [
- d.file("pkg.dart", ""),
- d.file("transformer.dart", transformer(["nonexistent.dart"]))])]).create();
-
- // Since pkg's transformer imports a nonexistent file, we assume that file
- // was generated by foo's transformer. Thus pkg's transformer depends on
- // foo's even though the latter doesn't transform the former.
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- /// qux is not part of pkg's transitive dependency tree, so pkg shouldn't
- /// depend on it.
- d.dir(
- "bar",
- [
- d.libPubspec("bar", "1.0.0"),
- d.dir("lib", [d.file("bar.dart", transformer())])]).create();
-
- expectDependencies({
- 'pkg': ['foo'],
- 'foo': [],
- 'bar': []
- });
- });
-
- integration(
- "reports all that package's dependencies' transformers as "
- "dependencies if a non-existent file is imported from another package",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- },
- "qux": {
- "path": "../qux"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file(
- "myapp.dart",
- transformer(["package:foo/nonexistent.dart"]))])]).create();
-
- // myapp imported a nonexistent file from foo so myapp will depend on every
- // transformer transitively reachable from foo, since the nonexistent file
- // could be generated to import anything.
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "dependencies": {
- "bar": {
- "path": "../bar"
- },
- "baz": {
- "path": "../baz"
- }
- },
- "transformers": ["foo"]
- }), d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- // bar is a dependency of foo so myapp will depend on it.
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "version": "1.0.0",
- "transformers": ["bar"]
- }), d.dir("lib", [d.file("bar.dart", transformer())])]).create();
-
- // baz is a dependency of foo so myapp will depend on it.
- d.dir("baz", [d.pubspec({
- "name": "baz",
- "version": "1.0.0",
- "transformers": ["baz"]
- }), d.dir("lib", [d.file("baz.dart", transformer())])]).create();
-
- // qux is not transitively reachable from foo so myapp won't depend on it.
- d.dir("qux", [d.pubspec({
- "name": "qux",
- "version": "1.0.0",
- "transformers": ["qux"]
- }), d.dir("lib", [d.file("qux.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': ['foo', 'bar', 'baz'],
- 'foo': [],
- 'bar': [],
- 'baz': [],
- 'qux': []
- });
- });
-
- integration(
- "reports all that package's dependencies' transformers as "
- "dependencies if a non-existent transformer is used from another package",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- },
- "qux": {
- "path": "../qux"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file(
- "myapp.dart",
- transformer(["package:foo/nonexistent.dart"]))])]).create();
-
- // myapp imported a nonexistent file from foo so myapp will depend on every
- // transformer transitively reachable from foo, since the nonexistent file
- // could be generated to import anything.
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "dependencies": {
- "bar": {
- "path": "../bar"
- },
- "baz": {
- "path": "../baz"
- }
- },
- "transformers": ["bar"]
- })]).create();
-
- // bar is a dependency of foo so myapp will depend on it.
- d.dir(
- "bar",
- [
- d.libPubspec("bar", "1.0.0"),
- d.dir("lib", [d.file("bar.dart", transformer())])]).create();
-
- // baz is a dependency of foo so myapp will depend on it.
- d.dir("baz", [d.pubspec({
- "name": "baz",
- "version": "1.0.0",
- "transformers": ["baz"]
- }), d.dir("lib", [d.file("baz.dart", transformer())])]).create();
-
- // qux is not transitively reachable from foo so myapp won't depend on it.
- d.dir("qux", [d.pubspec({
- "name": "qux",
- "version": "1.0.0",
- "transformers": ["qux"]
- }), d.dir("lib", [d.file("qux.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': ['bar', 'baz'],
- 'bar': [],
- 'baz': [],
- 'qux': []
- });
- });
-
- test("reports dependencies on transformers in past phases", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/first", "myapp/second", "myapp/third"]
- }),
- d.dir(
- "lib",
- [
- d.file("first.dart", transformer()),
- d.file("second.dart", transformer()),
- d.file("third.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp/first': [],
- 'myapp/second': ['myapp/first'],
- 'myapp/third': ['myapp/second', 'myapp/first']
- });
- });
-
- integration(
- "considers the entrypoint package's dev and override " "dependencies",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "dev_dependencies": {
- "bar": {
- "path": "../bar"
- }
- },
- "dependency_overrides": {
- "baz": {
- "path": "../baz"
- }
- },
- "transformers": ["foo", "myapp"]
- }), d.dir("lib", [d.file("myapp.dart", transformer())])]).create();
-
- // foo transforms myapp's transformer so it could import from bar or baz.
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": ["foo"]
- }), d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- // bar is a dev dependency that myapp could import from, so myapp should
- // depend on it.
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "version": "1.0.0",
- "transformers": ["bar"]
- }), d.dir("lib", [d.file("bar.dart", transformer())])]).create();
-
- // baz is an override dependency that myapp could import from, so myapp
- // should depend on it.
- d.dir("baz", [d.pubspec({
- "name": "baz",
- "version": "1.0.0",
- "transformers": ["baz"]
- }), d.dir("lib", [d.file("baz.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': ['foo', 'bar', 'baz'],
- 'foo': [],
- 'bar': [],
- 'baz': []
- });
- });
-
- integration(
- "doesn't consider a non-entrypoint package's dev and override " "dependencies",
- () {
- // myapp just exists so that pkg isn't the entrypoint.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "pkg": {
- "path": "../pkg"
- }
- }
- })]).create();
-
- d.dir("pkg", [d.pubspec({
- "name": "pkg",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "dev_dependencies": {
- "bar": {
- "path": "../bar"
- }
- },
- "dependency_overrides": {
- "baz": {
- "path": "../baz"
- }
- },
- "transformers": ["foo", "pkg"]
- }), d.dir("lib", [d.file("pkg.dart", transformer())])]).create();
-
- // foo transforms pkg's transformer so it could theoretcially import from
- // bar or baz. However, since pkg isn't the entrypoint, it doesn't have
- // access to them.
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": ["foo"]
- }), d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- // bar is a dev dependency that myapp can't import from, so myapp shouldn't
- // depend on it.
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "version": "1.0.0",
- "transformers": ["bar"]
- }), d.dir("lib", [d.file("bar.dart", transformer())])]).create();
-
- // baz is a dev dependency that myapp can't import from, so myapp shouldn't
- // depend on it.
- d.dir("baz", [d.pubspec({
- "name": "baz",
- "version": "1.0.0",
- "transformers": ["baz"]
- }), d.dir("lib", [d.file("baz.dart", transformer())])]).create();
-
- expectDependencies({
- 'pkg': ['foo'],
- 'foo': [],
- 'bar': [],
- 'baz': []
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/cycle_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/cycle_test.dart
deleted file mode 100644
index bfe4cb2..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_computer/cycle_test.dart
+++ /dev/null
@@ -1,266 +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.
-
-library pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-void main() {
- initConfig();
-
- integration(
- "allows a package dependency cycle that's unrelated to " "transformers",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp/first", "myapp/second"]
- }),
- d.dir(
- 'lib',
- [
- d.file("first.dart", transformer()),
- d.file("second.dart", transformer())])]).create();
-
- d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: {
- "bar": {
- "path": "../bar"
- }
- })]).create();
-
- d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: {
- "baz": {
- "path": "../baz"
- }
- })]).create();
-
- d.dir("baz", [d.libPubspec("baz", "1.0.0", deps: {
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- expectDependencies({
- 'myapp/first': [],
- 'myapp/second': ['myapp/first']
- });
- });
-
- integration(
- "disallows a package dependency cycle that may be related to " "transformers",
- () {
- // Two layers of myapp transformers are necessary here because otherwise pub
- // will figure out that the transformer doesn't import "foo" and thus
- // doesn't transitively import itself. Import loops are tested below.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp/first", "myapp/second"]
- }),
- d.dir(
- 'lib',
- [
- d.file("first.dart", transformer()),
- d.file("second.dart", transformer())])]).create();
-
- d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: {
- "bar": {
- "path": "../bar"
- }
- })]).create();
-
- d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: {
- "myapp": {
- "path": "../myapp"
- }
- })]).create();
-
- expectCycleException(
- [
- "myapp is transformed by myapp/second",
- "myapp depends on foo",
- "foo depends on bar",
- "bar depends on myapp",
- "myapp is transformed by myapp/first"]);
- });
-
- integration("disallows a transformation dependency cycle", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["foo"]
- }), d.dir('lib', [d.file("myapp.dart", transformer())])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "dependencies": {
- "bar": {
- "path": "../bar"
- }
- },
- "transformers": ["bar"]
- }), d.dir('lib', [d.file("foo.dart", transformer())])]).create();
-
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "dependencies": {
- "myapp": {
- "path": "../myapp"
- }
- },
- "transformers": ["myapp"]
- }), d.dir('lib', [d.file("bar.dart", transformer())])]).create();
-
- expectCycleException(
- [
- "bar is transformed by myapp",
- "myapp is transformed by foo",
- "foo is transformed by bar"]);
- });
-
- integration(
- "allows a cross-package import cycle that's unrelated to " "transformers",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- 'lib',
- [d.file("myapp.dart", transformer(['package:foo/foo.dart']))])]).create();
-
- d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: {
- "bar": {
- "path": "../bar"
- }
- }),
- d.dir('lib', [d.file("foo.dart", "import 'package:bar/bar.dart';")])]).create();
-
- d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: {
- "baz": {
- "path": "../baz"
- }
- }),
- d.dir('lib', [d.file("bar.dart", "import 'package:baz/baz.dart';")])]).create();
-
- d.dir("baz", [d.libPubspec("baz", "1.0.0", deps: {
- "foo": {
- "path": "../foo"
- }
- }),
- d.dir('lib', [d.file("baz.dart", "import 'package:foo/foo.dart';")])]).create();
-
- expectDependencies({
- 'myapp': []
- });
- });
-
- integration(
- "disallows a cross-package import cycle that's related to " "transformers",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- 'lib',
- [d.file("myapp.dart", transformer(['package:foo/foo.dart']))])]).create();
-
- d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: {
- "bar": {
- "path": "../bar"
- }
- }),
- d.dir('lib', [d.file("foo.dart", "import 'package:bar/bar.dart';")])]).create();
-
- d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: {
- "myapp": {
- "path": "../myapp"
- }
- }),
- d.dir(
- 'lib',
- [d.file("bar.dart", "import 'package:myapp/myapp.dart';")])]).create();
-
- expectCycleException(
- [
- "myapp is transformed by myapp",
- "myapp depends on foo",
- "foo depends on bar",
- "bar depends on myapp"]);
- });
-
- integration(
- "allows a single-package import cycle that's unrelated to " "transformers",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- 'lib',
- [
- d.file("myapp.dart", transformer(['foo.dart'])),
- d.file("foo.dart", "import 'bar.dart';"),
- d.file("bar.dart", "import 'baz.dart';"),
- d.file("baz.dart", "import 'foo.dart';")])]).create();
-
- expectDependencies({
- 'myapp': []
- });
- });
-
- integration(
- "allows a single-package import cycle that's related to " "transformers",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- 'lib',
- [
- d.file("myapp.dart", transformer(['foo.dart'])),
- d.file("foo.dart", "import 'bar.dart';"),
- d.file("bar.dart", "import 'myapp.dart';"),])]).create();
-
- expectDependencies({
- 'myapp': []
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/dev_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/dev_transformers_test.dart
deleted file mode 100644
index 853c406..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_computer/dev_transformers_test.dart
+++ /dev/null
@@ -1,88 +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.
-
-library pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-void main() {
- initConfig();
-
- integration(
- "doesn't return a dependency's transformer that can't run on lib",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- }
- })]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": [{
- "foo": {
- "\$include": "test/foo_test.dart"
- }
- }]
- }),
- d.dir("lib", [d.file("foo.dart", transformer())]),
- d.dir("test", [d.file("foo_test.dart", "")])]).create();
-
- expectDependencies({});
- });
-
- integration(
- "does return the root package's transformer that can't run on " "lib",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp": {
- "\$include": "test/myapp_test.dart"
- }
- }]
- }),
- d.dir("lib", [d.file("myapp.dart", transformer())]),
- d.dir("test", [d.file("myapp_test.dart", "")])]).create();
-
- expectDependencies({
- "myapp": []
- });
- });
-
- integration(
- "doesn't return a dependency's transformer that can run on bin",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- }
- })]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": [{
- "foo": {
- "\$include": "bin/foo.dart"
- }
- }]
- }),
- d.dir("lib", [d.file("foo.dart", transformer())]),
- d.dir("test", [d.file("foo_test.dart", "")])]).create();
-
- expectDependencies({
- "foo": []
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/error_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/error_test.dart
deleted file mode 100644
index 2670867..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_computer/error_test.dart
+++ /dev/null
@@ -1,45 +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.
-
-library pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exceptions.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-void main() {
- initConfig();
-
- integration("fails if an unknown package is imported", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp"]
- }),
- d.dir(
- 'lib',
- [d.file("myapp.dart", transformer(["package:foo/foo.dart"]))])]).create();
-
- expectException(predicate((error) {
- expect(error, new isInstanceOf<ApplicationException>());
- expect(
- error.message,
- equals(
- 'A transformer imported unknown package "foo" (in '
- '"package:foo/foo.dart").'));
- return true;
- }));
- });
-
- integration("fails on a syntax error", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp"]
- }), d.dir('lib', [d.file("myapp.dart", "library;")])]).create();
-
- expectException(new isInstanceOf<AnalyzerErrorGroup>());
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/import_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/import_dependencies_test.dart
deleted file mode 100644
index 50ea1c9..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_computer/import_dependencies_test.dart
+++ /dev/null
@@ -1,249 +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.
-
-library pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-void main() {
- initConfig();
-
- integration(
- "reports a dependency if a transformed local file is imported",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": [{
- "foo": {
- "\$include": "lib/lib.dart"
- }
- }, "myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("lib.dart", ""),
- d.file("transformer.dart", transformer(["lib.dart"]))])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0"
- }), d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': ['foo'],
- 'foo': []
- });
- });
-
- integration(
- "reports a dependency if a transformed foreign file is imported",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("transformer.dart", transformer(["package:foo/foo.dart"]))])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": [{
- "foo": {
- "\$include": "lib/foo.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [d.file("foo.dart", ""), d.file("transformer.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': ['foo'],
- 'foo': []
- });
- });
-
- integration(
- "reports a dependency if a transformed external package file is "
- "imported from an export",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("transformer.dart", transformer(["local.dart"])),
- d.file("local.dart", "export 'package:foo/foo.dart';")])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": [{
- "foo": {
- "\$include": "lib/foo.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [d.file("foo.dart", ""), d.file("transformer.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': ['foo'],
- 'foo': []
- });
- });
-
- integration(
- "reports a dependency if a transformed foreign file is "
- "transitively imported",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("transformer.dart", transformer(["local.dart"])),
- d.file("local.dart", "import 'package:foo/foreign.dart';")])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": [{
- "foo": {
- "\$include": "lib/foo.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [
- d.file("foo.dart", ""),
- d.file("transformer.dart", transformer()),
- d.file("foreign.dart", "import 'foo.dart';")])]).create();
-
- expectDependencies({
- 'myapp': ['foo'],
- 'foo': []
- });
- });
-
- integration(
- "reports a dependency if a transformed foreign file is "
- "transitively imported across packages",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("transformer.dart", transformer(["package:foo/foo.dart"])),])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "dependencies": {
- "bar": {
- "path": "../bar"
- }
- }
- }),
- d.dir("lib", [d.file("foo.dart", "import 'package:bar/bar.dart';")])]).create();
-
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "version": "1.0.0",
- "transformers": [{
- "bar": {
- "\$include": "lib/bar.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [d.file("bar.dart", ""), d.file("transformer.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': ['bar'],
- 'bar': []
- });
- });
-
- integration(
- "reports a dependency if an imported file is transformed by a "
- "different package",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": [{
- "foo": {
- '\$include': 'lib/local.dart'
- }
- }, "myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("transformer.dart", transformer(["local.dart"])),
- d.file("local.dart", "")])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0"
- }), d.dir("lib", [d.file("transformer.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': ['foo'],
- 'foo': []
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/no_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/no_dependencies_test.dart
deleted file mode 100644
index 7aeb6ee..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_computer/no_dependencies_test.dart
+++ /dev/null
@@ -1,204 +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.
-
-library pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-void main() {
- initConfig();
-
- integration("reports no dependencies if no transformers are used", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- }
- })]).create();
-
- d.dir("foo", [d.libPubspec("foo", "1.0.0")]).create();
-
- expectDependencies({});
- });
-
- integration(
- "reports no dependencies if a transformer is used in a "
- "package that doesn't expose a transformer",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["foo"]
- })]).create();
-
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- expectDependencies({
- "foo": []
- });
- });
-
- integration("reports no dependencies for non-file/package imports", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file(
- "myapp.dart",
- transformer(
- ["dart:async", "http://dartlang.org/nonexistent.dart"]))])]).create();
-
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- expectDependencies({
- "myapp": []
- });
- });
-
- integration("reports no dependencies for a single self transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp"]
- }), d.dir("lib", [d.file("myapp.dart", transformer())])]).create();
-
- expectDependencies({
- "myapp": []
- });
- });
-
- integration(
- "reports no dependencies if a transformer applies to files that "
- "aren't used by the exposed transformer",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": [{
- "foo": {
- "\$include": "lib/myapp.dart"
- }
- }, {
- "foo": {
- "\$exclude": "lib/transformer.dart"
- }
- }, "myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("transformer.dart", transformer())])]).create();
-
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- expectDependencies({
- "myapp": [],
- "foo": []
- });
- });
-
- integration(
- "reports no dependencies if a transformer applies to a "
- "dependency's files that aren't used by the exposed transformer",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("transformer.dart", transformer(["package:foo/foo.dart"]))])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": [{
- "foo": {
- "\$exclude": "lib/foo.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [d.file("foo.dart", ""), d.file("transformer.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp': [],
- 'foo': []
- });
- });
-
- test("reports no dependencies on transformers in future phases", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/first": {
- "\$include": "lib/myapp.dart"
- }
- }, {
- "myapp/second": {
- "\$include": "lib/first.dart"
- }
- }, {
- "myapp/third": {
- "\$include": "lib/second.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.file("first.dart", transformer()),
- d.file("second.dart", transformer()),
- d.file("third.dart", transformer())])]).create();
-
- expectDependencies({
- 'myapp/first': [],
- 'myapp/second': [],
- 'myapp/third': []
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/transformers_needed_by_library_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/transformers_needed_by_library_test.dart
deleted file mode 100644
index 1f27f68..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_computer/transformers_needed_by_library_test.dart
+++ /dev/null
@@ -1,131 +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.
-
-library pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-void main() {
- initConfig();
-
- integration("reports a dependency if the library itself is transformed", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": [{
- "foo": {
- "\$include": "bin/myapp.dart.dart"
- }
- }]
- }),
- d.dir(
- "bin",
- [d.file("myapp.dart", "import 'package:myapp/lib.dart';"),])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0"
- }), d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- expectLibraryDependencies('myapp|bin/myapp.dart', ['foo']);
- });
-
- integration(
- "reports a dependency if a transformed local file is imported",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": [{
- "foo": {
- "\$include": "lib/lib.dart"
- }
- }]
- }),
- d.dir("lib", [d.file("lib.dart", ""),]),
- d.dir(
- "bin",
- [d.file("myapp.dart", "import 'package:myapp/lib.dart';"),])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0"
- }), d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- expectLibraryDependencies('myapp|bin/myapp.dart', ['foo']);
- });
-
- integration(
- "reports a dependency if a transformed foreign file is imported",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- }),
- d.dir(
- "bin",
- [d.file("myapp.dart", "import 'package:foo/foo.dart';")])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": [{
- "foo": {
- "\$include": "lib/foo.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [d.file("foo.dart", ""), d.file("transformer.dart", transformer())])]).create();
-
- expectLibraryDependencies('myapp|bin/myapp.dart', ['foo']);
- });
-
- integration(
- "doesn't report a dependency if no transformed files are " "imported",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": [{
- "foo": {
- "\$include": "lib/lib.dart"
- }
- }]
- }),
- d.dir("lib", [d.file("lib.dart", ""), d.file("untransformed.dart", ""),]),
- d.dir(
- "bin",
- [
- d.file(
- "myapp.dart",
- "import 'package:myapp/untransformed.dart';"),])]).create();
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0"
- }), d.dir("lib", [d.file("foo.dart", transformer())])]).create();
-
- expectLibraryDependencies('myapp|bin/myapp.dart', []);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/utils.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/utils.dart
deleted file mode 100644
index 33b1bf7..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_computer/utils.dart
+++ /dev/null
@@ -1,129 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/barback/cycle_exception.dart';
-import '../../lib/src/barback/dependency_computer.dart';
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/io.dart';
-import '../../lib/src/package.dart';
-import '../../lib/src/package_graph.dart';
-import '../../lib/src/source/path.dart';
-import '../../lib/src/system_cache.dart';
-import '../../lib/src/utils.dart';
-import '../test_pub.dart';
-
-/// Expects that [DependencyComputer.transformersNeededByTransformers] will
-/// return a graph matching [expected] when run on the package graph defined by
-/// packages in the sandbox.
-void expectDependencies(Map<String, Iterable<String>> expected) {
- expected = mapMap(expected, value: (_, ids) => ids.toSet());
-
- schedule(() {
- var computer = new DependencyComputer(_loadPackageGraph());
- var result = mapMap(
- computer.transformersNeededByTransformers(),
- key: (id, _) => id.toString(),
- value: (_, ids) => ids.map((id) => id.toString()).toSet());
- expect(result, equals(expected));
- }, "expect dependencies to match $expected");
-}
-
-/// Expects that [computeTransformersNeededByTransformers] will throw an
-/// exception matching [matcher] when run on the package graph defiend by
-/// packages in the sandbox.
-void expectException(matcher) {
- schedule(() {
- expect(() {
- var computer = new DependencyComputer(_loadPackageGraph());
- computer.transformersNeededByTransformers();
- }, throwsA(matcher));
- }, "expect an exception: $matcher");
-}
-
-/// Expects that [computeTransformersNeededByTransformers] will throw a
-/// [CycleException] with the given [steps] when run on the package graph
-/// defiend by packages in the sandbox.
-void expectCycleException(Iterable<String> steps) {
- expectException(predicate((error) {
- expect(error, new isInstanceOf<CycleException>());
- expect(error.steps, equals(steps));
- return true;
- }, "cycle exception:\n${steps.map((step) => " $step").join("\n")}"));
-}
-
-/// Expects that [DependencyComputer.transformersNeededByLibrary] will return
-/// transformer ids matching [expected] when run on the library identified by
-/// [id].
-void expectLibraryDependencies(String id, Iterable<String> expected) {
- expected = expected.toSet();
-
- schedule(() {
- var computer = new DependencyComputer(_loadPackageGraph());
- var result = computer.transformersNeededByLibrary(
- new AssetId.parse(id)).map((id) => id.toString()).toSet();
- expect(result, equals(expected));
- }, "expect dependencies to match $expected");
-}
-
-/// Loads a [PackageGraph] from the packages in the sandbox.
-///
-/// This graph will also include barback and its transitive dependencies from
-/// the repo.
-PackageGraph _loadPackageGraph() {
- // Load the sandbox packages.
- var packages = {};
-
- var systemCache = new SystemCache(p.join(sandboxDir, cachePath));
- systemCache.sources
- ..register(new PathSource())
- ..setDefault('path');
- var entrypoint = new Entrypoint(p.join(sandboxDir, appPath), systemCache);
-
- for (var package in listDir(sandboxDir)) {
- if (!fileExists(p.join(package, 'pubspec.yaml'))) continue;
- var packageName = p.basename(package);
- packages[packageName] =
- new Package.load(packageName, package, systemCache.sources);
- }
-
- loadPackage(packageName) {
- if (packages.containsKey(packageName)) return;
- packages[packageName] =
- new Package.load(packageName, packagePath(packageName), systemCache.sources);
- for (var dep in packages[packageName].dependencies) {
- loadPackage(dep.name);
- }
- }
-
- loadPackage('barback');
-
- return new PackageGraph(entrypoint, null, packages);
-}
-
-/// Returns the contents of a no-op transformer that imports each URL in
-/// [imports].
-String transformer([Iterable<String> imports]) {
- if (imports == null) imports = [];
-
- var buffer =
- new StringBuffer()..writeln('import "package:barback/barback.dart";');
- for (var import in imports) {
- buffer.writeln('import "$import";');
- }
-
- buffer.writeln("""
-NoOpTransformer extends Transformer {
- bool isPrimary(AssetId id) => true;
- void apply(Transform transform) {}
-}
-""");
-
- return buffer.toString();
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dependency_override_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_override_test.dart
deleted file mode 100644
index 51eef32..0000000
--- a/sdk/lib/_internal/pub_generated/test/dependency_override_test.dart
+++ /dev/null
@@ -1,115 +0,0 @@
-// Copyright (c) 2013, 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:path/path.dart' as path;
-
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-main() {
- initConfig();
- forBothPubGetAndUpgrade((command) {
- integration("chooses best version matching override constraint", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "2.0.0");
- builder.serve("foo", "3.0.0");
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": ">2.0.0"
- },
- "dependency_overrides": {
- "foo": "<3.0.0"
- }
- })]).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "foo": "2.0.0"
- }).validate();
- });
-
- integration("treats override as implicit dependency", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependency_overrides": {
- "foo": "any"
- }
- })]).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "foo": "1.0.0"
- }).validate();
- });
-
- integration("ignores other constraints on overridden package", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "2.0.0");
- builder.serve("foo", "3.0.0");
- builder.serve("bar", "1.0.0", pubspec: {
- "dependencies": {
- "foo": "5.0.0-nonexistent"
- }
- });
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "bar": "any"
- },
- "dependency_overrides": {
- "foo": "<3.0.0"
- }
- })]).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "foo": "2.0.0",
- "bar": "1.0.0"
- }).validate();
- });
-
- integration("warns about overridden dependencies", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("bar", "1.0.0");
- });
-
- d.dir("baz", [d.libDir("baz"), d.libPubspec("baz", "0.0.1")]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependency_overrides": {
- "foo": "any",
- "bar": "any",
- "baz": {
- "path": "../baz"
- }
- }
- })]).create();
-
- var bazPath = path.join("..", "baz");
-
- schedulePub(args: [command.name], output: command.success, error: """
- Warning: You are using these overridden dependencies:
- ! bar 1.0.0
- ! baz 0.0.1 from path $bazPath
- ! foo 1.0.0
- """);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/deps_test.dart b/sdk/lib/_internal/pub_generated/test/deps_test.dart
deleted file mode 100644
index 20403c2..0000000
--- a/sdk/lib/_internal/pub_generated/test/deps_test.dart
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- servePackages((builder) {
- builder.serve("normal", "1.2.3", deps: {
- "transitive": "any",
- "circular_a": "any"
- });
- builder.serve("transitive", "1.2.3", deps: {
- "shared": "any"
- });
- builder.serve("shared", "1.2.3", deps: {
- "other": "any"
- });
- builder.serve("unittest", "1.2.3", deps: {
- "shared": "any"
- });
- builder.serve("other", "1.0.0");
- builder.serve("overridden", "1.0.0");
- builder.serve("overridden", "2.0.0");
- builder.serve("override_only", "1.2.3");
- builder.serve("circular_a", "1.2.3", deps: {
- "circular_b": "any"
- });
- builder.serve("circular_b", "1.2.3", deps: {
- "circular_a": "any"
- });
- });
-
- d.dir(
- "from_path",
- [d.libDir("from_path"), d.libPubspec("from_path", "1.2.3")]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "normal": "any",
- "overridden": "1.0.0",
- "from_path": {
- "path": "../from_path"
- }
- },
- "dev_dependencies": {
- "unittest": "any"
- },
- "dependency_overrides": {
- "overridden": "2.0.0",
- "override_only": "any"
- }
- })]).create();
- });
-
- integration("lists dependencies in compact form", () {
- pubGet();
- schedulePub(args: ['deps', '-s', 'compact'], output: '''
- myapp 0.0.0
-
- dependencies:
- - from_path 1.2.3
- - normal 1.2.3 [transitive circular_a]
- - overridden 2.0.0
-
- dev dependencies:
- - unittest 1.2.3 [shared]
-
- dependency overrides:
- - overridden 2.0.0
- - override_only 1.2.3
-
- transitive dependencies:
- - circular_a 1.2.3 [circular_b]
- - circular_b 1.2.3 [circular_a]
- - other 1.0.0
- - shared 1.2.3 [other]
- - transitive 1.2.3 [shared]
- ''');
- });
-
- integration("lists dependencies in list form", () {
- pubGet();
- schedulePub(args: ['deps', '--style', 'list'], output: '''
- myapp 0.0.0
-
- dependencies:
- - from_path 1.2.3
- - normal 1.2.3
- - transitive any
- - circular_a any
- - overridden 2.0.0
-
- dev dependencies:
- - unittest 1.2.3
- - shared any
-
- dependency overrides:
- - overridden 2.0.0
- - override_only 1.2.3
-
- transitive dependencies:
- - circular_a 1.2.3
- - circular_b any
- - circular_b 1.2.3
- - circular_a any
- - other 1.0.0
- - shared 1.2.3
- - other any
- - transitive 1.2.3
- - shared any
- ''');
- });
-
- integration("lists dependencies in tree form", () {
- pubGet();
- schedulePub(args: ['deps'], output: '''
- myapp 0.0.0
- |-- from_path 1.2.3
- |-- normal 1.2.3
- | |-- circular_a 1.2.3
- | | '-- circular_b 1.2.3
- | | '-- circular_a...
- | '-- transitive 1.2.3
- | '-- shared...
- |-- overridden 2.0.0
- |-- override_only 1.2.3
- '-- unittest 1.2.3
- '-- shared 1.2.3
- '-- other 1.0.0
- ''');
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/descriptor.dart b/sdk/lib/_internal/pub_generated/test/descriptor.dart
deleted file mode 100644
index 18fa385..0000000
--- a/sdk/lib/_internal/pub_generated/test/descriptor.dart
+++ /dev/null
@@ -1,183 +0,0 @@
-// Copyright (c) 2013, 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.
-
-/// Pub-specific scheduled_test descriptors.
-library descriptor;
-
-import 'package:oauth2/oauth2.dart' as oauth2;
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/descriptor.dart';
-
-import '../lib/src/io.dart';
-import '../lib/src/utils.dart';
-import 'descriptor/git.dart';
-import 'descriptor/tar.dart';
-import 'test_pub.dart';
-
-export 'package:scheduled_test/descriptor.dart';
-export 'descriptor/git.dart';
-export 'descriptor/tar.dart';
-
-/// Creates a new [GitRepoDescriptor] with [name] and [contents].
-GitRepoDescriptor git(String name, [Iterable<Descriptor> contents]) =>
- new GitRepoDescriptor(name, contents == null ? <Descriptor>[] : contents);
-
-/// Creates a new [TarRepoDescriptor] with [name] and [contents].
-TarFileDescriptor tar(String name, [Iterable<Descriptor> contents]) =>
- new TarFileDescriptor(name, contents == null ? <Descriptor>[] : contents);
-
-/// Describes a package that passes all validation.
-Descriptor get validPackage =>
- dir(
- appPath,
- [
- libPubspec("test_pkg", "1.0.0"),
- file("LICENSE", "Eh, do what you want."),
- dir("lib", [file("test_pkg.dart", "int i = 1;")])]);
-
-/// Returns a descriptor of a snapshot that can't be run by the current VM.
-///
-/// This snapshot was generated by the VM on r39611, the revision immediately
-/// before snapshot versioning was added.
-FileDescriptor outOfDateSnapshot(String name) =>
- binaryFile(name, readBinaryFile(testAssetPath('out-of-date.snapshot')));
-
-/// Describes a file named `pubspec.yaml` with the given YAML-serialized
-/// [contents], which should be a serializable object.
-///
-/// [contents] may contain [Future]s that resolve to serializable objects,
-/// which may in turn contain [Future]s recursively.
-Descriptor pubspec(Map contents) {
- return async(
- awaitObject(
- contents).then(
- (resolvedContents) => file("pubspec.yaml", yaml(resolvedContents))));
-}
-
-/// Describes a file named `pubspec.yaml` for an application package with the
-/// given [dependencies].
-Descriptor appPubspec([Map dependencies]) {
- var map = {
- "name": "myapp"
- };
- if (dependencies != null) map["dependencies"] = dependencies;
- return pubspec(map);
-}
-
-/// Describes a file named `pubspec.yaml` for a library package with the given
-/// [name], [version], and [deps]. If "sdk" is given, then it adds an SDK
-/// constraint on that version.
-Descriptor libPubspec(String name, String version, {Map deps, String sdk}) {
- var map = packageMap(name, version, deps);
- if (sdk != null) map["environment"] = {
- "sdk": sdk
- };
- return pubspec(map);
-}
-
-/// Describes a directory named `lib` containing a single dart file named
-/// `<name>.dart` that contains a line of Dart code.
-Descriptor libDir(String name, [String code]) {
- // Default to printing the name if no other code was given.
- if (code == null) code = name;
- return dir("lib", [file("$name.dart", 'main() => "$code";')]);
-}
-
-/// Describes a directory for a Git package. This directory is of the form
-/// found in the revision cache of the global package cache.
-Descriptor gitPackageRevisionCacheDir(String name, [int modifier]) {
- var value = name;
- if (modifier != null) value = "$name $modifier";
- return pattern(
- new RegExp("$name${r'-[a-f0-9]+'}"),
- (dirName) => dir(dirName, [libDir(name, value)]));
-}
-
-/// Describes a directory for a Git package. This directory is of the form
-/// found in the repo cache of the global package cache.
-Descriptor gitPackageRepoCacheDir(String name) {
- return pattern(
- new RegExp("$name${r'-[a-f0-9]+'}"),
- (dirName) =>
- dir(dirName, [dir('hooks'), dir('info'), dir('objects'), dir('refs')]));
-}
-
-/// Describes the `packages/` directory containing all the given [packages],
-/// which should be name/version pairs. The packages will be validated against
-/// the format produced by the mock package server.
-///
-/// A package with a null version should not be downloaded.
-Descriptor packagesDir(Map<String, String> packages) {
- var contents = <Descriptor>[];
- packages.forEach((name, version) {
- if (version == null) {
- contents.add(nothing(name));
- } else {
- contents.add(
- dir(name, [file("$name.dart", 'main() => "$name $version";')]));
- }
- });
- return dir(packagesPath, contents);
-}
-
-/// Describes the global package cache directory containing all the given
-/// [packages], which should be name/version pairs. The packages will be
-/// validated against the format produced by the mock package server.
-///
-/// A package's value may also be a list of versions, in which case all
-/// versions are expected to be downloaded.
-///
-/// If [includePubspecs] is `true`, then pubspecs will be created for each
-/// package. Defaults to `false` so that the contents of pubspecs are not
-/// validated since they will often lack the dependencies section that the
-/// real pubspec being compared against has. You usually only need to pass
-/// `true` for this if you plan to call [create] on the resulting descriptor.
-Descriptor cacheDir(Map packages, {bool includePubspecs: false}) {
- var contents = <Descriptor>[];
- packages.forEach((name, versions) {
- if (versions is! List) versions = [versions];
- for (var version in versions) {
- var packageContents = [libDir(name, '$name $version')];
- if (includePubspecs) {
- packageContents.add(libPubspec(name, version));
- }
- contents.add(dir("$name-$version", packageContents));
- }
- });
-
- return hostedCache(contents);
-}
-
-/// Describes the main cache directory containing cached hosted packages
-/// downloaded from the mock package server.
-Descriptor hostedCache(Iterable<Descriptor> contents) {
- return dir(
- cachePath,
- [dir('hosted', [async(port.then((p) => dir('localhost%58$p', contents)))])]);
-}
-
-/// Describes the file in the system cache that contains the client's OAuth2
-/// credentials. The URL "/token" on [server] will be used as the token
-/// endpoint for refreshing the access token.
-Descriptor credentialsFile(ScheduledServer server, String accessToken,
- {String refreshToken, DateTime expiration}) {
- return async(server.url.then((url) {
- return dir(
- cachePath,
- [
- file(
- 'credentials.json',
- new oauth2.Credentials(
- accessToken,
- refreshToken,
- url.resolve('/token'),
- ['https://www.googleapis.com/auth/userinfo.email'],
- expiration).toJson())]);
- }));
-}
-
-/// Describes the application directory, containing only a pubspec specifying
-/// the given [dependencies].
-DirectoryDescriptor appDir([Map dependencies]) =>
- dir(appPath, [appPubspec(dependencies)]);
diff --git a/sdk/lib/_internal/pub_generated/test/descriptor/git.dart b/sdk/lib/_internal/pub_generated/test/descriptor/git.dart
deleted file mode 100644
index 38ecdfa..0000000
--- a/sdk/lib/_internal/pub_generated/test/descriptor/git.dart
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright (c) 2013, 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 descriptor.git;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/descriptor.dart';
-
-import '../../lib/src/git.dart' as git;
-
-/// Describes a Git repository and its contents.
-class GitRepoDescriptor extends DirectoryDescriptor {
- GitRepoDescriptor(String name, List<Descriptor> contents)
- : super(name, contents);
-
- /// Creates the Git repository and commits the contents.
- Future create([String parent]) => schedule(() {
- return super.create(parent).then((_) {
- return _runGitCommands(
- parent,
- [['init'], ['add', '.'], ['commit', '-m', 'initial commit']]);
- });
- }, 'creating Git repo:\n${describe()}');
-
- /// Writes this descriptor to the filesystem, than commits any changes from
- /// the previous structure to the Git repo.
- ///
- /// [parent] defaults to [defaultRoot].
- Future commit([String parent]) => schedule(() {
- return super.create(parent).then((_) {
- return _runGitCommands(
- parent,
- [['add', '.'], ['commit', '-m', 'update']]);
- });
- }, 'committing Git repo:\n${describe()}');
-
- /// Return a Future that completes to the commit in the git repository
- /// referred to by [ref] at the current point in the scheduled test run.
- ///
- /// [parent] defaults to [defaultRoot].
- Future<String> revParse(String ref, [String parent]) => schedule(() {
- return _runGit(['rev-parse', ref], parent).then((output) => output[0]);
- }, 'parsing revision $ref for Git repo:\n${describe()}');
-
- /// Schedule a Git command to run in this repository.
- ///
- /// [parent] defaults to [defaultRoot].
- Future runGit(List<String> args, [String parent]) => schedule(() {
- return _runGit(args, parent);
- }, "running 'git ${args.join(' ')}' in Git repo:\n${describe()}");
-
- Future _runGitCommands(String parent, List<List<String>> commands) =>
- Future.forEach(commands, (command) => _runGit(command, parent));
-
- Future<List<String>> _runGit(List<String> args, String parent) {
- // Explicitly specify the committer information. Git needs this to commit
- // and we don't want to rely on the buildbots having this already set up.
- var environment = {
- 'GIT_AUTHOR_NAME': 'Pub Test',
- 'GIT_AUTHOR_EMAIL': 'pub@dartlang.org',
- 'GIT_COMMITTER_NAME': 'Pub Test',
- 'GIT_COMMITTER_EMAIL': 'pub@dartlang.org'
- };
-
- if (parent == null) parent = defaultRoot;
- return git.run(
- args,
- workingDir: path.join(parent, name),
- environment: environment);
- }
-}
-
diff --git a/sdk/lib/_internal/pub_generated/test/descriptor/tar.dart b/sdk/lib/_internal/pub_generated/test/descriptor/tar.dart
deleted file mode 100644
index 19280dc..0000000
--- a/sdk/lib/_internal/pub_generated/test/descriptor/tar.dart
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright (c) 2013, 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 descriptor.tar;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/descriptor.dart';
-
-import '../../lib/src/io.dart';
-
-/// Describes a tar file and its contents.
-class TarFileDescriptor extends DirectoryDescriptor implements
- ReadableDescriptor {
- TarFileDescriptor(String name, List<Descriptor> contents)
- : super(name, contents);
-
- /// Creates the files and directories within this tar file, then archives
- /// them, compresses them, and saves the result to [parentDir].
- Future<String> create([String parent]) => schedule(() {
- if (parent == null) parent = defaultRoot;
- return withTempDir((tempDir) {
- return Future.wait(contents.map((entry) {
- return entry.create(tempDir);
- })).then((_) {
- var createdContents =
- listDir(tempDir, recursive: true, includeHidden: true);
- return createTarGz(createdContents, baseDir: tempDir).toBytes();
- }).then((bytes) {
- var file = path.join(parent, name);
- writeBinaryFile(file, bytes);
- return file;
- });
- });
- }, 'creating tar file:\n${describe()}');
-
- /// Validates that the `.tar.gz` file at [path] contains the expected
- /// contents.
- Future validate([String parent]) {
- throw new UnimplementedError("TODO(nweiz): implement this");
- }
-
- Stream<List<int>> read() {
- return new Stream<List<int>>.fromFuture(withTempDir((tempDir) {
- return create(
- tempDir).then((_) => readBinaryFile(path.join(tempDir, name)));
- }));
- }
-}
diff --git a/sdk/lib/_internal/pub_generated/test/dev_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/dev_dependency_test.dart
deleted file mode 100644
index 31b181e..0000000
--- a/sdk/lib/_internal/pub_generated/test/dev_dependency_test.dart
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright (c) 2013, 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 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-main() {
- initConfig();
- integration("includes root package's dev dependencies", () {
- d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1')]).create();
-
- d.dir('bar', [d.libDir('bar'), d.libPubspec('bar', '0.0.1')]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dev_dependencies": {
- "foo": {
- "path": "../foo"
- },
- "bar": {
- "path": "../bar"
- },
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]),
- d.dir("bar", [d.file("bar.dart", 'main() => "bar";')])]).validate();
- });
-
- integration("includes dev dependency's transitive dependencies", () {
- d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1', deps: {
- "bar": {
- "path": "../bar"
- }
- })]).create();
-
- d.dir('bar', [d.libDir('bar'), d.libPubspec('bar', '0.0.1')]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dev_dependencies": {
- "foo": {
- "path": "../foo"
- }
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]),
- d.dir("bar", [d.file("bar.dart", 'main() => "bar";')])]).validate();
- });
-
- integration("ignores transitive dependency's dev dependencies", () {
- d.dir('foo', [d.libDir('foo'), d.pubspec({
- "name": "foo",
- "version": "0.0.1",
- "dev_dependencies": {
- "bar": {
- "path": "../bar"
- }
- }
- })]).create();
-
- d.dir('bar', [d.libDir('bar'), d.libPubspec('bar', '0.0.1')]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]),
- d.nothing("bar")]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/does_not_show_other_versions_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/does_not_show_other_versions_test.dart
deleted file mode 100644
index 2c49d31..0000000
--- a/sdk/lib/_internal/pub_generated/test/downgrade/does_not_show_other_versions_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2013, 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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("does not show how many other versions are available", () {
- servePackages((builder) {
- builder.serve("downgraded", "1.0.0");
- builder.serve("downgraded", "2.0.0");
- builder.serve("downgraded", "3.0.0-dev");
- });
-
- d.appDir({
- "downgraded": "3.0.0-dev"
- }).create();
-
- pubGet();
-
- // Loosen the constraints.
- d.appDir({
- "downgraded": ">=2.0.0"
- }).create();
-
- pubDowngrade(output: contains("downgraded 2.0.0 (was 3.0.0-dev)"));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/doesnt_change_git_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/doesnt_change_git_dependencies_test.dart
deleted file mode 100644
index 9d7b983..0000000
--- a/sdk/lib/_internal/pub_generated/test/downgrade/doesnt_change_git_dependencies_test.dart
+++ /dev/null
@@ -1,37 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("doesn't change git dependencies", () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- pubDowngrade();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/dry_run_does_not_apply_changes_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/dry_run_does_not_apply_changes_test.dart
deleted file mode 100644
index 3b0c9d1..0000000
--- a/sdk/lib/_internal/pub_generated/test/downgrade/dry_run_does_not_apply_changes_test.dart
+++ /dev/null
@@ -1,48 +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:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("--dry-run shows report but does not apply changes", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "2.0.0");
- });
-
- // Create the first lockfile.
- d.appDir({
- "foo": "2.0.0"
- }).create();
-
- pubGet();
-
- // Change the pubspec.
- d.appDir({
- "foo": "any"
- }).create();
-
- // Also delete the "packages" directory.
- schedule(() {
- deleteEntry(path.join(sandboxDir, appPath, "packages"));
- });
-
- // Do the dry run.
- pubDowngrade(
- args: ["--dry-run"],
- output: allOf(
- [contains("< foo 1.0.0"), contains("Would change 1 dependency.")]));
-
- d.dir(appPath, [// The lockfile should be unmodified.
- d.matcherFile("pubspec.lock", contains("2.0.0")),
- // The "packages" directory should not have been regenerated.
- d.nothing("packages")]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/unlock_dependers_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/unlock_dependers_test.dart
deleted file mode 100644
index 4140a5f..0000000
--- a/sdk/lib/_internal/pub_generated/test/downgrade/unlock_dependers_test.dart
+++ /dev/null
@@ -1,48 +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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "downgrades a locked package's dependers in order to get it to " "min version",
- () {
- servePackages((builder) {
- builder.serve("foo", "2.0.0", deps: {
- "bar": ">1.0.0"
- });
- builder.serve("bar", "2.0.0");
- });
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "2.0.0",
- "bar": "2.0.0"
- }).validate();
-
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "bar": "any"
- });
- builder.serve("bar", "1.0.0");
- });
-
- pubDowngrade(args: ['bar']);
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/unlock_if_necessary_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/unlock_if_necessary_test.dart
deleted file mode 100644
index 6eab79a..0000000
--- a/sdk/lib/_internal/pub_generated/test/downgrade/unlock_if_necessary_test.dart
+++ /dev/null
@@ -1,47 +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.
-
-library pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "downgrades one locked hosted package's dependencies if it's " "necessary",
- () {
- servePackages((builder) {
- builder.serve("foo", "2.0.0", deps: {
- "foo_dep": "any"
- });
- builder.serve("foo_dep", "2.0.0");
- });
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "2.0.0",
- "foo_dep": "2.0.0"
- }).validate();
-
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "foo_dep": "<2.0.0"
- });
- builder.serve("foo_dep", "1.0.0");
- });
-
- pubDowngrade(args: ['foo']);
-
- d.packagesDir({
- "foo": "1.0.0",
- "foo_dep": "1.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/error_group_test.dart b/sdk/lib/_internal/pub_generated/test/error_group_test.dart
deleted file mode 100644
index 3589b3e..0000000
--- a/sdk/lib/_internal/pub_generated/test/error_group_test.dart
+++ /dev/null
@@ -1,520 +0,0 @@
-// Copyright (c) 2013, 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 error_group_test;
-
-import 'dart:async';
-
-import 'package:unittest/unittest.dart';
-
-import '../lib/src/error_group.dart';
-import '../lib/src/utils.dart';
-
-ErrorGroup errorGroup;
-
-// TODO(nweiz): once there's a global error handler, we should test that it does
-// and does not get called at appropriate times. See issue 5958.
-//
-// One particular thing we should test that has no tests now is that a stream
-// that has a subscription added and subsequently canceled counts as having no
-// listeners.
-
-main() {
- group('with no futures or streams', () {
- setUp(() {
- errorGroup = new ErrorGroup();
- });
-
- test('should pass signaled errors to .done', () {
- expect(errorGroup.done, throwsFormatException);
- errorGroup.signalError(new FormatException());
- });
-
- test(
- "shouldn't allow additional futures or streams once an error has been "
- "signaled",
- () {
- expect(errorGroup.done, throwsFormatException);
- errorGroup.signalError(new FormatException());
-
- expect(
- () => errorGroup.registerFuture(new Future.value()),
- throwsStateError);
- expect(
- () => errorGroup.registerStream(new StreamController(sync: true).stream),
- throwsStateError);
- });
- });
-
- group('with a single future', () {
- Completer completer;
- Future future;
-
- setUp(() {
- errorGroup = new ErrorGroup();
- completer = new Completer();
- future = errorGroup.registerFuture(completer.future);
- });
-
- test('should pass through a value from the future', () {
- expect(future, completion(equals('value')));
- expect(errorGroup.done, completes);
- completer.complete('value');
- });
-
- test(
- "shouldn't allow additional futures or streams once .done has " "been called",
- () {
- completer.complete('value');
-
- expect(
- completer.future.then((_) => errorGroup.registerFuture(new Future.value())),
- throwsStateError);
- expect(
- completer.future.then(
- (_) => errorGroup.registerStream(new StreamController(sync: true).stream)),
- throwsStateError);
- });
-
- test(
- 'should pass through an exception from the future if it has a ' 'listener',
- () {
- expect(future, throwsFormatException);
- // errorGroup shouldn't top-level the exception
- completer.completeError(new FormatException());
- });
-
- test(
- 'should notify the error group of an exception from the future even '
- 'if it has a listener',
- () {
- expect(future, throwsFormatException);
- expect(errorGroup.done, throwsFormatException);
- completer.completeError(new FormatException());
- });
-
- test(
- 'should pass a signaled exception to the future if it has a listener '
- 'and should ignore a subsequent value from that future',
- () {
- expect(future, throwsFormatException);
- // errorGroup shouldn't top-level the exception
- errorGroup.signalError(new FormatException());
- completer.complete('value');
- });
-
- test(
- 'should pass a signaled exception to the future if it has a listener '
- 'and should ignore a subsequent exception from that future',
- () {
- expect(future, throwsFormatException);
- // errorGroup shouldn't top-level the exception
- errorGroup.signalError(new FormatException());
- completer.completeError(new ArgumentError());
- });
-
- test(
- 'should notify the error group of a signaled exception even if the '
- 'future has a listener',
- () {
- expect(future, throwsFormatException);
- expect(errorGroup.done, throwsFormatException);
- errorGroup.signalError(new FormatException());
- });
-
- test(
- "should complete .done if the future receives a value even if the "
- "future doesn't have a listener",
- () {
- expect(errorGroup.done, completes);
- completer.complete('value');
-
- // A listener added afterwards should receive the value
- expect(errorGroup.done.then((_) => future), completion(equals('value')));
- });
-
- test(
- "should pipe an exception from the future to .done if the future "
- "doesn't have a listener",
- () {
- expect(errorGroup.done, throwsFormatException);
- completer.completeError(new FormatException());
-
- // A listener added afterwards should receive the exception
- expect(errorGroup.done.catchError((_) {
- expect(future, throwsFormatException);
- }), completes);
- });
-
- test(
- "should pass a signaled exception to .done if the future doesn't have "
- "a listener",
- () {
- expect(errorGroup.done, throwsFormatException);
- errorGroup.signalError(new FormatException());
-
- // A listener added afterwards should receive the exception
- expect(errorGroup.done.catchError((_) {
- completer.complete('value'); // should be ignored
- expect(future, throwsFormatException);
- }), completes);
- });
- });
-
- group('with multiple futures', () {
- Completer completer1;
- Completer completer2;
- Future future1;
- Future future2;
-
- setUp(() {
- errorGroup = new ErrorGroup();
- completer1 = new Completer();
- completer2 = new Completer();
- future1 = errorGroup.registerFuture(completer1.future);
- future2 = errorGroup.registerFuture(completer2.future);
- });
-
- test(
- "should pipe exceptions from one future to the other and to " ".complete",
- () {
- expect(future1, throwsFormatException);
- expect(future2, throwsFormatException);
- expect(errorGroup.done, throwsFormatException);
-
- completer1.completeError(new FormatException());
- });
-
- test(
- "each future should be able to complete with a value " "independently",
- () {
- expect(future1, completion(equals('value1')));
- expect(future2, completion(equals('value2')));
- expect(errorGroup.done, completes);
-
- completer1.complete('value1');
- completer2.complete('value2');
- });
-
- test(
- "shouldn't throw a top-level exception if a future receives an error "
- "after the other listened future completes",
- () {
- expect(future1, completion(equals('value')));
- completer1.complete('value');
-
- expect(future1.then((_) {
- // shouldn't cause a top-level exception
- completer2.completeError(new FormatException());
- }), completes);
- });
-
- test(
- "shouldn't throw a top-level exception if an error is signaled after "
- "one listened future completes",
- () {
- expect(future1, completion(equals('value')));
- completer1.complete('value');
-
- expect(future1.then((_) {
- // shouldn't cause a top-level exception
- errorGroup.signalError(new FormatException());
- }), completes);
- });
- });
-
- group('with a single stream', () {
- StreamController controller;
- Stream stream;
-
- setUp(() {
- errorGroup = new ErrorGroup();
- controller = new StreamController.broadcast(sync: true);
- stream = errorGroup.registerStream(controller.stream);
- });
-
- test('should pass through values from the stream', () {
- StreamIterator iter = new StreamIterator(stream);
- iter.moveNext().then((hasNext) {
- expect(hasNext, isTrue);
- expect(iter.current, equals(1));
- iter.moveNext().then((hasNext) {
- expect(hasNext, isTrue);
- expect(iter.current, equals(2));
- expect(iter.moveNext(), completion(isFalse));
- });
- });
- expect(errorGroup.done, completes);
-
- controller
- ..add(1)
- ..add(2)
- ..close();
- });
-
- test(
- 'should pass through an error from the stream if it has a ' 'listener',
- () {
- expect(stream.first, throwsFormatException);
- // errorGroup shouldn't top-level the exception
- controller.addError(new FormatException());
- });
-
- test(
- 'should notify the error group of an exception from the stream even '
- 'if it has a listener',
- () {
- expect(stream.first, throwsFormatException);
- expect(errorGroup.done, throwsFormatException);
- controller.addError(new FormatException());
- });
-
- test(
- 'should pass a signaled exception to the stream if it has a listener '
- 'and should unsubscribe that stream',
- () {
- // errorGroup shouldn't top-level the exception
- expect(stream.first, throwsFormatException);
- errorGroup.signalError(new FormatException());
-
- expect(newFuture(() {
- controller.add('value');
- }), completes);
- });
-
- test(
- 'should notify the error group of a signaled exception even if the '
- 'stream has a listener',
- () {
- expect(stream.first, throwsFormatException);
- expect(errorGroup.done, throwsFormatException);
- errorGroup.signalError(new FormatException());
- });
-
- test(
- "should see one value and complete .done when the stream is done even "
- "if the stream doesn't have a listener",
- () {
- expect(errorGroup.done, completes);
- controller.add('value');
- controller.close();
-
- // Now that broadcast controllers have been removed a listener should
- // see the value that has been put into the controller.
- expect(
- errorGroup.done.then((_) => stream.toList()),
- completion(equals(['value'])));
- });
-
- });
-
- group('with a single single-subscription stream', () {
- StreamController controller;
- Stream stream;
-
- setUp(() {
- errorGroup = new ErrorGroup();
- controller = new StreamController(sync: true);
- stream = errorGroup.registerStream(controller.stream);
- });
-
- test(
- "should complete .done when the stream is done even if the stream "
- "doesn't have a listener",
- () {
- expect(errorGroup.done, completes);
- controller.add('value');
- controller.close();
-
- // A listener added afterwards should receive the value
- expect(
- errorGroup.done.then((_) => stream.toList()),
- completion(equals(['value'])));
- });
-
- test(
- "should pipe an exception from the stream to .done if the stream "
- "doesn't have a listener",
- () {
- expect(errorGroup.done, throwsFormatException);
- controller.addError(new FormatException());
-
- // A listener added afterwards should receive the exception
- expect(errorGroup.done.catchError((_) {
- controller.add('value'); // should be ignored
- expect(stream.first, throwsFormatException);
- }), completes);
- });
-
- test(
- "should pass a signaled exception to .done if the stream doesn't "
- "have a listener",
- () {
- expect(errorGroup.done, throwsFormatException);
- errorGroup.signalError(new FormatException());
-
- // A listener added afterwards should receive the exception
- expect(errorGroup.done.catchError((_) {
- controller.add('value'); // should be ignored
- expect(stream.first, throwsFormatException);
- }), completes);
- });
- });
-
- group('with multiple streams', () {
- StreamController controller1;
- StreamController controller2;
- Stream stream1;
- Stream stream2;
-
- setUp(() {
- errorGroup = new ErrorGroup();
- controller1 = new StreamController.broadcast(sync: true);
- controller2 = new StreamController.broadcast(sync: true);
- stream1 = errorGroup.registerStream(controller1.stream);
- stream2 = errorGroup.registerStream(controller2.stream);
- });
-
- test(
- "should pipe exceptions from one stream to the other and to .done",
- () {
- expect(stream1.first, throwsFormatException);
- expect(stream2.first, throwsFormatException);
- expect(errorGroup.done, throwsFormatException);
-
- controller1.addError(new FormatException());
- });
-
- test("each future should be able to emit values independently", () {
- expect(stream1.toList(), completion(equals(['value1.1', 'value1.2'])));
- expect(stream2.toList(), completion(equals(['value2.1', 'value2.2'])));
- expect(errorGroup.done, completes);
-
- controller1
- ..add('value1.1')
- ..add('value1.2')
- ..close();
- controller2
- ..add('value2.1')
- ..add('value2.2')
- ..close();
- });
-
- test(
- "shouldn't throw a top-level exception if a stream receives an error "
- "after the other listened stream completes",
- () {
- var signal = new Completer();
- expect(
- stream1.toList().whenComplete(signal.complete),
- completion(equals(['value1', 'value2'])));
- controller1
- ..add('value1')
- ..add('value2')
- ..close();
-
- expect(signal.future.then((_) {
- // shouldn't cause a top-level exception
- controller2.addError(new FormatException());
- }), completes);
- });
-
- test(
- "shouldn't throw a top-level exception if an error is signaled after "
- "one listened stream completes",
- () {
- var signal = new Completer();
- expect(
- stream1.toList().whenComplete(signal.complete),
- completion(equals(['value1', 'value2'])));
- controller1
- ..add('value1')
- ..add('value2')
- ..close();
-
- expect(signal.future.then((_) {
- // shouldn't cause a top-level exception
- errorGroup.signalError(new FormatException());
- }), completes);
- });
- });
-
- group('with a stream and a future', () {
- StreamController controller;
- Stream stream;
- Completer completer;
- Future future;
-
- setUp(() {
- errorGroup = new ErrorGroup();
- controller = new StreamController.broadcast(sync: true);
- stream = errorGroup.registerStream(controller.stream);
- completer = new Completer();
- future = errorGroup.registerFuture(completer.future);
- });
-
- test("should pipe exceptions from the stream to the future", () {
- expect(stream.first, throwsFormatException);
- expect(future, throwsFormatException);
- expect(errorGroup.done, throwsFormatException);
-
- controller.addError(new FormatException());
- });
-
- test("should pipe exceptions from the future to the stream", () {
- expect(stream.first, throwsFormatException);
- expect(future, throwsFormatException);
- expect(errorGroup.done, throwsFormatException);
-
- completer.completeError(new FormatException());
- });
-
- test(
- "the stream and the future should be able to complete/emit values "
- "independently",
- () {
- expect(stream.toList(), completion(equals(['value1.1', 'value1.2'])));
- expect(future, completion(equals('value2.0')));
- expect(errorGroup.done, completes);
-
- controller
- ..add('value1.1')
- ..add('value1.2')
- ..close();
- completer.complete('value2.0');
- });
-
- test(
- "shouldn't throw a top-level exception if the stream receives an error "
- "after the listened future completes",
- () {
- expect(future, completion(equals('value')));
- completer.complete('value');
-
- expect(future.then((_) {
- // shouldn't cause a top-level exception
- controller.addError(new FormatException());
- }), completes);
- });
-
- test(
- "shouldn't throw a top-level exception if the future receives an "
- "error after the listened stream completes",
- () {
- var signal = new Completer();
- expect(
- stream.toList().whenComplete(signal.complete),
- completion(equals(['value1', 'value2'])));
- controller
- ..add('value1')
- ..add('value2')
- ..close();
-
- expect(signal.future.then((_) {
- // shouldn't cause a top-level exception
- completer.completeError(new FormatException());
- }), completes);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/broken_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/broken_symlink_test.dart
deleted file mode 100644
index eb3646c..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/broken_symlink_test.dart
+++ /dev/null
@@ -1,51 +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 pub_tests;
-
-import 'package:path/path.dart' as path;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('replaces a broken "packages" symlink', () {
- d.dir(appPath, [d.appPubspec(), d.libDir('foo'), d.dir("bin")]).create();
-
- // Create a broken "packages" symlink in "bin".
- scheduleSymlink("nonexistent", path.join(appPath, "packages"));
-
- pubGet();
-
- d.dir(
- appPath,
- [
- d.dir(
- "bin",
- [
- d.dir(
- "packages",
- [d.dir("myapp", [d.file('foo.dart', 'main() => "foo";')])])])]).validate();
- });
-
- integration('replaces a broken secondary "packages" symlink', () {
- d.dir(appPath, [d.appPubspec(), d.libDir('foo'), d.dir("bin")]).create();
-
- // Create a broken "packages" symlink in "bin".
- scheduleSymlink("nonexistent", path.join(appPath, "bin", "packages"));
-
- pubGet();
-
- d.dir(
- appPath,
- [
- d.dir(
- "bin",
- [
- d.dir(
- "packages",
- [d.dir("myapp", [d.file('foo.dart', 'main() => "foo";')])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/cache_transformed_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/get/cache_transformed_dependency_test.dart
deleted file mode 100644
index 222e974..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/cache_transformed_dependency_test.dart
+++ /dev/null
@@ -1,477 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const MODE_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class ModeTransformer extends Transformer {
- final BarbackSettings _settings;
-
- ModeTransformer.asPlugin(this._settings);
-
- String get allowedExtensions => '.dart';
-
- void apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- transform.addOutput(new Asset.fromString(
- transform.primaryInput.id,
- contents.replaceAll("MODE", _settings.mode.name)));
- });
- }
-}
-""";
-
-const HAS_INPUT_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class HasInputTransformer extends Transformer {
- HasInputTransformer.asPlugin();
-
- bool get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return Future.wait([
- transform.hasInput(new AssetId("foo", "lib/foo.dart")),
- transform.hasInput(new AssetId("foo", "lib/does/not/exist.dart"))
- ]).then((results) {
- transform.addOutput(new Asset.fromString(
- transform.primaryInput.id,
- "lib/foo.dart: \${results.first}, "
- "lib/does/not/exist.dart: \${results.last}"));
- });
- }
-}
-""";
-
-main() {
- initConfig();
-
- integration("caches a transformed dependency", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")),
- d.file("foo.dart", "final message = 'Hello!';")])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/deps/debug/foo/lib",
- [d.file("foo.dart", "final message = 'Goodbye!';")])]).validate();
- });
-
- integration("caches a dependency transformed by its dependency", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'bar': '1.2.3'
- }, pubspec: {
- 'transformers': ['bar']
- },
- contents: [d.dir("lib", [d.file("foo.dart", "final message = 'Hello!';")])]);
-
- builder.serve("bar", "1.2.3", deps: {
- 'barback': 'any'
- },
- contents: [
- d.dir(
- "lib",
- [d.file("transformer.dart", replaceTransformer("Hello", "Goodbye"))])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/deps/debug/foo/lib",
- [d.file("foo.dart", "final message = 'Goodbye!';")])]).validate();
- });
-
- integration("doesn't cache an untransformed dependency", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve(
- "foo",
- "1.2.3",
- contents: [d.dir("lib", [d.file("foo.dart", "final message = 'Hello!';")])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(output: isNot(contains("Precompiled foo.")));
-
- d.dir(appPath, [d.nothing(".pub/deps")]).validate();
- });
-
- integration("recaches when the dependency is updated", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")),
- d.file("foo.dart", "final message = 'Hello!';")])]);
-
- builder.serve("foo", "1.2.4", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "See ya")),
- d.file("foo.dart", "final message = 'Hello!';")])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/deps/debug/foo/lib",
- [d.file("foo.dart", "final message = 'Goodbye!';")])]).validate();
-
- // Upgrade to the new version of foo.
- d.appDir({
- "foo": "1.2.4"
- }).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/deps/debug/foo/lib",
- [d.file("foo.dart", "final message = 'See ya!';")])]).validate();
- });
-
- integration("recaches when a transitive dependency is updated", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any',
- 'bar': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")),
- d.file("foo.dart", "final message = 'Hello!';")])]);
-
- builder.serve("bar", "5.6.7");
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
- pubGet(output: contains("Precompiled foo."));
-
- servePackages((builder) => builder.serve("bar", "6.0.0"));
- pubUpgrade(output: contains("Precompiled foo."));
- });
-
- integration("doesn't recache when an unrelated dependency is updated", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")),
- d.file("foo.dart", "final message = 'Hello!';")])]);
-
- builder.serve("bar", "5.6.7");
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
- pubGet(output: contains("Precompiled foo."));
-
- servePackages((builder) => builder.serve("bar", "6.0.0"));
- pubUpgrade(output: isNot(contains("Precompiled foo.")));
- });
-
- integration("caches the dependency in debug mode", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", MODE_TRANSFORMER),
- d.file("foo.dart", "final mode = 'MODE';")])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/deps/debug/foo/lib",
- [d.file("foo.dart", "final mode = 'debug';")])]).validate();
- });
-
- integration("loads code from the cache", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")),
- d.file("foo.dart", "final message = 'Hello!';")])]);
- });
-
- d.dir(appPath, [d.appPubspec({
- "foo": "1.2.3"
- }), d.dir('bin', [d.file('script.dart', """
- import 'package:foo/foo.dart';
-
- void main() => print(message);""")])]).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/deps/debug/foo/lib",
- [d.file("foo.dart", "final message = 'Modified!';")])]).create();
-
- var pub = pubRun(args: ["script"]);
- pub.stdout.expect("Modified!");
- pub.shouldExit();
- });
-
- integration("doesn't re-transform code loaded from the cache", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")),
- d.file("foo.dart", "final message = 'Hello!';")])]);
- });
-
- d.dir(appPath, [d.appPubspec({
- "foo": "1.2.3"
- }), d.dir('bin', [d.file('script.dart', """
- import 'package:foo/foo.dart';
-
- void main() => print(message);""")])]).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- // Manually reset the cache to its original state to prove that the
- // transformer won't be run again on it.
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/deps/debug/foo/lib",
- [d.file("foo.dart", "final message = 'Hello!';")])]).create();
-
- var pub = pubRun(args: ["script"]);
- pub.stdout.expect("Hello!");
- pub.shouldExit();
- });
-
- // Regression test for issue 21087.
- integration("hasInput works for static packages", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")),
- d.file("foo.dart", "void main() => print('Hello!');")])]);
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "1.2.3"
- },
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [d.dir("src", [d.file("transformer.dart", HAS_INPUT_TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- pubServe();
- requestShouldSucceed(
- "foo.txt",
- "lib/foo.dart: true, lib/does/not/exist.dart: false");
- endPubServe();
- });
-
- // Regression test for issue 21810.
- integration(
- "decaches when the dependency is updated to something " "untransformed",
- () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir(
- "lib",
- [
- d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")),
- d.file("foo.dart", "final message = 'Hello!';")])]);
-
- builder.serve("foo", "1.2.4", deps: {
- 'barback': 'any'
- },
- contents: [d.dir("lib", [d.file("foo.dart", "final message = 'Hello!';")])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(output: contains("Precompiled foo."));
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/deps/debug/foo/lib",
- [d.file("foo.dart", "final message = 'Goodbye!';")])]).validate();
-
- // Upgrade to the new version of foo.
- d.appDir({
- "foo": "1.2.4"
- }).create();
-
- pubGet(output: isNot(contains("Precompiled foo.")));
-
- d.dir(appPath, [d.nothing(".pub/deps/debug/foo")]).validate();
- });
-}
-
-String replaceTransformer(String input, String output) {
- return """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class ReplaceTransformer extends Transformer {
- ReplaceTransformer.asPlugin();
-
- String get allowedExtensions => '.dart';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- transform.addOutput(new Asset.fromString(
- transform.primaryInput.id,
- contents.replaceAll("$input", "$output")));
- });
- }
-}
-""";
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/dry_run_does_not_apply_changes_test.dart b/sdk/lib/_internal/pub_generated/test/get/dry_run_does_not_apply_changes_test.dart
deleted file mode 100644
index a23d6bd..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/dry_run_does_not_apply_changes_test.dart
+++ /dev/null
@@ -1,31 +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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("--dry-run shows but does not apply changes", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- });
-
- d.appDir({
- "foo": "1.0.0"
- }).create();
-
- pubGet(
- args: ["--dry-run"],
- output: allOf(
- [contains("+ foo 1.0.0"), contains("Would change 1 dependency.")]));
-
- d.dir(appPath, [// The lockfile should not be created.
- d.nothing("pubspec.lock"),
- // The "packages" directory should not have been generated.
- d.nothing("packages")]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_and_upgrade_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_and_upgrade_test.dart
deleted file mode 100644
index 9936664..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_and_upgrade_test.dart
+++ /dev/null
@@ -1,62 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('checks out and upgrades a package from Git', () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'git',
- [
- d.dir('cache', [d.gitPackageRepoCacheDir('foo')]),
- d.gitPackageRevisionCacheDir('foo')])]).validate();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- pubUpgrade(output: contains("Changed 1 dependency!"));
-
- // When we download a new version of the git package, we should re-use the
- // git/cache directory but create a new git/ directory.
- d.dir(
- cachePath,
- [
- d.dir(
- 'git',
- [
- d.dir('cache', [d.gitPackageRepoCacheDir('foo')]),
- d.gitPackageRevisionCacheDir('foo'),
- d.gitPackageRevisionCacheDir('foo', 2)])]).validate();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_branch_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_branch_test.dart
deleted file mode 100644
index bc40b99..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_branch_test.dart
+++ /dev/null
@@ -1,39 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('checks out a package at a specific branch from Git', () {
- ensureGit();
-
- var repo =
- d.git('foo.git', [d.libDir('foo', 'foo 1'), d.libPubspec('foo', '1.0.0')]);
- repo.create();
- repo.runGit(["branch", "old"]);
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- d.appDir({
- "foo": {
- "git": {
- "url": "../foo.git",
- "ref": "old"
- }
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_revision_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_revision_test.dart
deleted file mode 100644
index 3f65f8d..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_revision_test.dart
+++ /dev/null
@@ -1,39 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('checks out a package at a specific revision from Git', () {
- ensureGit();
-
- var repo =
- d.git('foo.git', [d.libDir('foo', 'foo 1'), d.libPubspec('foo', '1.0.0')]);
- repo.create();
- var commit = repo.revParse('HEAD');
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- d.appDir({
- "foo": {
- "git": {
- "url": "../foo.git",
- "ref": commit
- }
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_test.dart
deleted file mode 100644
index 9e25aad..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_test.dart
+++ /dev/null
@@ -1,38 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('checks out a package from Git', () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'git',
- [
- d.dir('cache', [d.gitPackageRepoCacheDir('foo')]),
- d.gitPackageRevisionCacheDir('foo')])]).validate();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_transitive_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_transitive_test.dart
deleted file mode 100644
index b2b1047..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_transitive_test.dart
+++ /dev/null
@@ -1,49 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('checks out packages transitively from Git', () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0', deps: {
- "bar": {
- "git": "../bar.git"
- }
- })]).create();
-
- d.git('bar.git', [d.libDir('bar'), d.libPubspec('bar', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'git',
- [
- d.dir(
- 'cache',
- [d.gitPackageRepoCacheDir('foo'), d.gitPackageRepoCacheDir('bar')]),
- d.gitPackageRevisionCacheDir('foo'),
- d.gitPackageRevisionCacheDir('bar')])]).validate();
-
- d.dir(
- packagesPath,
- [
- d.dir('foo', [d.file('foo.dart', 'main() => "foo";')]),
- d.dir('bar', [d.file('bar.dart', 'main() => "bar";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_twice_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_twice_test.dart
deleted file mode 100644
index 6a7c9c7..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_twice_test.dart
+++ /dev/null
@@ -1,42 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('checks out a package from Git twice', () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'git',
- [
- d.dir('cache', [d.gitPackageRepoCacheDir('foo')]),
- d.gitPackageRevisionCacheDir('foo')])]).validate();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- // Verify that nothing breaks if we get a Git revision that's already
- // in the cache.
- pubUpgrade();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_unfetched_revision_of_cached_repo_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_unfetched_revision_of_cached_repo_test.dart
deleted file mode 100644
index 277f2d1..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_unfetched_revision_of_cached_repo_test.dart
+++ /dev/null
@@ -1,71 +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 pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- // Regression test for issue 20947.
- integration(
- 'checks out an unfetched and locked revision of a cached ' 'repository',
- () {
- ensureGit();
-
- // In order to get a lockfile that refers to a newer revision than is in the
- // cache, we'll switch between two caches. First we ensure that the repo is
- // in the first cache.
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- // Switch to a new cache.
- schedule(
- () =>
- renameDir(p.join(sandboxDir, cachePath), p.join(sandboxDir, "$cachePath.old")));
-
- // Make the lockfile point to a new revision of the git repository.
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- pubUpgrade(output: contains("Changed 1 dependency!"));
-
- // Switch back to the old cache.
- schedule(() {
- var cacheDir = p.join(sandboxDir, cachePath);
- deleteEntry(cacheDir);
- renameDir(p.join(sandboxDir, "$cachePath.old"), cacheDir);
- });
-
- // Get the updated version of the git dependency based on the lockfile.
- pubGet();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'git',
- [
- d.dir('cache', [d.gitPackageRepoCacheDir('foo')]),
- d.gitPackageRevisionCacheDir('foo'),
- d.gitPackageRevisionCacheDir('foo', 2)])]).validate();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_with_trailing_slash_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_with_trailing_slash_test.dart
deleted file mode 100644
index 345ff4f..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_with_trailing_slash_test.dart
+++ /dev/null
@@ -1,44 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- group("(regression)", () {
- integration('checks out a package from Git with a trailing slash', () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git/"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'git',
- [
- d.dir('cache', [d.gitPackageRepoCacheDir('foo')]),
- d.gitPackageRevisionCacheDir('foo')])]).validate();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/dependency_name_match_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/dependency_name_match_pubspec_test.dart
deleted file mode 100644
index 86b3a2e..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/dependency_name_match_pubspec_test.dart
+++ /dev/null
@@ -1,32 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'requires the dependency name to match the remote pubspec ' 'name',
- () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.dir(appPath, [d.appPubspec({
- "weirdname": {
- "git": "../foo.git"
- }
- })]).create();
-
- pubGet(
- error: contains('"name" field doesn\'t match expected name ' '"weirdname".'),
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/different_repo_name_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/different_repo_name_test.dart
deleted file mode 100644
index e6e0173..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/different_repo_name_test.dart
+++ /dev/null
@@ -1,36 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'doesn\'t require the repository name to match the name in the ' 'pubspec',
- () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [d.libDir('weirdname'), d.libPubspec('weirdname', '1.0.0')]).create();
-
- d.dir(appPath, [d.appPubspec({
- "weirdname": {
- "git": "../foo.git"
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir(
- 'weirdname',
- [d.file('weirdname.dart', 'main() => "weirdname";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/doesnt_fetch_if_nothing_changes_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/doesnt_fetch_if_nothing_changes_test.dart
deleted file mode 100644
index c776a75..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/doesnt_fetch_if_nothing_changes_test.dart
+++ /dev/null
@@ -1,47 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("doesn't re-fetch a repository if nothing changes", () {
- ensureGit();
-
- var repo =
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]);
- repo.create();
-
- d.appDir({
- "foo": {
- "git": {
- "url": "../foo.git"
- }
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- // Delete the repo. This will cause "pub get" to fail if it tries to
- // re-fetch.
- schedule(() => deleteEntry(p.join(sandboxDir, 'foo.git')));
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/lock_version_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/lock_version_test.dart
deleted file mode 100644
index 63acc2c..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/lock_version_test.dart
+++ /dev/null
@@ -1,48 +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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('keeps a Git package locked to the version in the lockfile', () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- // This get should lock the foo.git dependency to the current revision.
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- // Delete the packages path to simulate a new checkout of the application.
- schedule(() => deleteEntry(path.join(sandboxDir, packagesPath)));
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- // This get shouldn't upgrade the foo.git dependency due to the lockfile.
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/locked_revision_without_repo_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/locked_revision_without_repo_test.dart
deleted file mode 100644
index ef31eb4..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/locked_revision_without_repo_test.dart
+++ /dev/null
@@ -1,52 +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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-// Regression test for issue 16470.
-
-main() {
- initConfig();
- integration('checks out the repository for a locked revision', () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- // This get should lock the foo.git dependency to the current revision.
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- // Delete the packages path and the cache to simulate a brand new checkout
- // of the application.
- schedule(() => deleteEntry(path.join(sandboxDir, packagesPath)));
- schedule(() => deleteEntry(path.join(sandboxDir, cachePath)));
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- // This get shouldn't upgrade the foo.git dependency due to the lockfile.
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_name_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_name_test.dart
deleted file mode 100644
index 2b0acbf..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_name_test.dart
+++ /dev/null
@@ -1,32 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'requires the dependency to have a pubspec with a name ' 'field',
- () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.pubspec({})]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet(
- error: contains('Missing the required "name" field.'),
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_test.dart
deleted file mode 100644
index a81e376..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_test.dart
+++ /dev/null
@@ -1,27 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('requires the dependency to have a pubspec', () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet(
- error: new RegExp(
- r'Could not find a file named "pubspec\.yaml" ' r'in "[^\n]*"\.'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/stay_locked_if_compatible_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/stay_locked_if_compatible_test.dart
deleted file mode 100644
index 962efb2..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/stay_locked_if_compatible_test.dart
+++ /dev/null
@@ -1,50 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "doesn't upgrade a locked Git package with a new compatible " "constraint",
- () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 1.0.0'), d.libPubspec("foo", "1.0.0")]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1.0.0";')])]).validate();
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 1.0.1'), d.libPubspec("foo", "1.0.1")]).commit();
-
- d.appDir({
- "foo": {
- "git": "../foo.git",
- "version": ">=1.0.0"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1.0.0";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/git/unlock_if_incompatible_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/unlock_if_incompatible_test.dart
deleted file mode 100644
index 588ee28..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/git/unlock_if_incompatible_test.dart
+++ /dev/null
@@ -1,48 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'upgrades a locked Git package with a new incompatible ' 'constraint',
- () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '0.5.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 1.0.0'), d.libPubspec("foo", "1.0.0")]).commit();
-
- d.appDir({
- "foo": {
- "git": "../foo.git",
- "version": ">=1.0.0"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1.0.0";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/avoid_network_requests_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/avoid_network_requests_test.dart
deleted file mode 100644
index 3421e8f..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/avoid_network_requests_test.dart
+++ /dev/null
@@ -1,61 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
-
- integration('only requests versions that are needed during solving', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "1.1.0");
- builder.serve("foo", "1.2.0");
- builder.serve("bar", "1.0.0");
- builder.serve("bar", "1.1.0");
- builder.serve("bar", "1.2.0");
- });
-
- d.appDir({
- "foo": "any"
- }).create();
-
- // Get once so it gets cached.
- pubGet();
-
- // Clear the cache. We don't care about anything that was served during
- // the initial get.
- getRequestedPaths();
-
- // Add "bar" to the dependencies.
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- // Run the solver again.
- pubGet();
-
- d.packagesDir({
- "foo": "1.2.0",
- "bar": "1.2.0"
- }).validate();
-
- // The get should not have done any network requests since the lock file is
- // up to date.
- getRequestedPaths().then((paths) {
- expect(
- paths,
- unorderedEquals([// Bar should be requested because it's new, but not foo.
- "api/packages/bar", // Should only request the most recent version.
- "api/packages/bar/versions/1.2.0", // Need to download it.
- "packages/bar/versions/1.2.0.tar.gz"]));
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/cached_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/cached_pubspec_test.dart
deleted file mode 100644
index 750ef6d..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/cached_pubspec_test.dart
+++ /dev/null
@@ -1,44 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
-
- integration('does not request a pubspec for a cached package', () {
- servePackages((builder) => builder.serve("foo", "1.2.3"));
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- // Get once so it gets cached.
- pubGet();
-
- // Clear the cache. We don't care about anything that was served during
- // the initial get.
- getRequestedPaths();
-
- d.cacheDir({
- "foo": "1.2.3"
- }).validate();
- d.packagesDir({
- "foo": "1.2.3"
- }).validate();
-
- // Run the solver again now that it's cached.
- pubGet();
-
- // The get should not have requested the pubspec since it's local already.
- getRequestedPaths().then((paths) {
- expect(paths, isNot(contains("packages/foo/versions/1.2.3.yaml")));
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/do_not_upgrade_on_removed_constraints_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/do_not_upgrade_on_removed_constraints_test.dart
deleted file mode 100644
index b3da83d..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/do_not_upgrade_on_removed_constraints_test.dart
+++ /dev/null
@@ -1,51 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "doesn't upgrade dependencies whose constraints have been " "removed",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "shared-dep": "any"
- });
- builder.serve("bar", "1.0.0", deps: {
- "shared-dep": "<2.0.0"
- });
- builder.serve("shared-dep", "1.0.0");
- builder.serve("shared-dep", "2.0.0");
- });
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0",
- "shared-dep": "1.0.0"
- }).validate();
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": null,
- "shared-dep": "1.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/does_no_network_requests_when_possible_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/does_no_network_requests_when_possible_test.dart
deleted file mode 100644
index 7ff76c0..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/does_no_network_requests_when_possible_test.dart
+++ /dev/null
@@ -1,49 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
-
- integration('does not request versions if the lockfile is up to date', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "1.1.0");
- builder.serve("foo", "1.2.0");
- });
-
- d.appDir({
- "foo": "any"
- }).create();
-
- // Get once so it gets cached.
- pubGet();
-
- // Clear the cache. We don't care about anything that was served during
- // the initial get.
- getRequestedPaths();
-
- // Run the solver again now that it's cached.
- pubGet();
-
- d.cacheDir({
- "foo": "1.2.0"
- }).validate();
- d.packagesDir({
- "foo": "1.2.0"
- }).validate();
-
- // The get should not have done any network requests since the lock file is
- // up to date.
- getRequestedPaths().then((paths) {
- expect(paths, isEmpty);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/get_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/get_test.dart
deleted file mode 100644
index 97b5630..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/get_test.dart
+++ /dev/null
@@ -1,42 +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 pub_tests;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('gets a package from a pub server', () {
- servePackages((builder) => builder.serve("foo", "1.2.3"));
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet();
-
- d.cacheDir({
- "foo": "1.2.3"
- }).validate();
- d.packagesDir({
- "foo": "1.2.3"
- }).validate();
- });
-
- integration('URL encodes the package name', () {
- serveNoPackages();
-
- d.appDir({
- "bad name!": "1.2.3"
- }).create();
-
- pubGet(
- error: new RegExp(
- r"Could not find package bad name! at http://localhost:\d+\."),
- exitCode: exit_codes.UNAVAILABLE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/get_transitive_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/get_transitive_test.dart
deleted file mode 100644
index ad984b5..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/get_transitive_test.dart
+++ /dev/null
@@ -1,37 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('gets packages transitively from a pub server', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3", deps: {
- "bar": "2.0.4"
- });
- builder.serve("bar", "2.0.3");
- builder.serve("bar", "2.0.4");
- builder.serve("bar", "2.0.5");
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet();
-
- d.cacheDir({
- "foo": "1.2.3",
- "bar": "2.0.4"
- }).validate();
- d.packagesDir({
- "foo": "1.2.3",
- "bar": "2.0.4"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/gets_a_package_with_busted_dev_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/gets_a_package_with_busted_dev_dependencies_test.dart
deleted file mode 100644
index 1ca31ec..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/gets_a_package_with_busted_dev_dependencies_test.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library pub_tests;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
-
- // Regression test for issue 22194.
- integration(
- 'gets a dependency with broken dev dependencies from a pub ' 'server',
- () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3", pubspec: {
- "dev_dependencies": {
- "busted": {
- "not a real source": null
- }
- }
- });
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet();
-
- d.cacheDir({
- "foo": "1.2.3"
- }).validate();
- d.packagesDir({
- "foo": "1.2.3"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/resolve_constraints_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/resolve_constraints_test.dart
deleted file mode 100644
index 0fc93c5..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/resolve_constraints_test.dart
+++ /dev/null
@@ -1,44 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('resolves version constraints from a pub server', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3", deps: {
- "baz": ">=2.0.0"
- });
- builder.serve("bar", "2.3.4", deps: {
- "baz": "<3.0.0"
- });
- builder.serve("baz", "2.0.3");
- builder.serve("baz", "2.0.4");
- builder.serve("baz", "3.0.1");
- });
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- pubGet();
-
- d.cacheDir({
- "foo": "1.2.3",
- "bar": "2.3.4",
- "baz": "2.0.4"
- }).validate();
-
- d.packagesDir({
- "foo": "1.2.3",
- "bar": "2.3.4",
- "baz": "2.0.4"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_compatible_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_compatible_test.dart
deleted file mode 100644
index a5915b0..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_compatible_test.dart
+++ /dev/null
@@ -1,40 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "doesn't upgrade a locked pub server package with a new "
- "compatible constraint",
- () {
- servePackages((builder) => builder.serve("foo", "1.0.0"));
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0"
- }).validate();
-
- servePackages((builder) => builder.serve("foo", "1.0.1"));
-
- d.appDir({
- "foo": ">=1.0.0"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_new_is_satisfied_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_new_is_satisfied_test.dart
deleted file mode 100644
index e35d0c1..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_new_is_satisfied_test.dart
+++ /dev/null
@@ -1,64 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "doesn't unlock dependencies if a new dependency is already " "satisfied",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "bar": "<2.0.0"
- });
- builder.serve("bar", "1.0.0", deps: {
- "baz": "<2.0.0"
- });
- builder.serve("baz", "1.0.0");
- });
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0",
- "baz": "1.0.0"
- }).validate();
-
- servePackages((builder) {
- builder.serve("foo", "2.0.0", deps: {
- "bar": "<3.0.0"
- });
- builder.serve("bar", "2.0.0", deps: {
- "baz": "<3.0.0"
- });
- builder.serve("baz", "2.0.0");
- builder.serve("newdep", "2.0.0", deps: {
- "baz": ">=1.0.0"
- });
- });
-
- d.appDir({
- "foo": "any",
- "newdep": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0",
- "baz": "1.0.0",
- "newdep": "2.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_test.dart
deleted file mode 100644
index befc73a..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_test.dart
+++ /dev/null
@@ -1,45 +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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'keeps a pub server package locked to the version in the ' 'lockfile',
- () {
- servePackages((builder) => builder.serve("foo", "1.0.0"));
-
- d.appDir({
- "foo": "any"
- }).create();
-
- // This should lock the foo dependency to version 1.0.0.
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0"
- }).validate();
-
- // Delete the packages path to simulate a new checkout of the application.
- schedule(() => deleteEntry(path.join(sandboxDir, packagesPath)));
-
- // Start serving a newer package as well.
- servePackages((builder) => builder.serve("foo", "1.0.1"));
-
- // This shouldn't upgrade the foo dependency due to the lockfile.
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_incompatible_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_incompatible_test.dart
deleted file mode 100644
index d1c2f21..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_incompatible_test.dart
+++ /dev/null
@@ -1,37 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'upgrades a locked pub server package with a new incompatible ' 'constraint',
- () {
- servePackages((builder) => builder.serve("foo", "1.0.0"));
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0"
- }).validate();
- servePackages((builder) => builder.serve("foo", "1.0.1"));
- d.appDir({
- "foo": ">1.0.0"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.1"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_new_is_unsatisfied_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_new_is_unsatisfied_test.dart
deleted file mode 100644
index dc58adc..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_new_is_unsatisfied_test.dart
+++ /dev/null
@@ -1,73 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "unlocks dependencies if necessary to ensure that a new "
- "dependency is satisfied",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "bar": "<2.0.0"
- });
- builder.serve("bar", "1.0.0", deps: {
- "baz": "<2.0.0"
- });
- builder.serve("baz", "1.0.0", deps: {
- "qux": "<2.0.0"
- });
- builder.serve("qux", "1.0.0");
- });
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0",
- "baz": "1.0.0",
- "qux": "1.0.0"
- }).validate();
-
- servePackages((builder) {
- builder.serve("foo", "2.0.0", deps: {
- "bar": "<3.0.0"
- });
- builder.serve("bar", "2.0.0", deps: {
- "baz": "<3.0.0"
- });
- builder.serve("baz", "2.0.0", deps: {
- "qux": "<3.0.0"
- });
- builder.serve("qux", "2.0.0");
- builder.serve("newdep", "2.0.0", deps: {
- "baz": ">=1.5.0"
- });
- });
-
- d.appDir({
- "foo": "any",
- "newdep": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "2.0.0",
- "bar": "2.0.0",
- "baz": "2.0.0",
- "qux": "1.0.0",
- "newdep": "2.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_version_doesnt_exist_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_version_doesnt_exist_test.dart
deleted file mode 100644
index 76ba6a2..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_version_doesnt_exist_test.dart
+++ /dev/null
@@ -1,37 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'upgrades a locked pub server package with a nonexistent version',
- () {
- servePackages((builder) => builder.serve("foo", "1.0.0"));
-
- d.appDir({
- "foo": "any"
- }).create();
- pubGet();
- d.packagesDir({
- "foo": "1.0.0"
- }).validate();
-
- schedule(() => deleteEntry(p.join(sandboxDir, cachePath)));
-
- servePackages((builder) => builder.serve("foo", "1.0.1"), replace: true);
- pubGet();
- d.packagesDir({
- "foo": "1.0.1"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/absolute_path_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/absolute_path_test.dart
deleted file mode 100644
index 2f0a0f3..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/absolute_path_test.dart
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('path dependency with absolute path', () {
- d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1')]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": path.join(sandboxDir, "foo")
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])]).validate();
-
- // Move the packages directory and ensure the symlink still works. That
- // will validate that we actually created an absolute symlink.
- d.dir("moved").create();
- scheduleRename(packagesPath, "moved/packages");
-
- d.dir(
- "moved/packages",
- [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/absolute_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/absolute_symlink_test.dart
deleted file mode 100644
index 82a2336..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/absolute_symlink_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "generates a symlink with an absolute path if the dependency "
- "path was absolute",
- () {
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": path.join(sandboxDir, "foo")
- }
- })]).create();
-
- pubGet();
-
- d.dir("moved").create();
-
- // Move the app but not the package. Since the symlink is absolute, it
- // should still be able to find it.
- scheduleRename(appPath, path.join("moved", appPath));
-
- d.dir(
- "moved",
- [
- d.dir(
- packagesPath,
- [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/empty_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/empty_pubspec_test.dart
deleted file mode 100644
index 4c3c78f..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/empty_pubspec_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as p;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- // Regression test for issue 20103.
- integration('path dependency to an empty pubspec', () {
- d.dir('foo', [d.libDir('foo'), d.file('pubspec.yaml', '')]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubGet(
- exitCode: exit_codes.DATA,
- error: 'Error on line 1, column 1 of ${p.join('..', 'foo', 'pubspec.yaml')}: '
- 'Missing the required "name" field.');
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/no_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/no_pubspec_test.dart
deleted file mode 100644
index 5e0ae1e..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/no_pubspec_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('path dependency to non-package directory', () {
- // Make an empty directory.
- d.dir('foo').create();
- var fooPath = path.join(sandboxDir, "foo");
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": fooPath
- }
- })]).create();
-
- pubGet(
- error: new RegExp(
- r'Could not find a file named "pubspec.yaml" ' r'in "[^\n]*"\.'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/nonexistent_dir_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/nonexistent_dir_test.dart
deleted file mode 100644
index 8496cba..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/nonexistent_dir_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('path dependency to non-existent directory', () {
- var badPath = path.join(sandboxDir, "bad_path");
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": badPath
- }
- })]).create();
-
- pubGet(error: """
- Could not find package foo at "$badPath".
- Depended on by:
- - myapp 0.0.0""", exitCode: exit_codes.UNAVAILABLE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/path_is_file_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/path_is_file_test.dart
deleted file mode 100644
index d88df0f..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/path_is_file_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('path dependency when path is a file', () {
- d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1')]).create();
-
- d.file('dummy.txt', '').create();
- var dummyPath = path.join(sandboxDir, 'dummy.txt');
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": dummyPath
- }
- })]).create();
-
- pubGet(
- error: 'Path dependency for package foo must refer to a '
- 'directory, not a file. Was "$dummyPath".');
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/relative_path_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/relative_path_test.dart
deleted file mode 100644
index b5f2a14..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/relative_path_test.dart
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:unittest/unittest.dart';
-
-import '../../../lib/src/lock_file.dart';
-import '../../../lib/src/source_registry.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("can use relative path", () {
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])]).validate();
- });
-
- integration("path is relative to containing d.pubspec", () {
- d.dir(
- "relative",
- [d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: {
- "bar": {
- "path": "../bar"
- }
- })]),
- d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../relative/foo"
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]),
- d.dir("bar", [d.file("bar.dart", 'main() => "bar";')])]).validate();
- });
-
- integration("relative path preserved in the lockfile", () {
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubGet();
-
- schedule(() {
- var lockfilePath = path.join(sandboxDir, appPath, "pubspec.lock");
- var lockfile = new LockFile.load(lockfilePath, new SourceRegistry());
- var description = lockfile.packages["foo"].description;
-
- expect(path.isRelative(description["path"]), isTrue);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/relative_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/relative_symlink_test.dart
deleted file mode 100644
index f5ec3a3..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/relative_symlink_test.dart
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- // Pub uses NTFS junction points to create links in the packages directory.
- // These (unlike the symlinks that are supported in Vista and later) do not
- // support relative paths. So this test, by design, will not pass on Windows.
- // So just skip it.
- if (Platform.operatingSystem == "windows") return;
-
- initConfig();
- integration(
- "generates a symlink with a relative path if the dependency "
- "path was relative",
- () {
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubGet();
-
- d.dir("moved").create();
-
- // Move the app and package. Since they are still next to each other, it
- // should still be found.
- scheduleRename("foo", path.join("moved", "foo"));
- scheduleRename(appPath, path.join("moved", appPath));
-
- d.dir(
- "moved",
- [
- d.dir(
- packagesPath,
- [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_symlink_test.dart
deleted file mode 100644
index f5cb84b..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_symlink_test.dart
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("shared dependency with symlink", () {
- d.dir(
- "shared",
- [d.libDir("shared"), d.libPubspec("shared", "0.0.1")]).create();
-
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: {
- "shared": {
- "path": "../shared"
- }
- })]).create();
-
- d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1", deps: {
- "shared": {
- "path": "../link/shared"
- }
- })]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- },
- "bar": {
- "path": "../bar"
- }
- })]).create();
-
- d.dir("link").create();
- scheduleSymlink("shared", path.join("link", "shared"));
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]),
- d.dir("bar", [d.file("bar.dart", 'main() => "bar";')]),
- d.dir("shared", [d.file("shared.dart", 'main() => "shared";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_test.dart
deleted file mode 100644
index 9516765..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_test.dart
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("shared dependency with same path", () {
- d.dir(
- "shared",
- [d.libDir("shared"), d.libPubspec("shared", "0.0.1")]).create();
-
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: {
- "shared": {
- "path": "../shared"
- }
- })]).create();
-
- d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1", deps: {
- "shared": {
- "path": "../shared"
- }
- })]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- },
- "bar": {
- "path": "../bar"
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]),
- d.dir("bar", [d.file("bar.dart", 'main() => "bar";')]),
- d.dir("shared", [d.file("shared.dart", 'main() => "shared";')])]).validate();
- });
-
- integration("shared dependency with paths that normalize the same", () {
- d.dir(
- "shared",
- [d.libDir("shared"), d.libPubspec("shared", "0.0.1")]).create();
-
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: {
- "shared": {
- "path": "../shared"
- }
- })]).create();
-
- d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1", deps: {
- "shared": {
- "path": "../././shared"
- }
- })]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- },
- "bar": {
- "path": "../bar"
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]),
- d.dir("bar", [d.file("bar.dart", 'main() => "bar";')]),
- d.dir("shared", [d.file("shared.dart", 'main() => "shared";')])]).validate();
- });
-
- integration("shared dependency with absolute and relative path", () {
- d.dir(
- "shared",
- [d.libDir("shared"), d.libPubspec("shared", "0.0.1")]).create();
-
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: {
- "shared": {
- "path": "../shared"
- }
- })]).create();
-
- d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1", deps: {
- "shared": {
- "path": path.join(sandboxDir, "shared")
- }
- })]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- },
- "bar": {
- "path": "../bar"
- }
- })]).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]),
- d.dir("bar", [d.file("bar.dart", 'main() => "bar";')]),
- d.dir("shared", [d.file("shared.dart", 'main() => "shared";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/relative_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/relative_symlink_test.dart
deleted file mode 100644
index a413c3a..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/relative_symlink_test.dart
+++ /dev/null
@@ -1,52 +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 pub_tests;
-
-import 'dart:io';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- // Pub uses NTFS junction points to create links in the packages directory.
- // These (unlike the symlinks that are supported in Vista and later) do not
- // support relative paths. So this test, by design, will not pass on Windows.
- // So just skip it.
- if (Platform.operatingSystem == "windows") return;
-
- initConfig();
- integration('uses a relative symlink for the self link', () {
- d.dir(appPath, [d.appPubspec(), d.libDir('foo')]).create();
-
- pubGet();
-
- scheduleRename(appPath, "moved");
-
- d.dir(
- "moved",
- [
- d.dir(
- "packages",
- [d.dir("myapp", [d.file('foo.dart', 'main() => "foo";')])])]).validate();
- });
-
- integration('uses a relative symlink for secondary packages directory', () {
- d.dir(appPath, [d.appPubspec(), d.libDir('foo'), d.dir("bin")]).create();
-
- pubGet();
-
- scheduleRename(appPath, "moved");
-
- d.dir(
- "moved",
- [
- d.dir(
- "bin",
- [
- d.dir(
- "packages",
- [d.dir("myapp", [d.file('foo.dart', 'main() => "foo";')])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/get/switch_source_test.dart b/sdk/lib/_internal/pub_generated/test/get/switch_source_test.dart
deleted file mode 100644
index 4ddee5c..0000000
--- a/sdk/lib/_internal/pub_generated/test/get/switch_source_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-library pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('re-gets a package if its source has changed', () {
- servePackages((builder) => builder.serve("foo", "1.2.3"));
-
- d.dir(
- 'foo',
- [d.libDir('foo', 'foo 0.0.1'), d.libPubspec('foo', '0.0.1')]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo"
- }
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "0.0.1"
- }).validate();
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.2.3"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/activate_git_after_hosted_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/activate_git_after_hosted_test.dart
deleted file mode 100644
index 6be9b07..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/activate_git_after_hosted_test.dart
+++ /dev/null
@@ -1,48 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activating a Git package deactivates the hosted one', () {
- ensureGit();
-
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir("bin", [d.file("foo.dart", "main(args) => print('hosted');")])]);
- });
-
- d.git(
- 'foo.git',
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('git');")])]).create();
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- schedulePub(
- args: ["global", "activate", "-sgit", "../foo.git"],
- output: allOf(
- startsWith(
- 'Package foo is currently active at version 1.0.0.\n'
- 'Resolving dependencies...\n' '+ foo 1.0.0 from git ../foo.git at '),
- // Specific revision number goes here.
- endsWith(
- 'Precompiling executables...\n' 'Loading source assets...\n'
- 'Precompiled foo:foo.\n'
- 'Activated foo 1.0.0 from Git repository "../foo.git".')));
-
- // Should now run the git one.
- var pub = pubRun(global: true, args: ["foo"]);
- pub.stdout.expect("git");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_git_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_git_test.dart
deleted file mode 100644
index 29d56b4..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_git_test.dart
+++ /dev/null
@@ -1,46 +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:path/path.dart' as p;
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activating a hosted package deactivates the Git one', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "2.0.0",
- contents: [
- d.dir("bin", [d.file("foo.dart", "main(args) => print('hosted');")])]);
- });
-
- d.git(
- 'foo.git',
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('git');")])]).create();
-
- schedulePub(args: ["global", "activate", "-sgit", "../foo.git"]);
-
- var path = canonicalize(p.join(sandboxDir, "foo"));
- schedulePub(args: ["global", "activate", "foo"], output: """
- Package foo is currently active from Git repository "../foo.git".
- Resolving dependencies...
- + foo 2.0.0
- Downloading foo 2.0.0...
- Precompiling executables...
- Loading source assets...
- Precompiled foo:foo.
- Activated foo 2.0.0.""");
-
- // Should now run the hosted one.
- var pub = pubRun(global: true, args: ["foo"]);
- pub.stdout.expect("hosted");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_path_test.dart
deleted file mode 100644
index 05e2d79..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_path_test.dart
+++ /dev/null
@@ -1,46 +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:path/path.dart' as p;
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activating a hosted package deactivates the path one', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "2.0.0",
- contents: [
- d.dir("bin", [d.file("foo.dart", "main(args) => print('hosted');")])]);
- });
-
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('path');")])]).create();
-
- schedulePub(args: ["global", "activate", "-spath", "../foo"]);
-
- var path = canonicalize(p.join(sandboxDir, "foo"));
- schedulePub(args: ["global", "activate", "foo"], output: """
- Package foo is currently active at path "$path".
- Resolving dependencies...
- + foo 2.0.0
- Downloading foo 2.0.0...
- Precompiling executables...
- Loading source assets...
- Precompiled foo:foo.
- Activated foo 2.0.0.""");
-
- // Should now run the hosted one.
- var pub = pubRun(global: true, args: ["foo"]);
- pub.stdout.expect("hosted");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/activate_path_after_hosted_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/activate_path_after_hosted_test.dart
deleted file mode 100644
index 50d077e..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/activate_path_after_hosted_test.dart
+++ /dev/null
@@ -1,40 +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:path/path.dart' as p;
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activating a hosted package deactivates the path one', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir("bin", [d.file("foo.dart", "main(args) => print('hosted');")])]);
- });
-
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "2.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('path');")])]).create();
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- var path = canonicalize(p.join(sandboxDir, "foo"));
- schedulePub(args: ["global", "activate", "-spath", "../foo"], output: """
- Package foo is currently active at version 1.0.0.
- Activated foo 2.0.0 at path "$path".""");
-
- // Should now run the path one.
- var pub = pubRun(global: true, args: ["foo"]);
- pub.stdout.expect("path");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/bad_version_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/bad_version_test.dart
deleted file mode 100644
index d915658..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/bad_version_test.dart
+++ /dev/null
@@ -1,18 +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:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if the version constraint cannot be parsed', () {
- schedulePub(
- args: ["global", "activate", "foo", "1.0"],
- error: contains('Could not parse version "1.0". Unknown text at "1.0".'),
- exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/cached_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/cached_package_test.dart
deleted file mode 100644
index e3a1f83..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/cached_package_test.dart
+++ /dev/null
@@ -1,35 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('can activate an already cached package', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- });
-
- schedulePub(args: ["cache", "add", "foo"]);
-
- schedulePub(args: ["global", "activate", "foo"], output: """
- Resolving dependencies...
- + foo 1.0.0
- Precompiling executables...
- Loading source assets...
- Activated foo 1.0.0.""");
-
- // Should be in global package cache.
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.0.0'))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/constraint_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/constraint_test.dart
deleted file mode 100644
index c4a0783..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/constraint_test.dart
+++ /dev/null
@@ -1,30 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('chooses the highest version that matches the constraint', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "1.0.1");
- builder.serve("foo", "1.1.0");
- builder.serve("foo", "1.2.3");
- });
-
- schedulePub(args: ["global", "activate", "foo", "<1.1.0"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.0.1'))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/constraint_with_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/constraint_with_path_test.dart
deleted file mode 100644
index 91de56f..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/constraint_with_path_test.dart
+++ /dev/null
@@ -1,18 +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:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if a version is passed with the path source', () {
- schedulePub(
- args: ["global", "activate", "-spath", "foo", "1.2.3"],
- error: contains('Unexpected argument "1.2.3".'),
- exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/different_version_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/different_version_test.dart
deleted file mode 100644
index 3c4b9fc..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/different_version_test.dart
+++ /dev/null
@@ -1,30 +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 '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "discards the previous active version if it doesn't match the " "constraint",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "2.0.0");
- });
-
- // Activate 1.0.0.
- schedulePub(args: ["global", "activate", "foo", "1.0.0"]);
-
- // Activating it again with a different constraint changes the version.
- schedulePub(args: ["global", "activate", "foo", ">1.0.0"], output: """
- Package foo is currently active at version 1.0.0.
- Resolving dependencies...
- + foo 2.0.0
- Downloading foo 2.0.0...
- Precompiling executables...
- Loading source assets...
- Activated foo 2.0.0.""");
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/doesnt_snapshot_path_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/doesnt_snapshot_path_executables_test.dart
deleted file mode 100644
index 4ee9c7b..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/doesnt_snapshot_path_executables_test.dart
+++ /dev/null
@@ -1,37 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("doesn't snapshots the executables for a path package", () {
- d.dir(
- 'foo',
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir(
- "bin",
- [d.file("hello.dart", "void main() => print('hello!');")])]).create();
-
- schedulePub(
- args: ["global", "activate", "-spath", "../foo"],
- output: isNot(contains('Precompiled foo:hello.')));
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir(
- 'foo',
- [
- d.matcherFile('pubspec.lock', contains('1.0.0')),
- d.nothing('bin')])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/empty_constraint_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/empty_constraint_test.dart
deleted file mode 100644
index 38302fb..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/empty_constraint_test.dart
+++ /dev/null
@@ -1,21 +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 '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('errors if the constraint matches no versions', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "1.0.1");
- });
-
- schedulePub(args: ["global", "activate", "foo", ">1.1.0"], error: """
- Package foo has no versions that match >1.1.0 derived from:
- - pub global activate depends on version >1.1.0""",
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/git_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/git_package_test.dart
deleted file mode 100644
index 2239576..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/git_package_test.dart
+++ /dev/null
@@ -1,31 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activates a package from a Git repo', () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(
- args: ["global", "activate", "-sgit", "../foo.git"],
- output: allOf(
- startsWith('Resolving dependencies...\n' '+ foo 1.0.0 from git ../foo.git at '),
- // Specific revision number goes here.
- endsWith(
- 'Precompiling executables...\n' 'Loading source assets...\n'
- 'Precompiled foo:foo.\n'
- 'Activated foo 1.0.0 from Git repository "../foo.git".')));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/ignores_active_version_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/ignores_active_version_test.dart
deleted file mode 100644
index 50f8ec9..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/ignores_active_version_test.dart
+++ /dev/null
@@ -1,28 +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 '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('ignores previously activated version', () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3");
- builder.serve("foo", "1.3.0");
- });
-
- // Activate 1.2.3.
- schedulePub(args: ["global", "activate", "foo", "1.2.3"]);
-
- // Activating it again resolves to the new best version.
- schedulePub(args: ["global", "activate", "foo", ">1.0.0"], output: """
- Package foo is currently active at version 1.2.3.
- Resolving dependencies...
- + foo 1.3.0
- Downloading foo 1.3.0...
- Precompiling executables...
- Loading source assets...
- Activated foo 1.3.0.""");
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_git_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_git_test.dart
deleted file mode 100644
index 6bebaf4..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_git_test.dart
+++ /dev/null
@@ -1,30 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activating a Git package installs its dependencies', () {
- servePackages((builder) {
- builder.serve("bar", "1.0.0", deps: {
- "baz": "any"
- });
- builder.serve("baz", "1.0.0");
- });
-
- d.git('foo.git', [d.libPubspec("foo", "1.0.0", deps: {
- "bar": "any"
- }),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(
- args: ["global", "activate", "-sgit", "../foo.git"],
- output: allOf(
- [contains("Downloading bar 1.0.0..."), contains("Downloading baz 1.0.0...")]));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_path_test.dart
deleted file mode 100644
index 151ae86..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_path_test.dart
+++ /dev/null
@@ -1,47 +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:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activating a path package installs dependencies', () {
- servePackages((builder) {
- builder.serve("bar", "1.0.0", deps: {
- "baz": "any"
- });
- builder.serve("baz", "2.0.0");
- });
-
- d.dir("foo", [d.libPubspec("foo", "0.0.0", deps: {
- "bar": "any"
- }),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- var pub = startPub(args: ["global", "activate", "-spath", "../foo"]);
- pub.stdout.expect(consumeThrough("Resolving dependencies..."));
- pub.stdout.expect(consumeThrough("Downloading bar 1.0.0..."));
- pub.stdout.expect(consumeThrough("Downloading baz 2.0.0..."));
- pub.stdout.expect(
- consumeThrough(startsWith("Activated foo 0.0.0 at path")));
- pub.shouldExit();
-
- // Puts the lockfile in the linked package itself.
- d.dir(
- "foo",
- [
- d.matcherFile(
- "pubspec.lock",
- allOf(
- [
- contains("bar"),
- contains("1.0.0"),
- contains("baz"),
- contains("2.0.0")]))]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_test.dart
deleted file mode 100644
index f3bc479..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_test.dart
+++ /dev/null
@@ -1,27 +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:scheduled_test/scheduled_test.dart';
-
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activating a package installs its dependencies', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "bar": "any"
- });
- builder.serve("bar", "1.0.0", deps: {
- "baz": "any"
- });
- builder.serve("baz", "1.0.0");
- });
-
- schedulePub(
- args: ["global", "activate", "foo"],
- output: allOf(
- [contains("Downloading bar 1.0.0..."), contains("Downloading baz 1.0.0...")]));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/missing_git_repo_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/missing_git_repo_test.dart
deleted file mode 100644
index 4da5970..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/missing_git_repo_test.dart
+++ /dev/null
@@ -1,19 +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:scheduled_test/scheduled_test.dart';
-
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if the Git repo does not exist', () {
- ensureGit();
-
- schedulePub(
- args: ["global", "activate", "-sgit", "../nope.git"],
- error: contains("repository '../nope.git' does not exist"),
- exitCode: 1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/missing_package_arg_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/missing_package_arg_test.dart
deleted file mode 100644
index 965a6df..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/missing_package_arg_test.dart
+++ /dev/null
@@ -1,18 +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:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if no package was given', () {
- schedulePub(
- args: ["global", "activate"],
- error: contains("No package to activate given."),
- exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/outdated_binstub_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/outdated_binstub_test.dart
deleted file mode 100644
index 65fd10b..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/outdated_binstub_test.dart
+++ /dev/null
@@ -1,55 +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 'dart:io';
-import 'dart:async';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-const _OUTDATED_BINSTUB = """
-#!/usr/bin/env sh
-# This file was created by pub v0.1.2-3.
-# Package: foo
-# Version: 1.0.0
-# Executable: foo-script
-# Script: script
-dart "/path/to/.pub-cache/global_packages/foo/bin/script.dart.snapshot" "\$@"
-""";
-
-main() {
- initConfig();
- integration("an outdated binstub is replaced", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "foo-script": "script"
- }
- },
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir('bin', [d.file(binStubName('foo-script'), _OUTDATED_BINSTUB)])]).create();
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [d.dir('bin', [// 255 is the VM's exit code upon seeing an out-of-date snapshot.
- d.matcherFile(
- binStubName('foo-script'),
- contains("255"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/path_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/path_package_test.dart
deleted file mode 100644
index 8d273c9..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/path_package_test.dart
+++ /dev/null
@@ -1,25 +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:path/path.dart' as p;
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activates a package at a local path', () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- var path = canonicalize(p.join(sandboxDir, "foo"));
- schedulePub(
- args: ["global", "activate", "--source", "path", "../foo"],
- output: 'Activated foo 1.0.0 at path "$path".');
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/reactivating_git_upgrades_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/reactivating_git_upgrades_test.dart
deleted file mode 100644
index 18b6829..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/reactivating_git_upgrades_test.dart
+++ /dev/null
@@ -1,40 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('ignores previously activated git commit', () {
- ensureGit();
-
- d.git('foo.git', [d.libPubspec("foo", "1.0.0")]).create();
-
- schedulePub(
- args: ["global", "activate", "-sgit", "../foo.git"],
- output: allOf(
- startsWith('Resolving dependencies...\n' '+ foo 1.0.0 from git ../foo.git at '),
- // Specific revision number goes here.
- endsWith(
- 'Precompiling executables...\n' 'Loading source assets...\n'
- 'Activated foo 1.0.0 from Git repository "../foo.git".')));
-
- d.git('foo.git', [d.libPubspec("foo", "1.0.1")]).commit();
-
- // Activating it again pulls down the latest commit.
- schedulePub(
- args: ["global", "activate", "-sgit", "../foo.git"],
- output: allOf(
- startsWith(
- 'Package foo is currently active from Git repository ' '"../foo.git".\n'
- 'Resolving dependencies...\n' '+ foo 1.0.1 from git ../foo.git at '),
- // Specific revision number goes here.
- endsWith(
- 'Precompiling executables...\n' 'Loading source assets...\n'
- 'Activated foo 1.0.1 from Git repository "../foo.git".')));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/removes_old_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/removes_old_lockfile_test.dart
deleted file mode 100644
index a9ff5c9..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/removes_old_lockfile_test.dart
+++ /dev/null
@@ -1,39 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('removes the 1.6-style lockfile', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- });
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.file(
- 'foo.lock',
- 'packages: {foo: {description: foo, source: hosted, '
- 'version: "1.0.0"}}}')])]).create();
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.nothing('foo.lock'),
- d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.0.0'))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_git_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_git_executables_test.dart
deleted file mode 100644
index c6b2633..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_git_executables_test.dart
+++ /dev/null
@@ -1,52 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('snapshots the executables for a Git repo', () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir(
- "bin",
- [
- d.file("hello.dart", "void main() => print('hello!');"),
- d.file("goodbye.dart", "void main() => print('goodbye!');"),
- d.file("shell.sh", "echo shell"),
- d.dir(
- "subdir",
- [d.file("sub.dart", "void main() => print('sub!');")])])]).create();
-
- schedulePub(
- args: ["global", "activate", "-sgit", "../foo.git"],
- output: allOf(
- [contains('Precompiled foo:hello.'), contains("Precompiled foo:goodbye.")]));
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir(
- 'foo',
- [
- d.matcherFile('pubspec.lock', contains('1.0.0')),
- d.dir(
- 'bin',
- [
- d.matcherFile('hello.dart.snapshot', contains('hello!')),
- d.matcherFile('goodbye.dart.snapshot', contains('goodbye!')),
- d.nothing('shell.sh.snapshot'),
- d.nothing('subdir')])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_hosted_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_hosted_executables_test.dart
deleted file mode 100644
index 254036e..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_hosted_executables_test.dart
+++ /dev/null
@@ -1,50 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('snapshots the executables for a hosted package', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir(
- 'bin',
- [
- d.file("hello.dart", "void main() => print('hello!');"),
- d.file("goodbye.dart", "void main() => print('goodbye!');"),
- d.file("shell.sh", "echo shell"),
- d.dir("subdir", [d.file("sub.dart", "void main() => print('sub!');")])])]);
- });
-
- schedulePub(
- args: ["global", "activate", "foo"],
- output: allOf(
- [contains('Precompiled foo:hello.'), contains("Precompiled foo:goodbye.")]));
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir(
- 'foo',
- [
- d.matcherFile('pubspec.lock', contains('1.0.0')),
- d.dir(
- 'bin',
- [
- d.matcherFile('hello.dart.snapshot', contains('hello!')),
- d.matcherFile('goodbye.dart.snapshot', contains('goodbye!')),
- d.nothing('shell.sh.snapshot'),
- d.nothing('subdir')])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/supports_version_solver_backtracking_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/supports_version_solver_backtracking_test.dart
deleted file mode 100644
index 1d75605..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/supports_version_solver_backtracking_test.dart
+++ /dev/null
@@ -1,38 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('performs verison solver backtracking if necessary', () {
- servePackages((builder) {
- builder.serve("foo", "1.1.0", pubspec: {
- "environment": {
- "sdk": ">=0.1.2 <0.2.0"
- }
- });
- builder.serve("foo", "1.2.0", pubspec: {
- "environment": {
- "sdk": ">=0.1.3 <0.2.0"
- }
- });
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- // foo 1.2.0 won't be picked because its SDK constraint conflicts with the
- // dummy SDK version 0.1.2+3.
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.1.0'))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/uncached_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/uncached_package_test.dart
deleted file mode 100644
index aa5d456..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/uncached_package_test.dart
+++ /dev/null
@@ -1,36 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('installs and activates the best version of a package', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "1.2.3");
- builder.serve("foo", "2.0.0-wildly.unstable");
- });
-
- schedulePub(args: ["global", "activate", "foo"], output: """
- Resolving dependencies...
- + foo 1.2.3 (2.0.0-wildly.unstable available)
- Downloading foo 1.2.3...
- Precompiling executables...
- Loading source assets...
- Activated foo 1.2.3.""");
-
- // Should be in global package cache.
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.2.3'))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/unexpected_arguments_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/unexpected_arguments_test.dart
deleted file mode 100644
index a62f356..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/unexpected_arguments_test.dart
+++ /dev/null
@@ -1,18 +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:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if there are extra arguments', () {
- schedulePub(
- args: ["global", "activate", "foo", "1.0.0", "bar", "baz"],
- error: contains('Unexpected arguments "bar" and "baz".'),
- exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/unknown_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/unknown_package_test.dart
deleted file mode 100644
index d0bc786..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/activate/unknown_package_test.dart
+++ /dev/null
@@ -1,20 +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:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('errors if the package could not be found', () {
- serveNoPackages();
-
- schedulePub(
- args: ["global", "activate", "foo"],
- error: startsWith("Could not find package foo at"),
- exitCode: exit_codes.UNAVAILABLE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_executable_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_executable_test.dart
deleted file mode 100644
index 314c2e5..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_executable_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 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("the generated binstub runs a snapshotted executable", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "foo-script": "script"
- }
- },
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- var process = new ScheduledProcess.start(
- p.join(sandboxDir, cachePath, "bin", binStubName("foo-script")),
- ["arg1", "arg2"],
- environment: getEnvironment());
-
- process.stdout.expect("ok [arg1, arg2]");
- process.shouldExit();
- });
-
- integration("the generated binstub runs a non-snapshotted executable", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "foo-script": "script"
- }
- }),
- d.dir(
- "bin",
- [d.file("script.dart", "main(args) => print('ok \$args');")])]).create();
-
- schedulePub(args: ["global", "activate", "-spath", "../foo"]);
-
- var process = new ScheduledProcess.start(
- p.join(sandboxDir, cachePath, "bin", binStubName("foo-script")),
- ["arg1", "arg2"],
- environment: getEnvironment());
-
- process.stdout.expect("ok [arg1, arg2]");
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_global_run_if_no_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_global_run_if_no_snapshot_test.dart
deleted file mode 100644
index 8b2bf6f..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_global_run_if_no_snapshot_test.dart
+++ /dev/null
@@ -1,36 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("the binstubs runs pub global run if there is no snapshot", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "foo-script": "script"
- }
- }),
- d.dir("bin", [d.file("script.dart", "main() => print('ok');")])]).create();
-
- // Path packages are mutable, so no snapshot is created.
- schedulePub(
- args: ["global", "activate", "--source", "path", "../foo"],
- output: contains("Installed executable foo-script."));
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [
- d.matcherFile(
- binStubName("foo-script"),
- contains("pub global run foo:script"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_precompiled_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_precompiled_snapshot_test.dart
deleted file mode 100644
index 1a2115c..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_precompiled_snapshot_test.dart
+++ /dev/null
@@ -1,35 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("the binstubs runs a precompiled snapshot if present", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "foo-script": "script"
- }
- },
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [
- d.matcherFile(
- binStubName("foo-script"),
- contains("script.dart.snapshot"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/creates_executables_in_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/creates_executables_in_pubspec_test.dart
deleted file mode 100644
index 04aaa96..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/creates_executables_in_pubspec_test.dart
+++ /dev/null
@@ -1,44 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("creates binstubs for each executable in the pubspec", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "one": null,
- "two-renamed": "second"
- }
- },
- contents: [
- d.dir(
- "bin",
- [
- d.file("one.dart", "main(args) => print('one');"),
- d.file("second.dart", "main(args) => print('two');"),
- d.file("nope.dart", "main(args) => print('nope');")])]);
- });
-
- schedulePub(
- args: ["global", "activate", "foo"],
- output: contains("Installed executables one and two-renamed."));
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [
- d.matcherFile(binStubName("one"), contains("one")),
- d.matcherFile(binStubName("two-renamed"), contains("second")),
- d.nothing(binStubName("two")),
- d.nothing(binStubName("nope"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_no_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_no_executables_test.dart
deleted file mode 100644
index ac6348a..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_no_executables_test.dart
+++ /dev/null
@@ -1,28 +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 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("does not warn if the package has no executables", () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]);
- });
-
- schedulePub(
- args: ["global", "activate", "foo"],
- output: isNot(contains("is not on your path")));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_on_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_on_path_test.dart
deleted file mode 100644
index 648519c..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_on_path_test.dart
+++ /dev/null
@@ -1,38 +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 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("does not warn if the binstub directory is on the path", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "script": null
- }
- },
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]);
- });
-
- // Add the test's cache bin directory to the path.
- var binDir = p.dirname(Platform.executable);
- var separator = Platform.operatingSystem == "windows" ? ";" : ":";
- var path = "${Platform.environment["PATH"]}$separator$binDir";
-
- schedulePub(
- args: ["global", "activate", "foo"],
- output: isNot(contains("is not on your path")),
- environment: {
- "PATH": path
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_and_no_executables_options_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_and_no_executables_options_test.dart
deleted file mode 100644
index d93ed56..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_and_no_executables_options_test.dart
+++ /dev/null
@@ -1,29 +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:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("errors if -x and --no-executables are both passed", () {
- d.dir("foo", [d.libPubspec("foo", "1.0.0")]).create();
-
- schedulePub(
- args: [
- "global",
- "activate",
- "--source",
- "path",
- "../foo",
- "-x",
- "anything",
- "--no-executables"],
- error: contains("Cannot pass both --no-executables and --executable."),
- exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_executables_test.dart
deleted file mode 100644
index ffac259..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_executables_test.dart
+++ /dev/null
@@ -1,48 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("only creates binstubs for the listed executables", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "one": "script",
- "two": "script",
- "three": "script"
- }
- }),
- d.dir("bin", [d.file("script.dart", "main() => print('ok');")])]).create();
-
- schedulePub(
- args: [
- "global",
- "activate",
- "--source",
- "path",
- "../foo",
- "-x",
- "one",
- "--executable",
- "three"],
- output: contains("Installed executables one and three."));
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [
- d.matcherFile(binStubName("one"), contains("pub global run foo:script")),
- d.nothing(binStubName("two")),
- d.matcherFile(
- binStubName("three"),
- contains("pub global run foo:script"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/missing_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/missing_script_test.dart
deleted file mode 100644
index c8b617a..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/missing_script_test.dart
+++ /dev/null
@@ -1,31 +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:path/path.dart' as p;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("errors if an executable's script can't be found", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "missing": "not_here",
- "nope": null
- }
- })]).create();
-
- var pub = startPub(args: ["global", "activate", "-spath", "../foo"]);
-
- pub.stderr.expect(
- 'Warning: Executable "missing" runs '
- '"${p.join('bin', 'not_here.dart')}", which was not found in foo.');
- pub.stderr.expect(
- 'Warning: Executable "nope" runs '
- '"${p.join('bin', 'nope.dart')}", which was not found in foo.');
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_test.dart
deleted file mode 100644
index 4667065..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_test.dart
+++ /dev/null
@@ -1,55 +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:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("does not overwrite an existing binstub", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "foo": "foo",
- "collide1": "foo",
- "collide2": "foo"
- }
- }),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "executables": {
- "bar": "bar",
- "collide1": "bar",
- "collide2": "bar"
- }
- }),
- d.dir("bin", [d.file("bar.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "-spath", "../foo"]);
-
- var pub = startPub(args: ["global", "activate", "-spath", "../bar"]);
- pub.stdout.expect(consumeThrough("Installed executable bar."));
- pub.stderr.expect("Executable collide1 was already installed from foo.");
- pub.stderr.expect("Executable collide2 was already installed from foo.");
- pub.stderr.expect(
- "Deactivate the other package(s) or activate bar using " "--overwrite.");
- pub.shouldExit();
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [
- d.matcherFile(binStubName("foo"), contains("foo:foo")),
- d.matcherFile(binStubName("bar"), contains("bar:bar")),
- d.matcherFile(binStubName("collide1"), contains("foo:foo")),
- d.matcherFile(binStubName("collide2"), contains("foo:foo"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_with_overwrite_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_with_overwrite_test.dart
deleted file mode 100644
index a868a24..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_with_overwrite_test.dart
+++ /dev/null
@@ -1,55 +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:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("overwrites an existing binstub if --overwrite is passed", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "foo": "foo",
- "collide1": "foo",
- "collide2": "foo"
- }
- }),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "executables": {
- "bar": "bar",
- "collide1": "bar",
- "collide2": "bar"
- }
- }),
- d.dir("bin", [d.file("bar.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "-spath", "../foo"]);
-
- var pub =
- startPub(args: ["global", "activate", "-spath", "../bar", "--overwrite"]);
- pub.stdout.expect(
- consumeThrough("Installed executables bar, collide1 and collide2."));
- pub.stderr.expect("Replaced collide1 previously installed from foo.");
- pub.stderr.expect("Replaced collide2 previously installed from foo.");
- pub.shouldExit();
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [
- d.matcherFile(binStubName("foo"), contains("foo:foo")),
- d.matcherFile(binStubName("bar"), contains("bar:bar")),
- d.matcherFile(binStubName("collide1"), contains("bar:bar")),
- d.matcherFile(binStubName("collide2"), contains("bar:bar"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/no_executables_flag_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/no_executables_flag_test.dart
deleted file mode 100644
index 050868e..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/no_executables_flag_test.dart
+++ /dev/null
@@ -1,31 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("does not create binstubs if --no-executables is passed", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "one": null
- }
- }),
- d.dir("bin", [d.file("one.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "--source", "path", "../foo"]);
-
- schedulePub(
- args: ["global", "activate", "--source", "path", "../foo", "--no-executables"]);
-
- // Should still delete old one.
- d.dir(
- cachePath,
- [d.dir("bin", [d.nothing(binStubName("one"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_binstub_runs_pub_global_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_binstub_runs_pub_global_test.dart
deleted file mode 100644
index 48da7f9..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_binstub_runs_pub_global_test.dart
+++ /dev/null
@@ -1,49 +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 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("an outdated binstub runs 'pub global run'", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "foo-script": "script"
- }
- },
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir(
- 'foo',
- [d.dir('bin', [d.outOfDateSnapshot('script.dart.snapshot')])])])]).create();
-
- var process = new ScheduledProcess.start(
- p.join(sandboxDir, cachePath, "bin", binStubName("foo-script")),
- ["arg1", "arg2"],
- environment: getEnvironment());
-
- process.stdout.expect(consumeThrough("ok"));
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_snapshot_test.dart
deleted file mode 100644
index 28da4f5..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_snapshot_test.dart
+++ /dev/null
@@ -1,62 +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 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("a binstub runs 'pub global run' for an outdated snapshot", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "foo-script": "script"
- }
- },
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir(
- 'foo',
- [d.dir('bin', [d.outOfDateSnapshot('script.dart.snapshot')])])])]).create();
-
- var process = new ScheduledProcess.start(
- p.join(sandboxDir, cachePath, "bin", binStubName("foo-script")),
- ["arg1", "arg2"],
- environment: getEnvironment());
-
- process.stderr.expect(startsWith("Wrong script snapshot version"));
- process.stdout.expect(consumeThrough("ok [arg1, arg2]"));
- process.shouldExit();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages/foo/bin',
- [
- d.binaryMatcherFile(
- 'script.dart.snapshot',
- isNot(
- equals(readBinaryFile(testAssetPath('out-of-date.snapshot')))))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/path_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/path_package_test.dart
deleted file mode 100644
index 49af05c..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/path_package_test.dart
+++ /dev/null
@@ -1,35 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("creates binstubs when activating a path package", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "foo": null
- }
- }),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(
- args: ["global", "activate", "--source", "path", "../foo"],
- output: contains("Installed executable foo."));
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [
- d.matcherFile(
- binStubName("foo"),
- contains("pub global run foo:foo"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/reactivate_removes_old_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/reactivate_removes_old_executables_test.dart
deleted file mode 100644
index e6cf443..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/reactivate_removes_old_executables_test.dart
+++ /dev/null
@@ -1,47 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("removes previous binstubs when reactivating a package", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "one": null,
- "two": null
- }
- }),
- d.dir(
- "bin",
- [
- d.file("one.dart", "main() => print('ok');"),
- d.file("two.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "--source", "path", "../foo"]);
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- // Remove "one".
- "two": null
- }
- }),]).create();
-
- schedulePub(args: ["global", "activate", "--source", "path", "../foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [
- d.nothing(binStubName("one")),
- d.matcherFile(binStubName("two"), contains("two"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_even_if_not_in_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_even_if_not_in_pubspec_test.dart
deleted file mode 100644
index 6c471b8..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_even_if_not_in_pubspec_test.dart
+++ /dev/null
@@ -1,38 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("removes all binstubs for package", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "foo": null
- }
- }),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- // Create the binstub for foo.
- schedulePub(args: ["global", "activate", "--source", "path", "../foo"]);
-
- // Remove it from the pubspec.
- d.dir("foo", [d.pubspec({
- "name": "foo"
- })]).create();
-
- // Deactivate.
- schedulePub(args: ["global", "deactivate", "foo"]);
-
- // It should still be deleted.
- d.dir(
- cachePath,
- [d.dir("bin", [d.nothing(binStubName("foo"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_when_deactivated_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_when_deactivated_test.dart
deleted file mode 100644
index 10bee75..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_when_deactivated_test.dart
+++ /dev/null
@@ -1,39 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("removes binstubs when the package is deactivated", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "one": null,
- "two": null
- }
- },
- contents: [
- d.dir(
- "bin",
- [
- d.file("one.dart", "main(args) => print('one');"),
- d.file("two.dart", "main(args) => print('two');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
- schedulePub(args: ["global", "deactivate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- "bin",
- [d.nothing(binStubName("one")), d.nothing(binStubName("two"))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/unknown_explicit_executable_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/unknown_explicit_executable_test.dart
deleted file mode 100644
index e272cb6..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/unknown_explicit_executable_test.dart
+++ /dev/null
@@ -1,40 +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:scheduled_test/scheduled_stream.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("errors on an unknown explicit executable", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "executables": {
- "one": "one"
- }
- }),
- d.dir("bin", [d.file("one.dart", "main() => print('ok');")])]).create();
-
- var pub = startPub(
- args: [
- "global",
- "activate",
- "--source",
- "path",
- "../foo",
- "-x",
- "who",
- "-x",
- "one",
- "--executable",
- "wat"]);
-
- pub.stdout.expect(consumeThrough("Installed executable one."));
- pub.stderr.expect("Unknown executables wat and who.");
- pub.shouldExit(exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/utils.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/utils.dart
deleted file mode 100644
index bd2243f..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/utils.dart
+++ /dev/null
@@ -1,43 +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 'dart:async';
-import 'dart:io';
-
-import 'package:path/path.dart' as p;
-
-import '../../test_pub.dart';
-
-/// The buildbots do not have the Dart SDK (containing "dart" and "pub") on
-/// their PATH, so we need to spawn the binstub process with a PATH that
-/// explicitly includes it.
-Future<Map> getEnvironment() {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var binDir = p.dirname(Platform.executable);
- join0(x0) {
- var separator = x0;
- var path = "${Platform.environment["PATH"]}${separator}${binDir}";
- new Future.value(getPubTestEnvironment()).then((x1) {
- try {
- var environment = x1;
- environment["PATH"] = path;
- completer0.complete(environment);
- } catch (e0, s0) {
- completer0.completeError(e0, s0);
- }
- }, onError: completer0.completeError);
- }
- if (Platform.operatingSystem == "windows") {
- join0(";");
- } else {
- join0(":");
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/warns_if_not_on_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/warns_if_not_on_path_test.dart
deleted file mode 100644
index 8e8c19f..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/binstubs/warns_if_not_on_path_test.dart
+++ /dev/null
@@ -1,27 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("warns if the binstub directory is not on the path", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", pubspec: {
- "executables": {
- "some-dart-script": "script"
- }
- },
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]);
- });
-
- schedulePub(
- args: ["global", "activate", "foo"],
- error: contains("is not on your path"));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/deactivate_and_reactivate_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/deactivate_and_reactivate_package_test.dart
deleted file mode 100644
index b9ea22a..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/deactivate/deactivate_and_reactivate_package_test.dart
+++ /dev/null
@@ -1,31 +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 '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('activates a different version after deactivating', () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "2.0.0");
- });
-
- // Activate an old version.
- schedulePub(args: ["global", "activate", "foo", "1.0.0"]);
-
- schedulePub(
- args: ["global", "deactivate", "foo"],
- output: "Deactivated package foo 1.0.0.");
-
- // Activating again should forget the old version.
- schedulePub(args: ["global", "activate", "foo"], output: """
- Resolving dependencies...
- + foo 2.0.0
- Downloading foo 2.0.0...
- Precompiling executables...
- Loading source assets...
- Activated foo 2.0.0.""");
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/git_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/git_package_test.dart
deleted file mode 100644
index 68725c7..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/deactivate/git_package_test.dart
+++ /dev/null
@@ -1,25 +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 '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('deactivates an active Git package', () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "-sgit", "../foo.git"]);
-
- schedulePub(
- args: ["global", "deactivate", "foo"],
- output: 'Deactivated package foo 1.0.0 from Git repository "../foo.git".');
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/hosted_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/hosted_package_test.dart
deleted file mode 100644
index ec8b985..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/deactivate/hosted_package_test.dart
+++ /dev/null
@@ -1,18 +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 '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('deactivates an active hosted package', () {
- servePackages((builder) => builder.serve("foo", "1.0.0"));
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- schedulePub(
- args: ["global", "deactivate", "foo"],
- output: "Deactivated package foo 1.0.0.");
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/missing_package_arg_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/missing_package_arg_test.dart
deleted file mode 100644
index e362ecb..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/deactivate/missing_package_arg_test.dart
+++ /dev/null
@@ -1,20 +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 '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if no package was given', () {
- schedulePub(args: ["global", "deactivate"], error: """
- No package to deactivate given.
-
- Usage: pub global deactivate <package>
- -h, --help Print this usage information.
-
- Run "pub help" to see global options.
- """, exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/path_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/path_package_test.dart
deleted file mode 100644
index 788c89d..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/deactivate/path_package_test.dart
+++ /dev/null
@@ -1,27 +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:path/path.dart' as p;
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('deactivates an active path package', () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "--source", "path", "../foo"]);
-
- var path = canonicalize(p.join(sandboxDir, "foo"));
- schedulePub(
- args: ["global", "deactivate", "foo"],
- output: 'Deactivated package foo 1.0.0 at path "$path".');
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/removes_precompiled_snapshots_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/removes_precompiled_snapshots_test.dart
deleted file mode 100644
index f4754b4..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/deactivate/removes_precompiled_snapshots_test.dart
+++ /dev/null
@@ -1,21 +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 '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('removes precompiled snapshots', () {
- servePackages((builder) => builder.serve("foo", "1.0.0"));
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- schedulePub(
- args: ["global", "deactivate", "foo"],
- output: "Deactivated package foo 1.0.0.");
-
- d.dir(cachePath, [d.dir('global_packages', [d.nothing('foo')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/unexpected_arguments_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/unexpected_arguments_test.dart
deleted file mode 100644
index 7e1e877..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/deactivate/unexpected_arguments_test.dart
+++ /dev/null
@@ -1,20 +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 '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if there are extra arguments', () {
- schedulePub(args: ["global", "deactivate", "foo", "bar", "baz"], error: """
- Unexpected arguments "bar" and "baz".
-
- Usage: pub global deactivate <package>
- -h, --help Print this usage information.
-
- Run "pub help" to see global options.
- """, exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/unknown_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/unknown_package_test.dart
deleted file mode 100644
index d20eaa0..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/deactivate/unknown_package_test.dart
+++ /dev/null
@@ -1,18 +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 '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('errors if the package is not activated', () {
- serveNoPackages();
-
- schedulePub(
- args: ["global", "deactivate", "foo"],
- error: "No active package foo.",
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/list_test.dart b/sdk/lib/_internal/pub_generated/test/global/list_test.dart
deleted file mode 100644
index f114896..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/list_test.dart
+++ /dev/null
@@ -1,74 +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:path/path.dart' as p;
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- integration('lists an activated hosted package', () {
- servePackages((builder) {
- builder.serve('foo', '1.0.0');
- });
-
- schedulePub(args: ['global', 'activate', 'foo']);
-
- schedulePub(args: ['global', 'list'], output: 'foo 1.0.0');
- });
-
- integration('lists an activated Git package', () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [
- d.libPubspec('foo', '1.0.0'),
- d.dir('bin', [d.file('foo.dart', 'main() => print("ok");')])]).create();
-
- schedulePub(args: ['global', 'activate', '-sgit', '../foo.git']);
-
- schedulePub(
- args: ['global', 'list'],
- output: 'foo 1.0.0 from Git repository "../foo.git"');
- });
-
- integration('lists an activated Path package', () {
- d.dir(
- 'foo',
- [
- d.libPubspec('foo', '1.0.0'),
- d.dir('bin', [d.file('foo.dart', 'main() => print("ok");')])]).create();
-
- schedulePub(args: ['global', 'activate', '-spath', '../foo']);
-
- var path = canonicalize(p.join(sandboxDir, 'foo'));
- schedulePub(args: ['global', 'list'], output: 'foo 1.0.0 at path "$path"');
- });
-
- integration('lists activated packages in alphabetical order', () {
- servePackages((builder) {
- builder.serve('aaa', '1.0.0');
- builder.serve('bbb', '1.0.0');
- builder.serve('ccc', '1.0.0');
- });
-
- schedulePub(args: ['global', 'activate', 'ccc']);
- schedulePub(args: ['global', 'activate', 'aaa']);
- schedulePub(args: ['global', 'activate', 'bbb']);
-
- schedulePub(args: ['global', 'list'], output: '''
-aaa 1.0.0
-bbb 1.0.0
-ccc 1.0.0
-''');
- });
-
- integration('lists nothing when no packages activated', () {
- schedulePub(args: ['global', 'list'], output: '\n');
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/errors_if_outside_bin_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/errors_if_outside_bin_test.dart
deleted file mode 100644
index aedeb48..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/errors_if_outside_bin_test.dart
+++ /dev/null
@@ -1,34 +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:path/path.dart' as p;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('errors if the script is in a subdirectory.', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir("example", [d.file("script.dart", "main(args) => print('ok');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
- schedulePub(args: ["global", "run", "foo:example/script"], error: """
-Cannot run an executable in a subdirectory of a global package.
-
-Usage: pub global run <package>:<executable> [args...]
--h, --help Print this usage information.
- --mode Mode to run transformers in.
- (defaults to "release")
-
-Run "pub help" to see global options.
-""", exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/implicit_executable_name_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/implicit_executable_name_test.dart
deleted file mode 100644
index 1e35eda..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/implicit_executable_name_test.dart
+++ /dev/null
@@ -1,25 +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 '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('defaults to the package name if the script is omitted', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [d.dir("bin", [d.file("foo.dart", "main(args) => print('foo');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- var pub = pubRun(global: true, args: ["foo"]);
- pub.stdout.expect("foo");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/missing_executable_arg_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/missing_executable_arg_test.dart
deleted file mode 100644
index c655cda..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/missing_executable_arg_test.dart
+++ /dev/null
@@ -1,22 +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 '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('fails if no executable was given', () {
- schedulePub(args: ["global", "run"], error: """
- Must specify an executable to run.
-
- Usage: pub global run <package>:<executable> [args...]
- -h, --help Print this usage information.
- --mode Mode to run transformers in.
- (defaults to "release")
-
- Run "pub help" to see global options.
- """, exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/missing_path_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/missing_path_package_test.dart
deleted file mode 100644
index 66f10f7..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/missing_path_package_test.dart
+++ /dev/null
@@ -1,30 +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:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('errors if the local package does not exist', () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "--source", "path", "../foo"]);
-
- schedule(() => deleteEntry(p.join(sandboxDir, "foo")));
-
- var pub = pubRun(global: true, args: ["foo"]);
- var path = canonicalize(p.join(sandboxDir, "foo"));
- pub.stderr.expect('Could not find a file named "pubspec.yaml" in "$path".');
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/mode_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/mode_test.dart
deleted file mode 100644
index fdf4b8a..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/mode_test.dart
+++ /dev/null
@@ -1,62 +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 '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class DartTransformer extends Transformer {
- final BarbackSettings _settings;
-
- DartTransformer.asPlugin(this._settings);
-
- String get allowedExtensions => '.in';
-
- void apply(Transform transform) {
- transform.addOutput(new Asset.fromString(
- new AssetId(transform.primaryInput.id.package, "bin/script.dart"),
- "void main() => print('\${_settings.mode.name}');"));
- }
-}
-""";
-
-main() {
- initConfig();
- integration(
- 'runs a script in an activated package with customizable modes',
- () {
- servePackages((builder) {
- builder.serveRepoPackage("barback");
-
- builder.serve("foo", "1.0.0", deps: {
- "barback": "any"
- }, pubspec: {
- "transformers": ["foo/src/transformer"]
- },
- contents: [
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [d.file("transformer.dart", TRANSFORMER), d.file("primary.in", "")])])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- // By default it should run in release mode.
- var pub = pubRun(global: true, args: ["foo:script"]);
- pub.stdout.expect("release");
- pub.shouldExit();
-
- // A custom mode should be specifiable.
- pub = pubRun(global: true, args: ["--mode", "custom-mode", "foo:script"]);
- pub.stdout.expect("custom-mode");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/nonexistent_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/nonexistent_script_test.dart
deleted file mode 100644
index d69c65a..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/nonexistent_script_test.dart
+++ /dev/null
@@ -1,21 +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:path/path.dart' as p;
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('errors if the script does not exist.', () {
- servePackages((builder) => builder.serve("foo", "1.0.0"));
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- var pub = pubRun(global: true, args: ["foo:script"]);
- pub.stderr.expect("Could not find ${p.join("bin", "script.dart")}.");
- pub.shouldExit(exit_codes.NO_INPUT);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/recompiles_if_sdk_is_out_of_date_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/recompiles_if_sdk_is_out_of_date_test.dart
deleted file mode 100644
index 1579ed5..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/recompiles_if_sdk_is_out_of_date_test.dart
+++ /dev/null
@@ -1,54 +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:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('recompiles a script if the SDK version is out-of-date', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir(
- 'foo',
- [d.dir('bin', [d.outOfDateSnapshot('script.dart.snapshot')])])])]).create();
-
- var pub = pubRun(global: true, args: ["foo:script"]);
- // In the real world this would just print "hello!", but since we collect
- // all output we see the precompilation messages as well.
- pub.stdout.expect("Precompiling executables...");
- pub.stdout.expect(consumeThrough("ok"));
- pub.shouldExit();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.dir(
- 'foo',
- [
- d.dir(
- 'bin',
- [d.matcherFile('script.dart.snapshot', contains('ok'))])])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/reflects_changes_to_local_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/reflects_changes_to_local_package_test.dart
deleted file mode 100644
index d4c19dd..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/reflects_changes_to_local_package_test.dart
+++ /dev/null
@@ -1,25 +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 '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('changes in a path package are immediately reflected', () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "--source", "path", "../foo"]);
-
- d.file("foo/bin/foo.dart", "main() => print('changed');").create();
-
- var pub = pubRun(global: true, args: ["foo"]);
- pub.stdout.expect("changed");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/runs_git_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/runs_git_script_test.dart
deleted file mode 100644
index ca9a6c3..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/runs_git_script_test.dart
+++ /dev/null
@@ -1,25 +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 '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('runs a script in a git package', () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "-sgit", "../foo.git"]);
-
- var pub = pubRun(global: true, args: ["foo"]);
- pub.stdout.expect("ok");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/runs_path_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/runs_path_script_test.dart
deleted file mode 100644
index 89985e6..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/runs_path_script_test.dart
+++ /dev/null
@@ -1,23 +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 '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('runs a script in a path package', () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create();
-
- schedulePub(args: ["global", "activate", "--source", "path", "../foo"]);
-
- var pub = pubRun(global: true, args: ["foo"]);
- pub.stdout.expect("ok");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/runs_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/runs_script_test.dart
deleted file mode 100644
index 3d9f35c..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/runs_script_test.dart
+++ /dev/null
@@ -1,25 +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 '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('runs a script in an activated package', () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.0.0",
- contents: [
- d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]);
- });
-
- schedulePub(args: ["global", "activate", "foo"]);
-
- var pub = pubRun(global: true, args: ["foo:script"]);
- pub.stdout.expect("ok");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/runs_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/runs_transformer_test.dart
deleted file mode 100644
index 035b0f0..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/runs_transformer_test.dart
+++ /dev/null
@@ -1,49 +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 '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class DartTransformer extends Transformer {
- DartTransformer.asPlugin();
-
- String get allowedExtensions => '.in';
-
- void apply(Transform transform) {
- transform.addOutput(new Asset.fromString(
- new AssetId("foo", "bin/script.dart"),
- "void main() => print('generated');"));
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration('runs a global script generated by a transformer', () {
- makeGlobalPackage("foo", "1.0.0", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": ["foo/src/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [d.file("transformer.dart", TRANSFORMER), d.file("primary.in", "")])])],
- pkg: ['barback']);
-
- var pub = pubRun(global: true, args: ["foo:script"]);
-
- pub.stdout.expect("generated");
- pub.shouldExit();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/unknown_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/unknown_package_test.dart
deleted file mode 100644
index dedce44..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/unknown_package_test.dart
+++ /dev/null
@@ -1,20 +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:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('errors if the package is not activated', () {
- serveNoPackages();
-
- schedulePub(
- args: ["global", "run", "foo:bar"],
- error: startsWith("No active package foo."),
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/global/run/uses_old_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/uses_old_lockfile_test.dart
deleted file mode 100644
index 1bdd634..0000000
--- a/sdk/lib/_internal/pub_generated/test/global/run/uses_old_lockfile_test.dart
+++ /dev/null
@@ -1,50 +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:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration('uses the 1.6-style lockfile if necessary', () {
- servePackages((builder) {
- builder.serve("bar", "1.0.0");
- builder.serve("foo", "1.0.0", deps: {
- "bar": "any"
- }, contents: [d.dir("bin", [d.file("script.dart", """
- import 'package:bar/bar.dart' as bar;
-
- main(args) => print(bar.main());""")])]);
- });
-
- schedulePub(args: ["cache", "add", "foo"]);
- schedulePub(args: ["cache", "add", "bar"]);
-
- d.dir(cachePath, [d.dir('global_packages', [d.file('foo.lock', '''
-packages:
- foo:
- description: foo
- source: hosted
- version: "1.0.0"
- bar:
- description: bar
- source: hosted
- version: "1.0.0"''')])]).create();
-
- var pub = pubRun(global: true, args: ["foo:script"]);
- pub.stdout.expect("bar 1.0.0");
- pub.shouldExit();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'global_packages',
- [
- d.nothing('foo.lock'),
- d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.0.0'))])])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_missing_package_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_missing_package_test.dart
deleted file mode 100644
index cfb153c..0000000
--- a/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_missing_package_test.dart
+++ /dev/null
@@ -1,29 +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 pub_tests;
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- integration('fails gracefully if the package does not exist', () {
- serveNoPackages();
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubCommand(command, error: new RegExp(r"""
-Could not find package foo at http://localhost:\d+\.
-Depended on by:
-- myapp""", multiLine: true), exitCode: exit_codes.UNAVAILABLE);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_url_resolve_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_url_resolve_test.dart
deleted file mode 100644
index b92346f..0000000
--- a/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_url_resolve_test.dart
+++ /dev/null
@@ -1,31 +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 pub_tests;
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- integration('fails gracefully if the url does not resolve', () {
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "hosted": {
- "name": "foo",
- "url": "http://pub.invalid"
- }
- }
- })]).create();
-
- pubCommand(
- command,
- error: 'Could not resolve URL "http://pub.invalid".',
- exitCode: exit_codes.UNAVAILABLE);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/hosted/offline_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/offline_test.dart
deleted file mode 100644
index 8a3bae5..0000000
--- a/sdk/lib/_internal/pub_generated/test/hosted/offline_test.dart
+++ /dev/null
@@ -1,76 +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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- integration('upgrades a package using the cache', () {
- // Run the server so that we know what URL to use in the system cache.
- serveNoPackages();
-
- d.cacheDir({
- "foo": ["1.2.2", "1.2.3"],
- "bar": ["1.2.3"]
- }, includePubspecs: true).create();
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- var warning = null;
- if (command == RunCommand.upgrade) {
- warning =
- "Warning: Upgrading when offline may not update you "
- "to the latest versions of your dependencies.";
- }
-
- pubCommand(command, args: ['--offline'], warning: warning);
-
- d.packagesDir({
- "foo": "1.2.3",
- "bar": "1.2.3"
- }).validate();
- });
-
- integration('fails gracefully if a dependency is not cached', () {
- // Run the server so that we know what URL to use in the system cache.
- serveNoPackages();
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubCommand(
- command,
- args: ['--offline'],
- error: "Could not find package foo in cache.");
- });
-
- integration('fails gracefully no cached versions match', () {
- // Run the server so that we know what URL to use in the system cache.
- serveNoPackages();
-
- d.cacheDir({
- "foo": ["1.2.2", "1.2.3"]
- }, includePubspecs: true).create();
-
- d.appDir({
- "foo": ">2.0.0"
- }).create();
-
- pubCommand(
- command,
- args: ['--offline'],
- error: "Package foo has no versions that match >2.0.0 derived from:\n"
- "- myapp 0.0.0 depends on version >2.0.0");
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_dependency_test.dart
deleted file mode 100644
index 1ec05e0..0000000
--- a/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_dependency_test.dart
+++ /dev/null
@@ -1,44 +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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- integration("removes a dependency that's removed from the pubspec", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("bar", "1.0.0");
- });
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0"
- }).validate();
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": null
- }).validate();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_transitive_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_transitive_dependency_test.dart
deleted file mode 100644
index a5f1a30..0000000
--- a/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_transitive_dependency_test.dart
+++ /dev/null
@@ -1,57 +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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- integration(
- "removes a transitive dependency that's no longer depended " "on",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "shared-dep": "any"
- });
- builder.serve("bar", "1.0.0", deps: {
- "shared-dep": "any",
- "bar-dep": "any"
- });
- builder.serve("shared-dep", "1.0.0");
- builder.serve("bar-dep", "1.0.0");
- });
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0",
- "shared-dep": "1.0.0",
- "bar-dep": "1.0.0",
- }).validate();
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": null,
- "shared-dep": "1.0.0",
- "bar-dep": null,
- }).validate();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/hosted/version_negotiation_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/version_negotiation_test.dart
deleted file mode 100644
index 7d2914e..0000000
--- a/sdk/lib/_internal/pub_generated/test/hosted/version_negotiation_test.dart
+++ /dev/null
@@ -1,69 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- integration('sends the correct Accept header', () {
- var server = new ScheduledServer();
-
- d.appDir({
- "foo": {
- "hosted": {
- "name": "foo",
- "url": server.url.then((url) => url.toString())
- }
- }
- }).create();
-
- var pub = startPub(args: [command.name]);
-
- server.handle('GET', '/api/packages/foo', (request) {
- expect(
- request.headers['accept'],
- equals('application/vnd.pub.v2+json'));
- return new shelf.Response(200);
- });
-
- pub.kill();
- });
-
- integration('prints a friendly error if the version is out-of-date', () {
- var server = new ScheduledServer();
-
- d.appDir({
- "foo": {
- "hosted": {
- "name": "foo",
- "url": server.url.then((url) => url.toString())
- }
- }
- }).create();
-
- var pub = startPub(args: [command.name]);
-
- server.handle(
- 'GET',
- '/api/packages/foo',
- (request) => new shelf.Response(406));
-
- pub.shouldExit(1);
-
- pub.stderr.expect(
- emitsLines(
- "Pub 0.1.2+3 is incompatible with the current version of localhost.\n"
- "Upgrade pub to the latest version and try again."));
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/implicit_barback_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/implicit_barback_dependency_test.dart
deleted file mode 100644
index a725797..0000000
--- a/sdk/lib/_internal/pub_generated/test/implicit_barback_dependency_test.dart
+++ /dev/null
@@ -1,173 +0,0 @@
-// Copyright (c) 2013, 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:pub_semver/pub_semver.dart';
-
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-import '../lib/src/barback.dart' as barback;
-
-main() {
- initConfig();
-
- var constraint = barback.pubConstraints["barback"];
- var current = constraint.min.toString();
- var previous =
- new Version(constraint.min.major, constraint.min.minor - 1, 0).toString();
- var nextPatch = constraint.min.nextPatch.toString();
- var max = constraint.max.toString();
-
- var sourceSpanVersion = barback.pubConstraints["source_span"].min.toString();
- var stackTraceVersion = barback.pubConstraints["stack_trace"].min.toString();
-
- forBothPubGetAndUpgrade((command) {
- integration("implicitly constrains barback to versions pub supports", () {
- servePackages((builder) {
- builder.serve("barback", previous);
- builder.serve("barback", current);
- builder.serve("barback", nextPatch);
- builder.serve("barback", max);
- builder.serve("source_span", sourceSpanVersion);
- builder.serve("stack_trace", stackTraceVersion);
- });
-
- d.appDir({
- "barback": "any"
- }).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "barback": nextPatch
- }).validate();
- });
-
- integration("discovers transitive dependency on barback", () {
- servePackages((builder) {
- builder.serve("barback", previous);
- builder.serve("barback", current);
- builder.serve("barback", nextPatch);
- builder.serve("barback", max);
- builder.serve("source_span", sourceSpanVersion);
- builder.serve("stack_trace", stackTraceVersion);
- });
-
- d.dir(
- "foo",
- [d.libDir("foo", "foo 0.0.1"), d.libPubspec("foo", "0.0.1", deps: {
- "barback": "any"
- })]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo"
- }
- }).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "barback": nextPatch,
- "foo": "0.0.1"
- }).validate();
- });
-
- integration(
- "pub's implicit constraint uses the same source and "
- "description as a dependency override",
- () {
- servePackages((builder) {
- builder.serve("source_span", sourceSpanVersion);
- builder.serve("stack_trace", stackTraceVersion);
- });
-
- d.dir(
- 'barback',
- [
- d.libDir('barback', 'barback $current'),
- d.libPubspec('barback', current),]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependency_overrides": {
- "barback": {
- "path": "../barback"
- }
- }
- })]).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "barback": current
- }).validate();
- });
- });
-
- integration("unlock if the locked version doesn't meet pub's constraint", () {
- servePackages((builder) {
- builder.serve("barback", previous);
- builder.serve("barback", current);
- builder.serve("source_span", sourceSpanVersion);
- builder.serve("stack_trace", stackTraceVersion);
- });
-
- d.appDir({
- "barback": "any"
- }).create();
-
- // Hand-create a lockfile to pin barback to an older version.
- createLockFile("myapp", hosted: {
- "barback": previous
- });
-
- pubGet();
-
- // It should be upgraded.
- d.packagesDir({
- "barback": current
- }).validate();
- });
-
- integration(
- "includes pub in the error if a solve failed because there "
- "is no version available",
- () {
- servePackages((builder) {
- builder.serve("barback", previous);
- builder.serve("source_span", sourceSpanVersion);
- builder.serve("stack_trace", stackTraceVersion);
- });
-
- d.appDir({
- "barback": "any"
- }).create();
-
- pubGet(error: """
-Package barback 0.12.0 does not match >=$current <$max derived from:
-- myapp 0.0.0 depends on version any
-- pub itself depends on version >=$current <$max""");
- });
-
- integration(
- "includes pub in the error if a solve failed because there "
- "is a disjoint constraint",
- () {
- servePackages((builder) {
- builder.serve("barback", previous);
- builder.serve("barback", current);
- builder.serve("source_span", sourceSpanVersion);
- builder.serve("stack_trace", stackTraceVersion);
- });
-
- d.appDir({
- "barback": previous
- }).create();
-
- pubGet(error: """
-Incompatible version constraints on barback:
-- myapp 0.0.0 depends on version $previous
-- pub itself depends on version >=$current <$max""");
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/implicit_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/implicit_dependency_test.dart
deleted file mode 100644
index d3c8560..0000000
--- a/sdk/lib/_internal/pub_generated/test/implicit_dependency_test.dart
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright (c) 2013, 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:pub_semver/pub_semver.dart';
-
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-import '../lib/src/barback.dart' as barback;
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- integration("implicitly constrains it to versions pub supports", () {
- servePackages((builder) {
- builder.serve("barback", current("barback"));
- builder.serve("stack_trace", previous("stack_trace"));
- builder.serve("stack_trace", current("stack_trace"));
- builder.serve("stack_trace", nextPatch("stack_trace"));
- builder.serve("stack_trace", max("stack_trace"));
- builder.serve("source_span", current("source_span"));
- });
-
- d.appDir({
- "barback": "any"
- }).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "stack_trace": nextPatch("stack_trace")
- }).validate();
- });
-
- integration(
- "pub's implicit constraint uses the same source and "
- "description as a dependency override",
- () {
- servePackages((builder) {
- builder.serve("barback", current("barback"));
- builder.serve("stack_trace", nextPatch("stack_trace"));
- builder.serve("source_span", current("source_span"));
- });
-
- d.dir(
- "stack_trace",
- [
- d.libDir("stack_trace", 'stack_trace ${current("stack_trace")}'),
- d.libPubspec("stack_trace", current("stack_trace"))]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "barback": "any"
- },
- "dependency_overrides": {
- "stack_trace": {
- "path": "../stack_trace"
- },
- }
- })]).create();
-
- pubCommand(command);
-
- // Validate that we're using the path dependency version of stack_trace
- // rather than the hosted version.
- d.packagesDir({
- "stack_trace": current("stack_trace")
- }).validate();
- });
-
- integration(
- "doesn't add a constraint if barback isn't in the package " "graph",
- () {
- servePackages((builder) {
- builder.serve("stack_trace", previous("stack_trace"));
- builder.serve("stack_trace", current("stack_trace"));
- builder.serve("stack_trace", nextPatch("stack_trace"));
- builder.serve("stack_trace", max("stack_trace"));
- builder.serve("source_span", current("source_span"));
- });
-
- d.appDir({
- "stack_trace": "any"
- }).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "stack_trace": max("stack_trace")
- }).validate();
- });
- });
-
- integration(
- "unlocks if the locked version doesn't meet pub's " "constraint",
- () {
- servePackages((builder) {
- builder.serve("barback", current("barback"));
- builder.serve("stack_trace", previous("stack_trace"));
- builder.serve("stack_trace", current("stack_trace"));
- builder.serve("source_span", current("source_span"));
- });
-
- d.appDir({
- "barback": "any"
- }).create();
-
- // Hand-create a lockfile to pin the package to an older version.
- createLockFile("myapp", hosted: {
- "barback": current("barback"),
- "stack_trace": previous("stack_trace")
- });
-
- pubGet();
-
- // It should be upgraded.
- d.packagesDir({
- "stack_trace": current("stack_trace")
- }).validate();
- });
-}
-
-String current(String packageName) =>
- barback.pubConstraints[packageName].min.toString();
-
-String previous(String packageName) {
- var constraint = barback.pubConstraints[packageName];
- return new Version(
- constraint.min.major,
- constraint.min.minor - 1,
- 0).toString();
-}
-
-String nextPatch(String packageName) =>
- barback.pubConstraints[packageName].min.nextPatch.toString();
-
-String max(String packageName) =>
- barback.pubConstraints[packageName].max.toString();
diff --git a/sdk/lib/_internal/pub_generated/test/io_test.dart b/sdk/lib/_internal/pub_generated/test/io_test.dart
deleted file mode 100644
index 056843f..0000000
--- a/sdk/lib/_internal/pub_generated/test/io_test.dart
+++ /dev/null
@@ -1,371 +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 io_test;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-import 'package:unittest/unittest.dart';
-
-import '../lib/src/io.dart';
-import 'test_pub.dart';
-
-main() {
- initConfig();
-
- group('listDir', () {
- test('ignores hidden files by default', () {
- expect(withTempDir((temp) {
- writeTextFile(path.join(temp, 'file1.txt'), '');
- writeTextFile(path.join(temp, 'file2.txt'), '');
- writeTextFile(path.join(temp, '.file3.txt'), '');
- createDir(path.join(temp, '.subdir'));
- writeTextFile(path.join(temp, '.subdir', 'file3.txt'), '');
-
- expect(
- listDir(temp, recursive: true),
- unorderedEquals([path.join(temp, 'file1.txt'), path.join(temp, 'file2.txt')]));
- }), completes);
- });
-
- test('includes hidden files when told to', () {
- expect(withTempDir((temp) {
- writeTextFile(path.join(temp, 'file1.txt'), '');
- writeTextFile(path.join(temp, 'file2.txt'), '');
- writeTextFile(path.join(temp, '.file3.txt'), '');
- createDir(path.join(temp, '.subdir'));
- writeTextFile(path.join(temp, '.subdir', 'file3.txt'), '');
-
- expect(
- listDir(temp, recursive: true, includeHidden: true),
- unorderedEquals(
- [
- path.join(temp, 'file1.txt'),
- path.join(temp, 'file2.txt'),
- path.join(temp, '.file3.txt'),
- path.join(temp, '.subdir'),
- path.join(temp, '.subdir', 'file3.txt')]));
- }), completes);
- });
-
- test("doesn't ignore hidden files above the directory being listed", () {
- expect(withTempDir((temp) {
- var dir = path.join(temp, '.foo', 'bar');
- ensureDir(dir);
- writeTextFile(path.join(dir, 'file1.txt'), '');
- writeTextFile(path.join(dir, 'file2.txt'), '');
- writeTextFile(path.join(dir, 'file3.txt'), '');
-
- expect(
- listDir(dir, recursive: true),
- unorderedEquals(
- [
- path.join(dir, 'file1.txt'),
- path.join(dir, 'file2.txt'),
- path.join(dir, 'file3.txt')]));
- }), completes);
- });
- });
-
- group('canonicalize', () {
- test('resolves a non-link', () {
- expect(withCanonicalTempDir((temp) {
- var filePath = path.join(temp, 'file');
- writeTextFile(filePath, '');
- expect(canonicalize(filePath), equals(filePath));
- }), completes);
- });
-
- test('resolves a non-existent file', () {
- expect(withCanonicalTempDir((temp) {
- expect(
- canonicalize(path.join(temp, 'nothing')),
- equals(path.join(temp, 'nothing')));
- }), completes);
- });
-
- test('resolves a symlink', () {
- expect(withCanonicalTempDir((temp) {
- createDir(path.join(temp, 'linked-dir'));
- createSymlink(path.join(temp, 'linked-dir'), path.join(temp, 'dir'));
- expect(
- canonicalize(path.join(temp, 'dir')),
- equals(path.join(temp, 'linked-dir')));
- }), completes);
- });
-
- test('resolves a relative symlink', () {
- expect(withCanonicalTempDir((temp) {
- createDir(path.join(temp, 'linked-dir'));
- createSymlink(
- path.join(temp, 'linked-dir'),
- path.join(temp, 'dir'),
- relative: true);
- expect(
- canonicalize(path.join(temp, 'dir')),
- equals(path.join(temp, 'linked-dir')));
- }), completes);
- });
-
- test('resolves a single-level horizontally recursive symlink', () {
- expect(withCanonicalTempDir((temp) {
- var linkPath = path.join(temp, 'foo');
- createSymlink(linkPath, linkPath);
- expect(canonicalize(linkPath), equals(linkPath));
- }), completes);
- });
-
- test('resolves a multi-level horizontally recursive symlink', () {
- expect(withCanonicalTempDir((temp) {
- var fooPath = path.join(temp, 'foo');
- var barPath = path.join(temp, 'bar');
- var bazPath = path.join(temp, 'baz');
- createSymlink(barPath, fooPath);
- createSymlink(bazPath, barPath);
- createSymlink(fooPath, bazPath);
- expect(canonicalize(fooPath), equals(fooPath));
- expect(canonicalize(barPath), equals(barPath));
- expect(canonicalize(bazPath), equals(bazPath));
-
- createSymlink(fooPath, path.join(temp, 'outer'));
- expect(canonicalize(path.join(temp, 'outer')), equals(fooPath));
- }), completes);
- });
-
- test('resolves a broken symlink', () {
- expect(withCanonicalTempDir((temp) {
- createSymlink(path.join(temp, 'nonexistent'), path.join(temp, 'foo'));
- expect(
- canonicalize(path.join(temp, 'foo')),
- equals(path.join(temp, 'nonexistent')));
- }), completes);
- });
-
- test('resolves multiple nested symlinks', () {
- expect(withCanonicalTempDir((temp) {
- var dir1 = path.join(temp, 'dir1');
- var dir2 = path.join(temp, 'dir2');
- var subdir1 = path.join(dir1, 'subdir1');
- var subdir2 = path.join(dir2, 'subdir2');
- createDir(dir2);
- createDir(subdir2);
- createSymlink(dir2, dir1);
- createSymlink(subdir2, subdir1);
- expect(
- canonicalize(path.join(subdir1, 'file')),
- equals(path.join(subdir2, 'file')));
- }), completes);
- });
-
- test('resolves a nested vertical symlink', () {
- expect(withCanonicalTempDir((temp) {
- var dir1 = path.join(temp, 'dir1');
- var dir2 = path.join(temp, 'dir2');
- var subdir = path.join(dir1, 'subdir');
- createDir(dir1);
- createDir(dir2);
- createSymlink(dir2, subdir);
- expect(
- canonicalize(path.join(subdir, 'file')),
- equals(path.join(dir2, 'file')));
- }), completes);
- });
-
- test('resolves a vertically recursive symlink', () {
- expect(withCanonicalTempDir((temp) {
- var dir = path.join(temp, 'dir');
- var subdir = path.join(dir, 'subdir');
- createDir(dir);
- createSymlink(dir, subdir);
- expect(
- canonicalize(
- path.join(temp, 'dir', 'subdir', 'subdir', 'subdir', 'subdir', 'file')),
- equals(path.join(dir, 'file')));
- }), completes);
- });
-
- test(
- 'resolves a symlink that links to a path that needs more resolving',
- () {
- expect(withCanonicalTempDir((temp) {
- var dir = path.join(temp, 'dir');
- var linkdir = path.join(temp, 'linkdir');
- var linkfile = path.join(dir, 'link');
- createDir(dir);
- createSymlink(dir, linkdir);
- createSymlink(path.join(linkdir, 'file'), linkfile);
- expect(canonicalize(linkfile), equals(path.join(dir, 'file')));
- }), completes);
- });
-
- test('resolves a pair of pathologically-recursive symlinks', () {
- expect(withCanonicalTempDir((temp) {
- var foo = path.join(temp, 'foo');
- var subfoo = path.join(foo, 'subfoo');
- var bar = path.join(temp, 'bar');
- var subbar = path.join(bar, 'subbar');
- createSymlink(subbar, foo);
- createSymlink(subfoo, bar);
- expect(
- canonicalize(subfoo),
- equals(path.join(subfoo, 'subbar', 'subfoo')));
- }), completes);
- });
- });
-
- testExistencePredicate(
- "entryExists",
- entryExists,
- forFile: true,
- forFileSymlink: true,
- forMultiLevelFileSymlink: true,
- forDirectory: true,
- forDirectorySymlink: true,
- forMultiLevelDirectorySymlink: true,
- forBrokenSymlink: true,
- forMultiLevelBrokenSymlink: true);
-
- testExistencePredicate(
- "linkExists",
- linkExists,
- forFile: false,
- forFileSymlink: true,
- forMultiLevelFileSymlink: true,
- forDirectory: false,
- forDirectorySymlink: true,
- forMultiLevelDirectorySymlink: true,
- forBrokenSymlink: true,
- forMultiLevelBrokenSymlink: true);
-
- testExistencePredicate(
- "fileExists",
- fileExists,
- forFile: true,
- forFileSymlink: true,
- forMultiLevelFileSymlink: true,
- forDirectory: false,
- forDirectorySymlink: false,
- forMultiLevelDirectorySymlink: false,
- forBrokenSymlink: false,
- forMultiLevelBrokenSymlink: false);
-
- testExistencePredicate(
- "dirExists",
- dirExists,
- forFile: false,
- forFileSymlink: false,
- forMultiLevelFileSymlink: false,
- forDirectory: true,
- forDirectorySymlink: true,
- forMultiLevelDirectorySymlink: true,
- forBrokenSymlink: false,
- forMultiLevelBrokenSymlink: false);
-}
-
-void testExistencePredicate(String name, bool predicate(String path),
- {bool forFile, bool forFileSymlink, bool forMultiLevelFileSymlink,
- bool forDirectory, bool forDirectorySymlink, bool forMultiLevelDirectorySymlink,
- bool forBrokenSymlink, bool forMultiLevelBrokenSymlink}) {
- group(name, () {
- test('returns $forFile for a file', () {
- expect(withTempDir((temp) {
- var file = path.join(temp, "test.txt");
- writeTextFile(file, "contents");
- expect(predicate(file), equals(forFile));
- }), completes);
- });
-
- test('returns $forDirectory for a directory', () {
- expect(withTempDir((temp) {
- var file = path.join(temp, "dir");
- createDir(file);
- expect(predicate(file), equals(forDirectory));
- }), completes);
- });
-
- test('returns $forDirectorySymlink for a symlink to a directory', () {
- expect(withTempDir((temp) {
- var targetPath = path.join(temp, "dir");
- var symlinkPath = path.join(temp, "linkdir");
- createDir(targetPath);
- createSymlink(targetPath, symlinkPath);
- expect(predicate(symlinkPath), equals(forDirectorySymlink));
- }), completes);
- });
-
- test(
- 'returns $forMultiLevelDirectorySymlink for a multi-level symlink to '
- 'a directory',
- () {
- expect(withTempDir((temp) {
- var targetPath = path.join(temp, "dir");
- var symlink1Path = path.join(temp, "link1dir");
- var symlink2Path = path.join(temp, "link2dir");
- createDir(targetPath);
- createSymlink(targetPath, symlink1Path);
- createSymlink(symlink1Path, symlink2Path);
- expect(predicate(symlink2Path), equals(forMultiLevelDirectorySymlink));
- }), completes);
- });
-
- test('returns $forBrokenSymlink for a broken symlink', () {
- expect(withTempDir((temp) {
- var targetPath = path.join(temp, "dir");
- var symlinkPath = path.join(temp, "linkdir");
- createDir(targetPath);
- createSymlink(targetPath, symlinkPath);
- deleteEntry(targetPath);
- expect(predicate(symlinkPath), equals(forBrokenSymlink));
- }), completes);
- });
-
- test(
- 'returns $forMultiLevelBrokenSymlink for a multi-level broken symlink',
- () {
- expect(withTempDir((temp) {
- var targetPath = path.join(temp, "dir");
- var symlink1Path = path.join(temp, "link1dir");
- var symlink2Path = path.join(temp, "link2dir");
- createDir(targetPath);
- createSymlink(targetPath, symlink1Path);
- createSymlink(symlink1Path, symlink2Path);
- deleteEntry(targetPath);
- expect(predicate(symlink2Path), equals(forMultiLevelBrokenSymlink));
- }), completes);
- });
-
- // Windows doesn't support symlinking to files.
- if (Platform.operatingSystem != 'windows') {
- test('returns $forFileSymlink for a symlink to a file', () {
- expect(withTempDir((temp) {
- var targetPath = path.join(temp, "test.txt");
- var symlinkPath = path.join(temp, "link.txt");
- writeTextFile(targetPath, "contents");
- createSymlink(targetPath, symlinkPath);
- expect(predicate(symlinkPath), equals(forFileSymlink));
- }), completes);
- });
-
- test(
- 'returns $forMultiLevelFileSymlink for a multi-level symlink to a ' 'file',
- () {
- expect(withTempDir((temp) {
- var targetPath = path.join(temp, "test.txt");
- var symlink1Path = path.join(temp, "link1.txt");
- var symlink2Path = path.join(temp, "link2.txt");
- writeTextFile(targetPath, "contents");
- createSymlink(targetPath, symlink1Path);
- createSymlink(symlink1Path, symlink2Path);
- expect(predicate(symlink2Path), equals(forMultiLevelFileSymlink));
- }), completes);
- });
- }
- });
-}
-
-/// Like [withTempDir], but canonicalizes the path before passing it to [fn].
-Future withCanonicalTempDir(Future fn(String path)) =>
- withTempDir((temp) => fn(canonicalize(temp)));
diff --git a/sdk/lib/_internal/pub_generated/test/lish/archives_and_uploads_a_package_test.dart b/sdk/lib/_internal/pub_generated/test/lish/archives_and_uploads_a_package_test.dart
deleted file mode 100644
index db70c72..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/archives_and_uploads_a_package_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('archives and uploads a package', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
- handleUploadForm(server);
- handleUpload(server);
-
- server.handle('GET', '/create', (request) {
- return new shelf.Response.ok(JSON.encode({
- 'success': {
- 'message': 'Package test_pkg 1.0.0 uploaded!'
- }
- }));
- });
-
- pub.stdout.expect(startsWith('Uploading...'));
- pub.stdout.expect('Package test_pkg 1.0.0 uploaded!');
- pub.shouldExit(exit_codes.SUCCESS);
- });
-
- // TODO(nweiz): Once a multipart/form-data parser in Dart exists, we should
- // test that "pub lish" chooses the correct files to publish.
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_doesnt_redirect_test.dart b/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_doesnt_redirect_test.dart
deleted file mode 100644
index faef7ca..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_doesnt_redirect_test.dart
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration("cloud storage upload doesn't redirect", () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
- handleUploadForm(server);
-
- server.handle('POST', '/upload', (request) {
- return drainStream(request.read()).then((_) => new shelf.Response(200));
- });
-
- pub.stderr.expect('Failed to upload the package.');
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_provides_an_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_provides_an_error_test.dart
deleted file mode 100644
index a994e23..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_provides_an_error_test.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('cloud storage upload provides an error', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
- handleUploadForm(server);
-
- server.handle('POST', '/upload', (request) {
- return drainStream(request.read()).then((_) {
- return new shelf.Response.notFound(
- '<Error><Message>Your request sucked.</Message></Error>',
- headers: {
- 'content-type': 'application/xml'
- });
- });
- });
-
- // TODO(nweiz): This should use the server's error message once the client
- // can parse the XML.
- pub.stderr.expect('Failed to upload the package.');
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_test.dart b/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_test.dart
deleted file mode 100644
index 9698409..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_test.dart
+++ /dev/null
@@ -1,23 +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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('does not publish if the package is private', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["publish_to"] = "none";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- schedulePub(
- args: ["lish"],
- error: startsWith("A private package cannot be published."),
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_with_server_arg_test.dart b/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_with_server_arg_test.dart
deleted file mode 100644
index 44568c4..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_with_server_arg_test.dart
+++ /dev/null
@@ -1,26 +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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'does not publish if the package is private even if a server '
- 'argument is provided',
- () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["publish_to"] = "none";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- schedulePub(
- args: ["lish", "--server", "http://example.com"],
- error: startsWith("A private package cannot be published."),
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_cannot_be_combined_with_dry_run_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_cannot_be_combined_with_dry_run_test.dart
deleted file mode 100644
index 0cc6cd6..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/force_cannot_be_combined_with_dry_run_test.dart
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('--force cannot be combined with --dry-run', () {
- schedulePub(args: ['lish', '--force', '--dry-run'], error: """
- Cannot use both --force and --dry-run.
-
- Usage: pub publish [options]
- -h, --help Print this usage information.
- -n, --dry-run Validate but do not publish the package.
- -f, --force Publish without confirmation if there are no errors.
- --server The package server to which to upload this package.
- (defaults to "https://pub.dartlang.org")
-
- Run "pub help" to see global options.
- See http://dartlang.org/tools/pub/cmd/pub-lish.html for detailed documentation.
- """, exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_private_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_private_test.dart
deleted file mode 100644
index aca919b..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_private_test.dart
+++ /dev/null
@@ -1,23 +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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('force does not publish if the package is private', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["publish_to"] = "none";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- schedulePub(
- args: ["lish", "--force"],
- error: startsWith("A private package cannot be published."),
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_there_are_errors_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_there_are_errors_test.dart
deleted file mode 100644
index d651716..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_there_are_errors_test.dart
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('--force does not publish if there are errors', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg.remove("homepage");
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- var server = new ScheduledServer();
- var pub = startPublish(server, args: ['--force']);
-
- pub.shouldExit(exit_codes.SUCCESS);
- pub.stderr.expect(
- consumeThrough(
- "Sorry, your package is missing a " "requirement and can't be published yet."));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_tests_are_no_warnings_or_errors_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_tests_are_no_warnings_or_errors_test.dart
deleted file mode 100644
index 0db2516d..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_tests_are_no_warnings_or_errors_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('--force publishes if there are no warnings or errors', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server, args: ['--force']);
-
- handleUploadForm(server);
- handleUpload(server);
-
- server.handle('GET', '/create', (request) {
- return new shelf.Response.ok(JSON.encode({
- 'success': {
- 'message': 'Package test_pkg 1.0.0 uploaded!'
- }
- }));
- });
-
- pub.shouldExit(exit_codes.SUCCESS);
- pub.stdout.expect(consumeThrough('Package test_pkg 1.0.0 uploaded!'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_there_are_warnings_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_there_are_warnings_test.dart
deleted file mode 100644
index faf58fe..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_there_are_warnings_test.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('--force publishes if there are warnings', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["author"] = "Natalie Weizenbaum";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server, args: ['--force']);
-
- handleUploadForm(server);
- handleUpload(server);
-
- server.handle('GET', '/create', (request) {
- return new shelf.Response.ok(JSON.encode({
- 'success': {
- 'message': 'Package test_pkg 1.0.0 uploaded!'
- }
- }));
- });
-
- pub.shouldExit(exit_codes.SUCCESS);
- pub.stderr.expect(consumeThrough('Suggestions:'));
- pub.stderr.expect(
- emitsLines(
- '* Author "Natalie Weizenbaum" in pubspec.yaml should have an email '
- 'address\n' ' (e.g. "name <email>").'));
- pub.stdout.expect(consumeThrough('Package test_pkg 1.0.0 uploaded!'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_error_test.dart
deleted file mode 100644
index cfd75aa..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_error_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('package creation provides a malformed error', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
- handleUploadForm(server);
- handleUpload(server);
-
- var body = {
- 'error': 'Your package was too boring.'
- };
- server.handle('GET', '/create', (request) {
- return new shelf.Response.notFound(JSON.encode(body));
- });
-
- pub.stderr.expect('Invalid server response:');
- pub.stderr.expect(JSON.encode(body));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_success_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_success_test.dart
deleted file mode 100644
index 5696382..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_success_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('package creation provides a malformed success', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
- handleUploadForm(server);
- handleUpload(server);
-
- var body = {
- 'success': 'Your package was awesome.'
- };
- server.handle('GET', '/create', (request) {
- return new shelf.Response.ok(JSON.encode(body));
- });
-
- pub.stderr.expect('Invalid server response:');
- pub.stderr.expect(JSON.encode(body));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_an_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_an_error_test.dart
deleted file mode 100644
index fec17cd..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_an_error_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('package creation provides an error', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
- handleUploadForm(server);
- handleUpload(server);
-
- server.handle('GET', '/create', (request) {
- return new shelf.Response.notFound(JSON.encode({
- 'error': {
- 'message': 'Your package was too boring.'
- }
- }));
- });
-
- pub.stderr.expect('Your package was too boring.');
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_invalid_json_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_invalid_json_test.dart
deleted file mode 100644
index d6babb9..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_invalid_json_test.dart
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('package creation provides invalid JSON', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
- handleUploadForm(server);
- handleUpload(server);
-
- server.handle('GET', '/create', (request) {
- return new shelf.Response.ok('{not json');
- });
-
- pub.stderr.expect(emitsLines('Invalid server response:\n' '{not json'));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_continues_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_continues_test.dart
deleted file mode 100644
index 18e2f5b..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_continues_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('package validation has a warning and continues', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["author"] = "Natalie Weizenbaum";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
- pub.writeLine("y");
- handleUploadForm(server);
- handleUpload(server);
-
- server.handle('GET', '/create', (request) {
- return new shelf.Response.ok(JSON.encode({
- 'success': {
- 'message': 'Package test_pkg 1.0.0 uploaded!'
- }
- }));
- });
-
- pub.shouldExit(exit_codes.SUCCESS);
- pub.stdout.expect(consumeThrough('Package test_pkg 1.0.0 uploaded!'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_is_canceled_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_is_canceled_test.dart
deleted file mode 100644
index 314c528e9..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_is_canceled_test.dart
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('package validation has a warning and is canceled', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["author"] = "Natalie Weizenbaum";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- var server = new ScheduledServer();
- var pub = startPublish(server);
-
- pub.writeLine("n");
- pub.shouldExit(exit_codes.SUCCESS);
- pub.stderr.expect(consumeThrough("Package upload canceled."));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_an_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_an_error_test.dart
deleted file mode 100644
index dacc67c..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_an_error_test.dart
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('package validation has an error', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg.remove("homepage");
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- var server = new ScheduledServer();
- var pub = startPublish(server);
-
- pub.shouldExit(exit_codes.SUCCESS);
- pub.stderr.expect(
- consumeThrough(
- "Sorry, your package is missing a " "requirement and can't be published yet."));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/preview_errors_if_private_test.dart b/sdk/lib/_internal/pub_generated/test/lish/preview_errors_if_private_test.dart
deleted file mode 100644
index 642c5c3..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/preview_errors_if_private_test.dart
+++ /dev/null
@@ -1,23 +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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('preview shows an error if the package is private', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["publish_to"] = "none";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- schedulePub(
- args: ["lish", "--dry-run"],
- error: startsWith("A private package cannot be published."),
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_a_warning_test.dart b/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_a_warning_test.dart
deleted file mode 100644
index 4f229af..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_a_warning_test.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('preview package validation has a warning', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["author"] = "Natalie Weizenbaum";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- var server = new ScheduledServer();
- var pub = startPublish(server, args: ['--dry-run']);
-
- pub.shouldExit(exit_codes.SUCCESS);
- pub.stderr.expect(consumeThrough('Suggestions:'));
- pub.stderr.expect(
- emitsLines(
- '* Author "Natalie Weizenbaum" in pubspec.yaml should have an email '
- 'address\n' ' (e.g. "name <email>").\n' '\n' 'Package has 1 warning.'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_no_warnings_test.dart b/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_no_warnings_test.dart
deleted file mode 100644
index 66f092e..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_no_warnings_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('preview package validation has no warnings', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["author"] = "Natalie Weizenbaum <nweiz@google.com>";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- var server = new ScheduledServer();
- var pub = startPublish(server, args: ['--dry-run']);
-
- pub.shouldExit(exit_codes.SUCCESS);
- pub.stderr.expect(consumeThrough('Package has 0 warnings.'));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/server_arg_does_not_override_private_test.dart b/sdk/lib/_internal/pub_generated/test/lish/server_arg_does_not_override_private_test.dart
deleted file mode 100644
index 37c3f22..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/server_arg_does_not_override_private_test.dart
+++ /dev/null
@@ -1,23 +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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('an explicit --server argument does not override privacy', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["publish_to"] = "none";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- schedulePub(
- args: ["lish", "--server", "http://arg.com"],
- error: startsWith("A private package cannot be published."),
- exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/server_arg_overrides_publish_to_url_test.dart b/sdk/lib/_internal/pub_generated/test/lish/server_arg_overrides_publish_to_url_test.dart
deleted file mode 100644
index b509445..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/server_arg_overrides_publish_to_url_test.dart
+++ /dev/null
@@ -1,21 +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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('an explicit --server argument overrides a "publish_to" url', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["publish_to"] = "http://pubspec.com";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- schedulePub(
- args: ["lish", "--dry-run", "--server", "http://arg.com"],
- output: contains("http://arg.com"));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_has_a_non_string_value_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_has_a_non_string_value_test.dart
deleted file mode 100644
index b24270c..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_has_a_non_string_value_test.dart
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('upload form fields has a non-string value', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- var body = {
- 'url': 'http://example.com/upload',
- 'fields': {
- 'field': 12
- }
- };
- handleUploadForm(server, body);
- pub.stderr.expect('Invalid server response:');
- pub.stderr.expect(JSON.encode(body));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_is_not_a_map_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_is_not_a_map_test.dart
deleted file mode 100644
index ed5ad00..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_is_not_a_map_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('upload form fields is not a map', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- var body = {
- 'url': 'http://example.com/upload',
- 'fields': 12
- };
- handleUploadForm(server, body);
- pub.stderr.expect('Invalid server response:');
- pub.stderr.expect(JSON.encode(body));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_fields_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_fields_test.dart
deleted file mode 100644
index 433666a..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_fields_test.dart
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('upload form is missing fields', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- var body = {
- 'url': 'http://example.com/upload'
- };
- handleUploadForm(server, body);
- pub.stderr.expect('Invalid server response:');
- pub.stderr.expect(JSON.encode(body));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_url_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_url_test.dart
deleted file mode 100644
index a08b581..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_url_test.dart
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('upload form is missing url', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- var body = {
- 'fields': {
- 'field1': 'value1',
- 'field2': 'value2'
- }
- };
-
- handleUploadForm(server, body);
- pub.stderr.expect('Invalid server response:');
- pub.stderr.expect(JSON.encode(body));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_an_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_an_error_test.dart
deleted file mode 100644
index bf65fd0..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_an_error_test.dart
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('upload form provides an error', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- server.handle('GET', '/api/packages/versions/new', (request) {
- return new shelf.Response.notFound(JSON.encode({
- 'error': {
- 'message': 'your request sucked'
- }
- }));
- });
-
- pub.stderr.expect('your request sucked');
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_invalid_json_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_invalid_json_test.dart
deleted file mode 100644
index 70d4df0..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_invalid_json_test.dart
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('upload form provides invalid JSON', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- server.handle(
- 'GET',
- '/api/packages/versions/new',
- (request) => new shelf.Response.ok('{not json'));
-
- pub.stderr.expect(emitsLines('Invalid server response:\n' '{not json'));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_url_is_not_a_string_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_url_is_not_a_string_test.dart
deleted file mode 100644
index 2f32df4..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_url_is_not_a_string_test.dart
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(d.validPackage.create);
-
- integration('upload form url is not a string', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- var body = {
- 'url': 12,
- 'fields': {
- 'field1': 'value1',
- 'field2': 'value2'
- }
- };
-
- handleUploadForm(server, body);
- pub.stderr.expect('Invalid server response:');
- pub.stderr.expect(JSON.encode(body));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/uses_publish_to_url_test.dart b/sdk/lib/_internal/pub_generated/test/lish/uses_publish_to_url_test.dart
deleted file mode 100644
index 32ca1b8..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/uses_publish_to_url_test.dart
+++ /dev/null
@@ -1,21 +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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('preview shows an error if the package is private', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["publish_to"] = "http://example.com";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- schedulePub(
- args: ["lish", "--dry-run"],
- output: contains("Publishing test_pkg 1.0.0 to http://example.com"));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lish/utils.dart b/sdk/lib/_internal/pub_generated/test/lish/utils.dart
deleted file mode 100644
index 1342f8e..0000000
--- a/sdk/lib/_internal/pub_generated/test/lish/utils.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2013, 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 lish.utils;
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/io.dart';
-
-void handleUploadForm(ScheduledServer server, [Map body]) {
- server.handle('GET', '/api/packages/versions/new', (request) {
- return server.url.then((url) {
- expect(
- request.headers,
- containsPair('authorization', 'Bearer access token'));
-
- if (body == null) {
- body = {
- 'url': url.resolve('/upload').toString(),
- 'fields': {
- 'field1': 'value1',
- 'field2': 'value2'
- }
- };
- }
-
- return new shelf.Response.ok(JSON.encode(body), headers: {
- 'content-type': 'application/json'
- });
- });
- });
-}
-
-void handleUpload(ScheduledServer server) {
- server.handle('POST', '/upload', (request) {
- // TODO(nweiz): Once a multipart/form-data parser in Dart exists, validate
- // that the request body is correctly formatted. See issue 6952.
- return drainStream(
- request.read()).then(
- (_) =>
- server.url).then((url) => new shelf.Response.found(url.resolve('/create')));
- });
-}
-
diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/ignores_updated_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/ignores_updated_pubspec_test.dart
deleted file mode 100644
index df4f670..0000000
--- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/ignores_updated_pubspec_test.dart
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("uses what's in the lockfile regardless of the pubspec", () {
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "1.0.0")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": path.join(sandboxDir, "foo")
- }
- })]).create();
-
- pubGet();
-
- // Add a dependency on "bar" and remove "foo", but don't run "pub get".
- d.dir(appPath, [d.appPubspec({
- "bar": "any"
- })]).create();
-
- // Note: Using canonicalize here because pub gets the path to the
- // entrypoint package from the working directory, which has had symlinks
- // resolve. On Mac, "/tmp" is actually a symlink to "/private/tmp", so we
- // need to accomodate that.
- schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: {
- "packages": {
- "foo": path.join(sandboxDir, "foo", "lib"),
- "myapp": canonicalize(path.join(sandboxDir, appPath, "lib"))
- },
- "input_files": [
- canonicalize(path.join(sandboxDir, appPath, "pubspec.lock")),
- canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml"))]
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/includes_dev_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/includes_dev_dependencies_test.dart
deleted file mode 100644
index b122013..0000000
--- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/includes_dev_dependencies_test.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('includes dev dependencies in the results', () {
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "1.0.0")]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dev_dependencies": {
- "foo": {
- "path": path.join(sandboxDir, "foo")
- }
- }
- })]).create();
-
- pubGet();
-
- // Note: Using canonicalize here because pub gets the path to the
- // entrypoint package from the working directory, which has had symlinks
- // resolve. On Mac, "/tmp" is actually a symlink to "/private/tmp", so we
- // need to accomodate that.
- schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: {
- "packages": {
- "foo": path.join(sandboxDir, "foo", "lib"),
- "myapp": canonicalize(path.join(sandboxDir, appPath, "lib"))
- },
- "input_files": [
- canonicalize(path.join(sandboxDir, appPath, "pubspec.lock")),
- canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml"))]
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/lists_dependency_directories_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/lists_dependency_directories_test.dart
deleted file mode 100644
index c9725c3..0000000
--- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/lists_dependency_directories_test.dart
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('prints the local paths to all packages in the lockfile', () {
- servePackages((builder) => builder.serve("bar", "1.0.0"));
-
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "1.0.0")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": path.join(sandboxDir, "foo")
- },
- "bar": "any"
- })]).create();
-
- pubGet();
-
- // Note: Using canonicalize here because pub gets the path to the
- // entrypoint package from the working directory, which has had symlinks
- // resolve. On Mac, "/tmp" is actually a symlink to "/private/tmp", so we
- // need to accomodate that.
- schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: {
- "packages": {
- "foo": path.join(sandboxDir, "foo", "lib"),
- "bar": port.then(
- (p) =>
- path.join(
- sandboxDir,
- cachePath,
- "hosted",
- "localhost%58$p",
- "bar-1.0.0",
- "lib")),
- "myapp": canonicalize(path.join(sandboxDir, appPath, "lib"))
- },
- "input_files": [
- canonicalize(path.join(sandboxDir, appPath, "pubspec.lock")),
- canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml"))]
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/lockfile_error_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/lockfile_error_test.dart
deleted file mode 100644
index d9b872a..0000000
--- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/lockfile_error_test.dart
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("reports the lockfile path when there is an error in it", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.file("pubspec.lock", "some bad yaml")]).create();
-
- schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: {
- "error": contains('The lockfile must be a YAML mapping.'),
- "path": canonicalize(path.join(sandboxDir, appPath, "pubspec.lock"))
- }, exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/missing_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/missing_pubspec_test.dart
deleted file mode 100644
index 0838cd2..0000000
--- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/missing_pubspec_test.dart
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- // This is a regression test for #20065.
- integration("reports a missing pubspec error using JSON", () {
- d.dir(appPath).create();
-
- schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: {
- "error": 'Could not find a file named "pubspec.yaml" in "'
- '${canonicalize(path.join(sandboxDir, appPath))}".',
- "path": canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml"))
- }, exitCode: 1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/no_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/no_lockfile_test.dart
deleted file mode 100644
index 7bc9570..0000000
--- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/no_lockfile_test.dart
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('with no lockfile, exits with error', () {
- d.dir(appPath, [d.appPubspec()]).create();
-
- schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: {
- "error": 'Package "myapp" has no lockfile. Please run "pub get" first.'
- }, exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/pubspec_error_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/pubspec_error_test.dart
deleted file mode 100644
index 5610e81..0000000
--- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/pubspec_error_test.dart
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("reports the pubspec path when there is an error in it", () {
- d.dir(appPath, [d.file("pubspec.yaml", "some bad yaml")]).create();
-
- schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: {
- "error": contains('Error on line 1'),
- "path": canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml"))
- }, exitCode: exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/lock_file_test.dart b/sdk/lib/_internal/pub_generated/test/lock_file_test.dart
deleted file mode 100644
index de144c2..0000000
--- a/sdk/lib/_internal/pub_generated/test/lock_file_test.dart
+++ /dev/null
@@ -1,229 +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 lock_file_test;
-
-import 'dart:async';
-
-import 'package:pub_semver/pub_semver.dart';
-import 'package:unittest/unittest.dart';
-import 'package:yaml/yaml.dart';
-
-import '../lib/src/lock_file.dart';
-import '../lib/src/package.dart';
-import '../lib/src/pubspec.dart';
-import '../lib/src/source.dart';
-import '../lib/src/source_registry.dart';
-import 'test_pub.dart';
-
-class MockSource extends Source {
- final String name = 'mock';
-
- Future<Pubspec> doDescribe(PackageId id) =>
- throw new UnsupportedError("Cannot describe mock packages.");
-
- Future get(PackageId id, String symlink) =>
- throw new UnsupportedError("Cannot get a mock package.");
-
- Future<String> getDirectory(PackageId id) =>
- throw new UnsupportedError("Cannot get the directory for mock packages.");
-
- dynamic parseDescription(String filePath, String description,
- {bool fromLockFile: false}) {
- if (!description.endsWith(' desc')) throw new FormatException();
- return description;
- }
-
- bool descriptionsEqual(description1, description2) =>
- description1 == description2;
-
- String packageName(String description) {
- // Strip off ' desc'.
- return description.substring(0, description.length - 5);
- }
-}
-
-main() {
- initConfig();
-
- var sources = new SourceRegistry();
- var mockSource = new MockSource();
- sources.register(mockSource);
-
- group('LockFile', () {
- group('parse()', () {
- test('returns an empty lockfile if the contents are empty', () {
- var lockFile = new LockFile.parse('', sources);
- expect(lockFile.packages.length, equals(0));
- });
-
- test('returns an empty lockfile if the contents are whitespace', () {
- var lockFile = new LockFile.parse(' \t\n ', sources);
- expect(lockFile.packages.length, equals(0));
- });
-
- test('parses a series of package descriptions', () {
- var lockFile = new LockFile.parse('''
-packages:
- bar:
- version: 1.2.3
- source: mock
- description: bar desc
- foo:
- version: 2.3.4
- source: mock
- description: foo desc
-''', sources);
-
- expect(lockFile.packages.length, equals(2));
-
- var bar = lockFile.packages['bar'];
- expect(bar.name, equals('bar'));
- expect(bar.version, equals(new Version(1, 2, 3)));
- expect(bar.source, equals(mockSource.name));
- expect(bar.description, equals('bar desc'));
-
- var foo = lockFile.packages['foo'];
- expect(foo.name, equals('foo'));
- expect(foo.version, equals(new Version(2, 3, 4)));
- expect(foo.source, equals(mockSource.name));
- expect(foo.description, equals('foo desc'));
- });
-
- test("allows an unknown source", () {
- var lockFile = new LockFile.parse('''
-packages:
- foo:
- source: bad
- version: 1.2.3
- description: foo desc
-''', sources);
- var foo = lockFile.packages['foo'];
- expect(foo.source, equals('bad'));
- });
-
- test("allows an empty dependency map", () {
- var lockFile = new LockFile.parse('''
-packages:
-''', sources);
- expect(lockFile.packages, isEmpty);
- });
-
- test("throws if the top level is not a map", () {
- expect(() {
- new LockFile.parse('''
-not a map
-''', sources);
- }, throwsFormatException);
- });
-
- test("throws if the contents of 'packages' is not a map", () {
- expect(() {
- new LockFile.parse('''
-packages: not a map
-''', sources);
- }, throwsFormatException);
- });
-
- test("throws if the version is missing", () {
- expect(() {
- new LockFile.parse('''
-packages:
- foo:
- source: mock
- description: foo desc
-''', sources);
- }, throwsFormatException);
- });
-
- test("throws if the version is invalid", () {
- expect(() {
- new LockFile.parse('''
-packages:
- foo:
- version: vorpal
- source: mock
- description: foo desc
-''', sources);
- }, throwsFormatException);
- });
-
- test("throws if the source is missing", () {
- expect(() {
- new LockFile.parse('''
-packages:
- foo:
- version: 1.2.3
- description: foo desc
-''', sources);
- }, throwsFormatException);
- });
-
- test("throws if the description is missing", () {
- expect(() {
- new LockFile.parse('''
-packages:
- foo:
- version: 1.2.3
- source: mock
-''', sources);
- }, throwsFormatException);
- });
-
- test("throws if the description is invalid", () {
- expect(() {
- new LockFile.parse('''
-packages:
- foo:
- version: 1.2.3
- source: mock
- description: foo desc is bad
-''', sources);
- }, throwsFormatException);
- });
-
- test("ignores extra stuff in file", () {
- var lockFile = new LockFile.parse('''
-extra:
- some: stuff
-packages:
- foo:
- bonus: not used
- version: 1.2.3
- source: mock
- description: foo desc
-''', sources);
- });
- });
-
- group('serialize()', () {
- var lockfile;
- setUp(() {
- lockfile = new LockFile.empty();
- });
-
- test('dumps the lockfile to YAML', () {
- lockfile.packages['foo'] =
- new PackageId('foo', mockSource.name, new Version.parse('1.2.3'), 'foo desc');
- lockfile.packages['bar'] =
- new PackageId('bar', mockSource.name, new Version.parse('3.2.1'), 'bar desc');
-
- expect(loadYaml(lockfile.serialize(null, sources)), equals({
- 'packages': {
- 'foo': {
- 'version': '1.2.3',
- 'source': 'mock',
- 'description': 'foo desc'
- },
- 'bar': {
- 'version': '3.2.1',
- 'source': 'mock',
- 'description': 'bar desc'
- }
- }
- }));
- });
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/no_package_symlinks_test.dart b/sdk/lib/_internal/pub_generated/test/no_package_symlinks_test.dart
deleted file mode 100644
index 720561b..0000000
--- a/sdk/lib/_internal/pub_generated/test/no_package_symlinks_test.dart
+++ /dev/null
@@ -1,125 +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:scheduled_test/scheduled_test.dart';
-
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- group("with --no-package-symlinks", () {
- integration("installs hosted dependencies to the cache", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("bar", "1.0.0");
- });
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- pubCommand(command, args: ["--no-package-symlinks"]);
-
- d.nothing("$appPath/packages").validate();
-
- d.hostedCache(
- [
- d.dir(
- "foo-1.0.0",
- [d.dir("lib", [d.file("foo.dart", 'main() => "foo 1.0.0";')])]),
- d.dir(
- "bar-1.0.0",
- [d.dir("lib", [d.file("bar.dart", 'main() => "bar 1.0.0";')])])]).validate();
- });
-
- integration("installs git dependencies to the cache", () {
- ensureGit();
-
- d.git(
- 'foo.git',
- [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubCommand(command, args: ["--no-package-symlinks"]);
-
- d.nothing("$appPath/packages").validate();
-
- d.dir(
- cachePath,
- [
- d.dir(
- 'git',
- [
- d.dir('cache', [d.gitPackageRepoCacheDir('foo')]),
- d.gitPackageRevisionCacheDir('foo')])]).validate();
- });
-
- integration("locks path dependencies", () {
- d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubCommand(command, args: ["--no-package-symlinks"]);
-
- d.nothing("$appPath/packages").validate();
- d.matcherFile("$appPath/pubspec.lock", contains("foo"));
- });
-
- integration("removes package directories near entrypoints", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("packages"),
- d.dir("bin/packages"),
- d.dir("web/packages"),
- d.dir("web/subdir/packages")]).create();
-
- pubCommand(command, args: ["--no-package-symlinks"]);
-
- d.dir(
- appPath,
- [
- d.nothing("packages"),
- d.nothing("bin/packages"),
- d.nothing("web/packages"),
- d.nothing("web/subdir/packages")]).validate();
- });
-
- integration(
- "doesn't remove package directories that pub wouldn't " "generate",
- () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("packages"),
- d.dir("bin/subdir/packages"),
- d.dir("lib/packages")]).create();
-
- pubCommand(command, args: ["--no-package-symlinks"]);
-
- d.dir(
- appPath,
- [
- d.nothing("packages"),
- d.dir("bin/subdir/packages"),
- d.dir("lib/packages")]).validate();
- });
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/utils.dart b/sdk/lib/_internal/pub_generated/test/oauth2/utils.dart
deleted file mode 100644
index 8c6f824..0000000
--- a/sdk/lib/_internal/pub_generated/test/oauth2/utils.dart
+++ /dev/null
@@ -1,58 +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 oauth2.utils;
-
-import 'dart:convert';
-
-import 'package:http/http.dart' as http;
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/utils.dart';
-
-void authorizePub(ScheduledProcess pub, ScheduledServer server,
- [String accessToken = "access token"]) {
- pub.stdout.expect(
- 'Pub needs your authorization to upload packages on your ' 'behalf.');
-
- schedule(() {
- return pub.stdout.next().then((line) {
- var match =
- new RegExp(r'[?&]redirect_uri=([0-9a-zA-Z.%+-]+)[$&]').firstMatch(line);
- expect(match, isNotNull);
-
- var redirectUrl = Uri.parse(Uri.decodeComponent(match.group(1)));
- redirectUrl = addQueryParameters(redirectUrl, {
- 'code': 'access code'
- });
- return (new http.Request('GET', redirectUrl)..followRedirects =
- false).send();
- }).then((response) {
- expect(
- response.headers['location'],
- equals('http://pub.dartlang.org/authorized'));
- });
- });
-
- handleAccessTokenRequest(server, accessToken);
-}
-
-void handleAccessTokenRequest(ScheduledServer server, String accessToken) {
- server.handle('POST', '/token', (request) {
- return request.readAsString().then((body) {
- expect(body, matches(new RegExp(r'(^|&)code=access\+code(&|$)')));
-
- return new shelf.Response.ok(JSON.encode({
- "access_token": accessToken,
- "token_type": "bearer"
- }), headers: {
- 'content-type': 'application/json'
- });
- });
- });
-}
-
diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_malformed_credentials_authenticates_again_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_a_malformed_credentials_authenticates_again_test.dart
deleted file mode 100644
index 48600b5..0000000
--- a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_malformed_credentials_authenticates_again_test.dart
+++ /dev/null
@@ -1,42 +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.
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- 'with a malformed credentials.json, authenticates again and '
- 'saves credentials.json',
- () {
- d.validPackage.create();
-
- var server = new ScheduledServer();
- d.dir(cachePath, [d.file('credentials.json', '{bad json')]).create();
-
- var pub = startPublish(server);
- confirmPublish(pub);
- authorizePub(pub, server, "new access token");
-
- server.handle('GET', '/api/packages/versions/new', (request) {
- expect(
- request.headers,
- containsPair('authorization', 'Bearer new access token'));
-
- return new shelf.Response(200);
- });
-
- // After we give pub an invalid response, it should crash. We wait for it to
- // do so rather than killing it so it'll write out the credentials file.
- pub.shouldExit(1);
-
- d.credentialsFile(server, 'new access token').validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_pre_existing_credentials_does_not_authenticate_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_a_pre_existing_credentials_does_not_authenticate_test.dart
deleted file mode 100644
index f1ee88a..0000000
--- a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_pre_existing_credentials_does_not_authenticate_test.dart
+++ /dev/null
@@ -1,32 +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.
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('with a pre-existing credentials.json does not authenticate', () {
- d.validPackage.create();
-
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
- confirmPublish(pub);
-
- server.handle('GET', '/api/packages/versions/new', (request) {
- expect(
- request.headers,
- containsPair('authorization', 'Bearer access token'));
-
- return new shelf.Response(200);
- });
-
- pub.kill();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_server_rejected_refresh_token_authenticates_again_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_a_server_rejected_refresh_token_authenticates_again_test.dart
deleted file mode 100644
index f613ebc..0000000
--- a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_server_rejected_refresh_token_authenticates_again_test.dart
+++ /dev/null
@@ -1,59 +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.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- // Regression test for issue 8849.
- integration(
- 'with a server-rejected refresh token, authenticates again and '
- 'saves credentials.json',
- () {
- d.validPackage.create();
-
- var server = new ScheduledServer();
- d.credentialsFile(
- server,
- 'access token',
- refreshToken: 'bad refresh token',
- expiration: new DateTime.now().subtract(new Duration(hours: 1))).create();
-
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- server.handle('POST', '/token', (request) {
- return drainStream(request.read()).then((_) {
- return new shelf.Response(400, body: JSON.encode({
- "error": "invalid_request"
- }), headers: {
- 'content-type': 'application/json'
- });
- });
- });
-
- pub.stdout.expect(startsWith('Uploading...'));
- authorizePub(pub, server, 'new access token');
-
- server.handle('GET', '/api/packages/versions/new', (request) {
- expect(
- request.headers,
- containsPair('authorization', 'Bearer new access token'));
-
- return new shelf.Response(200);
- });
-
- pub.kill();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_refreshes_and_saves_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_refreshes_and_saves_test.dart
deleted file mode 100644
index 82b7c4a5..0000000
--- a/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_refreshes_and_saves_test.dart
+++ /dev/null
@@ -1,62 +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.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'with an expired credentials.json, refreshes and saves the '
- 'refreshed access token to credentials.json',
- () {
- d.validPackage.create();
-
- var server = new ScheduledServer();
- d.credentialsFile(
- server,
- 'access token',
- refreshToken: 'refresh token',
- expiration: new DateTime.now().subtract(new Duration(hours: 1))).create();
-
- var pub = startPublish(server);
- confirmPublish(pub);
-
- server.handle('POST', '/token', (request) {
- return request.readAsString().then((body) {
- expect(
- body,
- matches(new RegExp(r'(^|&)refresh_token=refresh\+token(&|$)')));
-
- return new shelf.Response.ok(JSON.encode({
- "access_token": "new access token",
- "token_type": "bearer"
- }), headers: {
- 'content-type': 'application/json'
- });
- });
- });
-
- server.handle('GET', '/api/packages/versions/new', (request) {
- expect(
- request.headers,
- containsPair('authorization', 'Bearer new access token'));
-
- return new shelf.Response(200);
- });
-
- pub.shouldExit();
-
- d.credentialsFile(
- server,
- 'new access token',
- refreshToken: 'refresh token').validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_without_a_refresh_token_authenticates_again_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_without_a_refresh_token_authenticates_again_test.dart
deleted file mode 100644
index 4dabe89..0000000
--- a/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_without_a_refresh_token_authenticates_again_test.dart
+++ /dev/null
@@ -1,49 +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.
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- 'with an expired credentials.json without a refresh token, '
- 'authenticates again and saves credentials.json',
- () {
- d.validPackage.create();
-
- var server = new ScheduledServer();
- d.credentialsFile(
- server,
- 'access token',
- expiration: new DateTime.now().subtract(new Duration(hours: 1))).create();
-
- var pub = startPublish(server);
- confirmPublish(pub);
-
- pub.stderr.expect(
- "Pub's authorization to upload packages has expired and "
- "can't be automatically refreshed.");
- authorizePub(pub, server, "new access token");
-
- server.handle('GET', '/api/packages/versions/new', (request) {
- expect(
- request.headers,
- containsPair('authorization', 'Bearer new access token'));
-
- return new shelf.Response(200);
- });
-
- // After we give pub an invalid response, it should crash. We wait for it to
- // do so rather than killing it so it'll write out the credentials file.
- pub.shouldExit(1);
-
- d.credentialsFile(server, 'new access token').validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_no_credentials_authenticates_and_saves_credentials_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_no_credentials_authenticates_and_saves_credentials_test.dart
deleted file mode 100644
index a6a6551..0000000
--- a/sdk/lib/_internal/pub_generated/test/oauth2/with_no_credentials_authenticates_and_saves_credentials_test.dart
+++ /dev/null
@@ -1,39 +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.
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- 'with no credentials.json, authenticates and saves ' 'credentials.json',
- () {
- d.validPackage.create();
-
- var server = new ScheduledServer();
- var pub = startPublish(server);
- confirmPublish(pub);
- authorizePub(pub, server);
-
- server.handle('GET', '/api/packages/versions/new', (request) {
- expect(
- request.headers,
- containsPair('authorization', 'Bearer access token'));
-
- return new shelf.Response(200);
- });
-
- // After we give pub an invalid response, it should crash. We wait for it to
- // do so rather than killing it so it'll write out the credentials file.
- pub.shouldExit(1);
-
- d.credentialsFile(server, 'access token').validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_server_rejected_credentials_authenticates_again_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_server_rejected_credentials_authenticates_again_test.dart
deleted file mode 100644
index 75b6abb..0000000
--- a/sdk/lib/_internal/pub_generated/test/oauth2/with_server_rejected_credentials_authenticates_again_test.dart
+++ /dev/null
@@ -1,42 +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.
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'with server-rejected credentials, authenticates again and saves '
- 'credentials.json',
- () {
- d.validPackage.create();
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPublish(server);
-
- confirmPublish(pub);
-
- server.handle('GET', '/api/packages/versions/new', (request) {
- return new shelf.Response(401, body: JSON.encode({
- 'error': {
- 'message': 'your token sucks'
- }
- }), headers: {
- 'www-authenticate': 'Bearer error="invalid_token",'
- ' error_description="your token sucks"'
- });
- });
-
- pub.stderr.expect('OAuth2 authorization failed (your token sucks).');
- pub.stdout.expect(startsWith('Uploading...'));
- pub.kill();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/package_list_files_test.dart b/sdk/lib/_internal/pub_generated/test/package_list_files_test.dart
deleted file mode 100644
index 7d48927..0000000
--- a/sdk/lib/_internal/pub_generated/test/package_list_files_test.dart
+++ /dev/null
@@ -1,258 +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 packages_list_files_test;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../lib/src/entrypoint.dart';
-import '../lib/src/io.dart';
-import '../lib/src/system_cache.dart';
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-String root;
-Entrypoint entrypoint;
-
-main() {
- initConfig();
-
- group('not in a git repo', () {
- setUp(() {
- d.appDir().create();
- scheduleEntrypoint();
- });
-
-
- integration('lists files recursively', () {
- d.dir(
- appPath,
- [
- d.file('file1.txt', 'contents'),
- d.file('file2.txt', 'contents'),
- d.dir(
- 'subdir',
- [
- d.file('subfile1.txt', 'subcontents'),
- d.file('subfile2.txt', 'subcontents')])]).create();
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(),
- unorderedEquals(
- [
- path.join(root, 'pubspec.yaml'),
- path.join(root, 'file1.txt'),
- path.join(root, 'file2.txt'),
- path.join(root, 'subdir', 'subfile1.txt'),
- path.join(root, 'subdir', 'subfile2.txt')]));
- });
- });
-
- commonTests();
- });
-
- group('with git', () {
- setUp(() {
- ensureGit();
- d.git(appPath, [d.appPubspec()]).create();
- scheduleEntrypoint();
- });
-
- integration("includes files that are or aren't checked in", () {
- d.dir(
- appPath,
- [
- d.file('file1.txt', 'contents'),
- d.file('file2.txt', 'contents'),
- d.dir(
- 'subdir',
- [
- d.file('subfile1.txt', 'subcontents'),
- d.file('subfile2.txt', 'subcontents')])]).create();
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(),
- unorderedEquals(
- [
- path.join(root, 'pubspec.yaml'),
- path.join(root, 'file1.txt'),
- path.join(root, 'file2.txt'),
- path.join(root, 'subdir', 'subfile1.txt'),
- path.join(root, 'subdir', 'subfile2.txt')]));
- });
- });
-
- integration("ignores files that are gitignored if desired", () {
- d.dir(
- appPath,
- [
- d.file('.gitignore', '*.txt'),
- d.file('file1.txt', 'contents'),
- d.file('file2.text', 'contents'),
- d.dir(
- 'subdir',
- [
- d.file('subfile1.txt', 'subcontents'),
- d.file('subfile2.text', 'subcontents')])]).create();
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(useGitIgnore: true),
- unorderedEquals(
- [
- path.join(root, 'pubspec.yaml'),
- path.join(root, '.gitignore'),
- path.join(root, 'file2.text'),
- path.join(root, 'subdir', 'subfile2.text')]));
- });
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(),
- unorderedEquals(
- [
- path.join(root, 'pubspec.yaml'),
- path.join(root, 'file1.txt'),
- path.join(root, 'file2.text'),
- path.join(root, 'subdir', 'subfile1.txt'),
- path.join(root, 'subdir', 'subfile2.text')]));
- });
- });
-
- commonTests();
- });
-}
-
-void scheduleEntrypoint() {
- schedule(() {
- root = path.join(sandboxDir, appPath);
- entrypoint =
- new Entrypoint(root, new SystemCache.withSources(rootDir: root));
- }, 'initializing entrypoint');
-
- currentSchedule.onComplete.schedule(() {
- entrypoint = null;
- }, 'nulling entrypoint');
-}
-
-void commonTests() {
- integration('ignores broken symlinks', () {
- // Windows requires us to symlink to a directory that actually exists.
- d.dir(appPath, [d.dir('target')]).create();
- scheduleSymlink(path.join(appPath, 'target'), path.join(appPath, 'link'));
- schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'target')));
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(),
- equals([path.join(root, 'pubspec.yaml')]));
- });
- });
-
- integration('ignores pubspec.lock files', () {
- d.dir(
- appPath,
- [d.file('pubspec.lock'), d.dir('subdir', [d.file('pubspec.lock')])]).create();
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(),
- equals([path.join(root, 'pubspec.yaml')]));
- });
- });
-
- integration('ignores packages directories', () {
- d.dir(
- appPath,
- [
- d.dir('packages', [d.file('file.txt', 'contents')]),
- d.dir(
- 'subdir',
- [d.dir('packages', [d.file('subfile.txt', 'subcontents')]),])]).create();
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(),
- equals([path.join(root, 'pubspec.yaml')]));
- });
- });
-
- integration('allows pubspec.lock directories', () {
- d.dir(
- appPath,
- [d.dir('pubspec.lock', [d.file('file.txt', 'contents'),])]).create();
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(),
- unorderedEquals(
- [
- path.join(root, 'pubspec.yaml'),
- path.join(root, 'pubspec.lock', 'file.txt')]));
- });
- });
-
- group('and "beneath"', () {
- integration('only lists files beneath the given root', () {
- d.dir(
- appPath,
- [
- d.file('file1.txt', 'contents'),
- d.file('file2.txt', 'contents'),
- d.dir(
- 'subdir',
- [
- d.file('subfile1.txt', 'subcontents'),
- d.file('subfile2.txt', 'subcontents'),
- d.dir(
- 'subsubdir',
- [
- d.file('subsubfile1.txt', 'subsubcontents'),
- d.file('subsubfile2.txt', 'subsubcontents'),])])]).create();
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(beneath: path.join(root, 'subdir')),
- unorderedEquals(
- [
- path.join(root, 'subdir', 'subfile1.txt'),
- path.join(root, 'subdir', 'subfile2.txt'),
- path.join(root, 'subdir', 'subsubdir', 'subsubfile1.txt'),
- path.join(root, 'subdir', 'subsubdir', 'subsubfile2.txt')]));
- });
- });
-
- integration("doesn't care if the root is blacklisted", () {
- d.dir(
- appPath,
- [
- d.file('file1.txt', 'contents'),
- d.file('file2.txt', 'contents'),
- d.dir(
- 'packages',
- [
- d.file('subfile1.txt', 'subcontents'),
- d.file('subfile2.txt', 'subcontents'),
- d.dir(
- 'subsubdir',
- [
- d.file('subsubfile1.txt', 'subsubcontents'),
- d.file('subsubfile2.txt', 'subsubcontents')])])]).create();
-
- schedule(() {
- expect(
- entrypoint.root.listFiles(beneath: path.join(root, 'packages')),
- unorderedEquals(
- [
- path.join(root, 'packages', 'subfile1.txt'),
- path.join(root, 'packages', 'subfile2.txt'),
- path.join(root, 'packages', 'subsubdir', 'subsubfile1.txt'),
- path.join(root, 'packages', 'subsubdir', 'subsubfile2.txt')]));
- });
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/preprocess_test.dart b/sdk/lib/_internal/pub_generated/test/preprocess_test.dart
deleted file mode 100644
index 0cd4ead..0000000
--- a/sdk/lib/_internal/pub_generated/test/preprocess_test.dart
+++ /dev/null
@@ -1,306 +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.
-
-library pub.test.preprocess_test;
-
-import 'package:pub_semver/pub_semver.dart';
-import 'package:unittest/unittest.dart';
-
-import '../lib/src/preprocess.dart';
-import 'test_pub.dart';
-
-main() {
- initConfig();
-
- test("does nothing on a file without preprocessor directives", () {
- var text = '''
-some text
-// normal comment
-// #
- //# not beginning of line
-''';
-
- expect(_preprocess(text), equals(text));
- });
-
- test("allows bare insert directive", () {
- expect(_preprocess('//> foo'), equals('foo'));
- });
-
- test("allows empty insert directive", () {
- expect(_preprocess('''
-//> foo
-//>
-//> bar
-'''), equals('foo\n\nbar\n'));
- });
-
- group("if", () {
- group("with a version range", () {
- test("removes sections with non-matching versions", () {
- expect(_preprocess('''
-before
-//# if barback <1.0.0
-inside
-//# end
-after
-'''), equals('''
-before
-after
-'''));
- });
-
- test("doesn't insert section with non-matching versions", () {
- expect(_preprocess('''
-before
-//# if barback <1.0.0
-//> inside
-//# end
-after
-'''), equals('''
-before
-after
-'''));
- });
-
- test("doesn't remove sections with matching versions", () {
- expect(_preprocess('''
-before
-//# if barback >1.0.0
-inside
-//# end
-after
-'''), equals('''
-before
-inside
-after
-'''));
- });
-
- test("inserts sections with matching versions", () {
- expect(_preprocess('''
-before
-//# if barback >1.0.0
-//> inside
-//# end
-after
-'''), equals('''
-before
-inside
-after
-'''));
- });
-
- test("allows multi-element version ranges", () {
- expect(_preprocess('''
-before
-//# if barback >=1.0.0 <2.0.0
-inside 1
-//# end
-//# if barback >=0.9.0 <1.0.0
-inside 2
-//# end
-after
-'''), equals('''
-before
-inside 1
-after
-'''));
- });
- });
-
- group("with a package name", () {
- test("removes sections for a nonexistent package", () {
- expect(_preprocess('''
-before
-//# if fblthp
-inside
-//# end
-after
-'''), equals('''
-before
-after
-'''));
- });
-
- test("doesn't insert sections for a nonexistent package", () {
- expect(_preprocess('''
-before
-//# if fblthp
-//> inside
-//# end
-after
-'''), equals('''
-before
-after
-'''));
- });
-
- test("doesn't remove sections with an existent package", () {
- expect(_preprocess('''
-before
-//# if barback
-inside
-//# end
-after
-'''), equals('''
-before
-inside
-after
-'''));
- });
-
- test("inserts sections with an existent package", () {
- expect(_preprocess('''
-before
-//# if barback
-//> inside
-//# end
-after
-'''), equals('''
-before
-inside
-after
-'''));
- });
- });
- });
-
- group("else", () {
- test("removes non-matching sections", () {
- expect(_preprocess('''
-before
-//# if barback >1.0.0
-inside 1
-//# else
-inside 2
-//# end
-after
-'''), equals('''
-before
-inside 1
-after
-'''));
- });
-
- test("doesn't insert non-matching sections", () {
- expect(_preprocess('''
-before
-//# if barback >1.0.0
-inside 1
-//# else
-//> inside 2
-//# end
-after
-'''), equals('''
-before
-inside 1
-after
-'''));
- });
-
- test("doesn't remove matching sections", () {
- expect(_preprocess('''
-before
-//# if barback <1.0.0
-inside 1
-//# else
-inside 2
-//# end
-after
-'''), equals('''
-before
-inside 2
-after
-'''));
- });
-
- test("inserts matching sections", () {
- expect(_preprocess('''
-before
-//# if barback <1.0.0
-inside 1
-//# else
-//> inside 2
-//# end
-after
-'''), equals('''
-before
-inside 2
-after
-'''));
- });
- });
-
- group("errors", () {
- test("disallows unknown statements", () {
- expect(() => _preprocess('//# foo bar\n//# end'), throwsFormatException);
- });
-
- test("disallows insert directive without space", () {
- expect(() => _preprocess('//>foo'), throwsFormatException);
- });
-
- group("if", () {
- test("disallows if with no arguments", () {
- expect(() => _preprocess('//# if\n//# end'), throwsFormatException);
- });
-
- test("disallows if with no package", () {
- expect(
- () => _preprocess('//# if <=1.0.0\n//# end'),
- throwsFormatException);
- });
-
- test("disallows invalid version constraint", () {
- expect(
- () => _preprocess('//# if barback >=1.0\n//# end'),
- throwsFormatException);
- });
-
- test("disallows dangling end", () {
- expect(() => _preprocess('//# end'), throwsFormatException);
- });
-
- test("disallows if without end", () {
- expect(
- () => _preprocess('//# if barback >=1.0.0'),
- throwsFormatException);
- });
-
- test("disallows nested if", () {
- expect(() => _preprocess('''
-//# if barback >=1.0.0
-//# if barback >= 1.5.0
-//# end
-//# end
-'''), throwsFormatException);
- });
- });
-
- group("else", () {
- test("disallows else without if", () {
- expect(() => _preprocess('//# else\n//# end'), throwsFormatException);
- });
-
- test("disallows else without end", () {
- expect(
- () => _preprocess('//# if barback >=1.0.0\n//# else'),
- throwsFormatException);
- });
-
- test("disallows else with an argument", () {
- expect(() => _preprocess('''
-//# if barback >=1.0.0
-//# else barback <0.5.0
-//# end
-'''), throwsFormatException);
- });
- });
- });
-}
-
-String _preprocess(String input) => preprocess(input, {
- 'barback': new Version.parse("1.2.3")
-}, 'source/url');
diff --git a/sdk/lib/_internal/pub_generated/test/pub_get_and_upgrade_test.dart b/sdk/lib/_internal/pub_generated/test/pub_get_and_upgrade_test.dart
deleted file mode 100644
index c4ff0e9..0000000
--- a/sdk/lib/_internal/pub_generated/test/pub_get_and_upgrade_test.dart
+++ /dev/null
@@ -1,155 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../lib/src/exit_codes.dart' as exit_codes;
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- group('requires', () {
- integration('a pubspec', () {
- d.dir(appPath, []).create();
-
- pubCommand(
- command,
- error: new RegExp(
- r'Could not find a file named "pubspec.yaml" ' r'in "[^\n]*"\.'));
- });
-
- integration('a pubspec with a "name" key', () {
- d.dir(appPath, [d.pubspec({
- "dependencies": {
- "foo": null
- }
- })]).create();
-
- pubCommand(
- command,
- error: contains('Missing the required "name" field.'),
- exitCode: exit_codes.DATA);
- });
- });
-
- integration('adds itself to the packages', () {
- // The symlink should use the name in the pubspec, not the name of the
- // directory.
- d.dir(appPath, [d.pubspec({
- "name": "myapp_name"
- }), d.libDir('myapp_name')]).create();
-
- pubCommand(command);
-
- d.dir(
- packagesPath,
- [
- d.dir(
- "myapp_name",
- [d.file('myapp_name.dart', 'main() => "myapp_name";')])]).validate();
- });
-
- integration(
- 'does not adds itself to the packages if it has no "lib" ' 'directory',
- () {
- // The symlink should use the name in the pubspec, not the name of the
- // directory.
- d.dir(appPath, [d.pubspec({
- "name": "myapp_name"
- }),]).create();
-
- pubCommand(command);
-
- d.dir(packagesPath, [d.nothing("myapp_name")]).validate();
- });
-
- integration(
- 'does not add a package if it does not have a "lib" ' 'directory',
- () {
- // Using a path source, but this should be true of all sources.
- d.dir('foo', [d.libPubspec('foo', '0.0.0-not.used')]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubCommand(command);
-
- d.packagesDir({
- "foo": null
- }).validate();
- });
-
- integration('reports a solver failure', () {
- // myapp depends on foo and bar which both depend on baz with mismatched
- // descriptions.
- d.dir('deps', [d.dir('foo', [d.pubspec({
- "name": "foo",
- "dependencies": {
- "baz": {
- "path": "../baz1"
- }
- }
- })]), d.dir('bar', [d.pubspec({
- "name": "bar",
- "dependencies": {
- "baz": {
- "path": "../baz2"
- }
- }
- })]),
- d.dir('baz1', [d.libPubspec('baz', '0.0.0')]),
- d.dir('baz2', [d.libPubspec('baz', '0.0.0')])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../deps/foo"
- },
- "bar": {
- "path": "../deps/bar"
- }
- })]).create();
-
- pubCommand(
- command,
- error: new RegExp("^Incompatible dependencies on baz:\n"));
- });
-
- integration('does not allow a dependency on itself', () {
- d.dir(appPath, [d.appPubspec({
- "myapp": {
- "path": "."
- }
- })]).create();
-
- pubCommand(
- command,
- error: contains('A package may not list itself as a dependency.'),
- exitCode: exit_codes.DATA);
- });
-
- integration('does not allow a dev dependency on itself', () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dev_dependencies": {
- "myapp": {
- "path": "."
- }
- }
- })]).create();
-
- pubCommand(
- command,
- error: contains('A package may not list itself as a dependency.'),
- exitCode: exit_codes.DATA);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/pub_test.dart b/sdk/lib/_internal/pub_generated/test/pub_test.dart
deleted file mode 100644
index d664fa7..0000000
--- a/sdk/lib/_internal/pub_generated/test/pub_test.dart
+++ /dev/null
@@ -1,57 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../lib/src/exit_codes.dart' as exit_codes;
-import 'test_pub.dart';
-
-main() {
- initConfig();
-
- integration('running pub with no command displays usage', () {
- schedulePub(args: [], output: """
- Pub is a package manager for Dart.
-
- Usage: pub <command> [arguments]
-
- Global options:
- -h, --help Print this usage information.
- --version Print pub version.
- --[no-]trace Print debugging information when an error occurs.
- --verbosity Control output verbosity.
-
- [all] Show all output including internal tracing messages.
- [io] Also show IO operations.
- [normal] Show errors, warnings, and user messages.
- [solver] Show steps during version resolution.
-
- -v, --verbose Shortcut for "--verbosity=all".
-
- Available commands:
- build Apply transformers to build a package.
- cache Work with the system cache.
- deps Print package dependencies.
- downgrade Downgrade the current package's dependencies to oldest versions.
- get Get the current package's dependencies.
- global Work with global packages.
- help Display help information for pub.
- publish Publish the current package to pub.dartlang.org.
- run Run an executable from a package.
- serve Run a local web development server.
- upgrade Upgrade the current package's dependencies to latest versions.
- uploader Manage uploaders for a package on pub.dartlang.org.
- version Print pub version.
-
- Run "pub help <command>" for more information about a command.
- See http://dartlang.org/tools/pub for detailed documentation.
- """);
- });
-
- integration('running pub with just --version displays version', () {
- schedulePub(args: ['--version'], output: 'Pub 0.1.2+3');
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/pub_uploader_test.dart b/sdk/lib/_internal/pub_generated/test/pub_uploader_test.dart
deleted file mode 100644
index 1047ede..0000000
--- a/sdk/lib/_internal/pub_generated/test/pub_uploader_test.dart
+++ /dev/null
@@ -1,195 +0,0 @@
-// Copyright (c) 2013, 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 pub_uploader_test;
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:shelf/shelf.dart' as shelf;
-
-import '../lib/src/exit_codes.dart' as exit_codes;
-import '../lib/src/utils.dart';
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-final USAGE_STRING = '''
-Manage uploaders for a package on pub.dartlang.org.
-
-Usage: pub uploader [options] {add/remove} <email>
--h, --help Print this usage information.
- --server The package server on which the package is hosted.
- (defaults to "https://pub.dartlang.org")
-
- --package The package whose uploaders will be modified.
- (defaults to the current package)
-
-Run "pub help" to see global options.
-See http://dartlang.org/tools/pub/cmd/pub-uploader.html for detailed documentation.
-''';
-
-ScheduledProcess startPubUploader(ScheduledServer server, List<String> args) {
- var tokenEndpoint =
- server.url.then((url) => url.resolve('/token').toString());
- args = flatten(['uploader', '--server', tokenEndpoint, args]);
- return startPub(args: args, tokenEndpoint: tokenEndpoint);
-}
-
-main() {
- initConfig();
- group('displays usage', () {
- integration('when run with no arguments', () {
- schedulePub(
- args: ['uploader'],
- output: USAGE_STRING,
- exitCode: exit_codes.USAGE);
- });
-
- integration('when run with only a command', () {
- schedulePub(
- args: ['uploader', 'add'],
- output: USAGE_STRING,
- exitCode: exit_codes.USAGE);
- });
-
- integration('when run with an invalid command', () {
- schedulePub(
- args: ['uploader', 'foo', 'email'],
- output: USAGE_STRING,
- exitCode: exit_codes.USAGE);
- });
- });
-
- integration('adds an uploader', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPubUploader(server, ['--package', 'pkg', 'add', 'email']);
-
- server.handle('POST', '/api/packages/pkg/uploaders', (request) {
- return request.readAsString().then((body) {
- expect(body, equals('email=email'));
-
- return new shelf.Response.ok(JSON.encode({
- 'success': {
- 'message': 'Good job!'
- }
- }), headers: {
- 'content-type': 'application/json'
- });
- });
- });
-
- pub.stdout.expect('Good job!');
- pub.shouldExit(exit_codes.SUCCESS);
- });
-
- integration('removes an uploader', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPubUploader(server, ['--package', 'pkg', 'remove', 'email']);
-
- server.handle('DELETE', '/api/packages/pkg/uploaders/email', (request) {
- return new shelf.Response.ok(JSON.encode({
- 'success': {
- 'message': 'Good job!'
- }
- }), headers: {
- 'content-type': 'application/json'
- });
- });
-
- pub.stdout.expect('Good job!');
- pub.shouldExit(exit_codes.SUCCESS);
- });
-
- integration('defaults to the current package', () {
- d.validPackage.create();
-
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPubUploader(server, ['add', 'email']);
-
- server.handle('POST', '/api/packages/test_pkg/uploaders', (request) {
- return new shelf.Response.ok(JSON.encode({
- 'success': {
- 'message': 'Good job!'
- }
- }), headers: {
- 'content-type': 'application/json'
- });
- });
-
- pub.stdout.expect('Good job!');
- pub.shouldExit(exit_codes.SUCCESS);
- });
-
- integration('add provides an error', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPubUploader(server, ['--package', 'pkg', 'add', 'email']);
-
- server.handle('POST', '/api/packages/pkg/uploaders', (request) {
- return new shelf.Response(400, body: JSON.encode({
- 'error': {
- 'message': 'Bad job!'
- }
- }), headers: {
- 'content-type': 'application/json'
- });
- });
-
- pub.stderr.expect('Bad job!');
- pub.shouldExit(1);
- });
-
- integration('remove provides an error', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub =
- startPubUploader(server, ['--package', 'pkg', 'remove', 'e/mail']);
-
- server.handle('DELETE', '/api/packages/pkg/uploaders/e%2Fmail', (request) {
- return new shelf.Response(400, body: JSON.encode({
- 'error': {
- 'message': 'Bad job!'
- }
- }), headers: {
- 'content-type': 'application/json'
- });
- });
-
- pub.stderr.expect('Bad job!');
- pub.shouldExit(1);
- });
-
- integration('add provides invalid JSON', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPubUploader(server, ['--package', 'pkg', 'add', 'email']);
-
- server.handle(
- 'POST',
- '/api/packages/pkg/uploaders',
- (request) => new shelf.Response.ok("{not json"));
-
- pub.stderr.expect(emitsLines('Invalid server response:\n' '{not json'));
- pub.shouldExit(1);
- });
-
- integration('remove provides invalid JSON', () {
- var server = new ScheduledServer();
- d.credentialsFile(server, 'access token').create();
- var pub = startPubUploader(server, ['--package', 'pkg', 'remove', 'email']);
-
- server.handle(
- 'DELETE',
- '/api/packages/pkg/uploaders/email',
- (request) => new shelf.Response.ok("{not json"));
-
- pub.stderr.expect(emitsLines('Invalid server response:\n' '{not json'));
- pub.shouldExit(1);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/pubspec_test.dart
deleted file mode 100644
index 1418bf9..0000000
--- a/sdk/lib/_internal/pub_generated/test/pubspec_test.dart
+++ /dev/null
@@ -1,558 +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 pubspec_test;
-
-import 'dart:async';
-
-import 'package:pub_semver/pub_semver.dart';
-import 'package:unittest/unittest.dart';
-
-import '../lib/src/package.dart';
-import '../lib/src/pubspec.dart';
-import '../lib/src/source.dart';
-import '../lib/src/source/path.dart';
-import '../lib/src/source_registry.dart';
-import 'test_pub.dart';
-
-class MockSource extends Source {
- final String name = "mock";
-
- Future<Pubspec> doDescribe(PackageId id) =>
- throw new UnsupportedError("Cannot describe mock packages.");
-
- Future get(PackageId id, String symlink) =>
- throw new UnsupportedError("Cannot get a mock package.");
-
- Future<String> getDirectory(PackageId id) =>
- throw new UnsupportedError("Cannot get the directory for mock packages.");
-
- dynamic parseDescription(String filePath, description, {bool fromLockFile:
- false}) {
- if (description != 'ok') throw new FormatException('Bad');
- return description;
- }
-
- bool descriptionsEqual(description1, description2) =>
- description1 == description2;
-
- String packageName(description) => 'foo';
-}
-
-main() {
- initConfig();
- group('parse()', () {
- var sources = new SourceRegistry();
- sources.register(new MockSource());
- sources.register(new PathSource());
-
- var throwsPubspecException =
- throwsA(new isInstanceOf<PubspecException>('PubspecException'));
-
- expectPubspecException(String contents, fn(Pubspec pubspec),
- [String expectedContains]) {
- var expectation = throwsPubspecException;
- if (expectedContains != null) {
- expectation = throwsA(
- allOf(
- new isInstanceOf<PubspecException>('PubspecException'),
- predicate((error) => error.message.contains(expectedContains))));
- }
-
- var pubspec = new Pubspec.parse(contents, sources);
- expect(() => fn(pubspec), expectation);
- }
-
- test("doesn't eagerly throw an error for an invalid field", () {
- // Shouldn't throw an error.
- new Pubspec.parse('version: not a semver', sources);
- });
-
- test(
- "eagerly throws an error if the pubspec name doesn't match the "
- "expected name",
- () {
- expect(
- () => new Pubspec.parse("name: foo", sources, expectedName: 'bar'),
- throwsPubspecException);
- });
-
- test(
- "eagerly throws an error if the pubspec doesn't have a name and an "
- "expected name is passed",
- () {
- expect(
- () => new Pubspec.parse("{}", sources, expectedName: 'bar'),
- throwsPubspecException);
- });
-
- test("allows a version constraint for dependencies", () {
- var pubspec = new Pubspec.parse('''
-dependencies:
- foo:
- mock: ok
- version: ">=1.2.3 <3.4.5"
-''', sources);
-
- var foo = pubspec.dependencies[0];
- expect(foo.name, equals('foo'));
- expect(foo.constraint.allows(new Version(1, 2, 3)), isTrue);
- expect(foo.constraint.allows(new Version(1, 2, 5)), isTrue);
- expect(foo.constraint.allows(new Version(3, 4, 5)), isFalse);
- });
-
- test("allows an empty dependencies map", () {
- var pubspec = new Pubspec.parse('''
-dependencies:
-''', sources);
-
- expect(pubspec.dependencies, isEmpty);
- });
-
- test("allows a version constraint for dev dependencies", () {
- var pubspec = new Pubspec.parse('''
-dev_dependencies:
- foo:
- mock: ok
- version: ">=1.2.3 <3.4.5"
-''', sources);
-
- var foo = pubspec.devDependencies[0];
- expect(foo.name, equals('foo'));
- expect(foo.constraint.allows(new Version(1, 2, 3)), isTrue);
- expect(foo.constraint.allows(new Version(1, 2, 5)), isTrue);
- expect(foo.constraint.allows(new Version(3, 4, 5)), isFalse);
- });
-
- test("allows an empty dev dependencies map", () {
- var pubspec = new Pubspec.parse('''
-dev_dependencies:
-''', sources);
-
- expect(pubspec.devDependencies, isEmpty);
- });
-
- test("allows a version constraint for dependency overrides", () {
- var pubspec = new Pubspec.parse('''
-dependency_overrides:
- foo:
- mock: ok
- version: ">=1.2.3 <3.4.5"
-''', sources);
-
- var foo = pubspec.dependencyOverrides[0];
- expect(foo.name, equals('foo'));
- expect(foo.constraint.allows(new Version(1, 2, 3)), isTrue);
- expect(foo.constraint.allows(new Version(1, 2, 5)), isTrue);
- expect(foo.constraint.allows(new Version(3, 4, 5)), isFalse);
- });
-
- test("allows an empty dependency overrides map", () {
- var pubspec = new Pubspec.parse('''
-dependency_overrides:
-''', sources);
-
- expect(pubspec.dependencyOverrides, isEmpty);
- });
-
- test("allows an unknown source", () {
- var pubspec = new Pubspec.parse('''
-dependencies:
- foo:
- unknown: blah
-''', sources);
-
- var foo = pubspec.dependencies[0];
- expect(foo.name, equals('foo'));
- expect(foo.source, equals('unknown'));
- });
-
- test("throws if a package is in dependencies and dev_dependencies", () {
- expectPubspecException('''
-dependencies:
- foo:
- mock: ok
-dev_dependencies:
- foo:
- mock: ok
-''', (pubspec) {
- // This check only triggers if both [dependencies] and [devDependencies]
- // are accessed.
- pubspec.dependencies;
- pubspec.devDependencies;
- });
- });
-
- test("throws if it dependes on itself", () {
- expectPubspecException('''
-name: myapp
-dependencies:
- myapp:
- mock: ok
-''', (pubspec) => pubspec.dependencies);
- });
-
- test("throws if it has a dev dependency on itself", () {
- expectPubspecException('''
-name: myapp
-dev_dependencies:
- myapp:
- mock: ok
-''', (pubspec) => pubspec.devDependencies);
- });
-
- test("throws if it has an override on itself", () {
- expectPubspecException('''
-name: myapp
-dependency_overrides:
- myapp:
- mock: ok
-''', (pubspec) => pubspec.dependencyOverrides);
- });
-
- test("throws if the description isn't valid", () {
- expectPubspecException('''
-dependencies:
- foo:
- mock: bad
-''', (pubspec) => pubspec.dependencies);
- });
-
- test("throws if dependency version is not a string", () {
- expectPubspecException('''
-dependencies:
- foo:
- mock: ok
- version: 1.2
-''', (pubspec) => pubspec.dependencies);
- });
-
- test("throws if version is not a version constraint", () {
- expectPubspecException('''
-dependencies:
- foo:
- mock: ok
- version: not constraint
-''', (pubspec) => pubspec.dependencies);
- });
-
- test("throws if 'name' is not a string", () {
- expectPubspecException(
- 'name: [not, a, string]',
- (pubspec) => pubspec.name);
- });
-
- test("throws if version is not a string", () {
- expectPubspecException(
- 'version: [2, 0, 0]',
- (pubspec) => pubspec.version,
- '"version" field must be a string');
- });
-
- test("throws if version is malformed (looking like a double)", () {
- expectPubspecException(
- 'version: 2.1',
- (pubspec) => pubspec.version,
- '"version" field must have three numeric components: major, minor, '
- 'and patch. Instead of "2.1", consider "2.1.0"');
- });
-
- test("throws if version is malformed (looking like an int)", () {
- expectPubspecException(
- 'version: 2',
- (pubspec) => pubspec.version,
- '"version" field must have three numeric components: major, minor, '
- 'and patch. Instead of "2", consider "2.0.0"');
- });
-
- test("throws if version is not a version", () {
- expectPubspecException(
- 'version: not version',
- (pubspec) => pubspec.version);
- });
-
- test("throws if transformers isn't a list", () {
- expectPubspecException(
- 'transformers: "not list"',
- (pubspec) => pubspec.transformers,
- '"transformers" field must be a list');
- });
-
- test("throws if a transformer isn't a string or map", () {
- expectPubspecException(
- 'transformers: [12]',
- (pubspec) => pubspec.transformers,
- 'A transformer must be a string or map.');
- });
-
- test("throws if a transformer's configuration isn't a map", () {
- expectPubspecException(
- 'transformers: [{pkg: 12}]',
- (pubspec) => pubspec.transformers,
- "A transformer's configuration must be a map.");
- });
-
- test(
- "throws if a transformer's configuration contains an unknown "
- "reserved key at the top level",
- () {
- expectPubspecException('''
-name: pkg
-transformers: [{pkg: {\$key: "value"}}]''',
- (pubspec) => pubspec.transformers,
- 'Invalid transformer config: Unknown reserved field.');
- });
-
- test(
- "doesn't throw if a transformer's configuration contains a "
- "non-top-level key beginning with a dollar sign",
- () {
- var pubspec = new Pubspec.parse('''
-name: pkg
-transformers:
-- pkg: {outer: {\$inner: value}}
-''', sources);
-
- var pkg = pubspec.transformers[0].single;
- expect(pkg.configuration["outer"]["\$inner"], equals("value"));
- });
-
- test("throws if the \$include value is not a string or list", () {
- expectPubspecException('''
-name: pkg
-transformers:
-- pkg: {\$include: 123}''',
- (pubspec) => pubspec.transformers,
- 'Invalid transformer config: "\$include" field must be a string or ' 'list.');
- });
-
- test("throws if the \$include list contains a non-string", () {
- expectPubspecException('''
-name: pkg
-transformers:
-- pkg: {\$include: ["ok", 123, "alright", null]}''',
- (pubspec) => pubspec.transformers,
- 'Invalid transformer config: "\$include" field may contain only ' 'strings.');
- });
-
- test("throws if the \$exclude value is not a string or list", () {
- expectPubspecException('''
-name: pkg
-transformers:
-- pkg: {\$exclude: 123}''',
- (pubspec) => pubspec.transformers,
- 'Invalid transformer config: "\$exclude" field must be a string or ' 'list.');
- });
-
- test("throws if the \$exclude list contains a non-string", () {
- expectPubspecException('''
-name: pkg
-transformers:
-- pkg: {\$exclude: ["ok", 123, "alright", null]}''',
- (pubspec) => pubspec.transformers,
- 'Invalid transformer config: "\$exclude" field may contain only ' 'strings.');
- });
-
- test("throws if a transformer is not from a dependency", () {
- expectPubspecException('''
-name: pkg
-transformers: [foo]
-''', (pubspec) => pubspec.transformers, '"foo" is not a dependency.');
- });
-
- test("allows a transformer from a normal dependency", () {
- var pubspec = new Pubspec.parse('''
-name: pkg
-dependencies:
- foo:
- mock: ok
-transformers:
-- foo''', sources);
-
- expect(pubspec.transformers[0].single.id.package, equals("foo"));
- });
-
- test("allows a transformer from a dev dependency", () {
- var pubspec = new Pubspec.parse('''
-name: pkg
-dev_dependencies:
- foo:
- mock: ok
-transformers:
-- foo''', sources);
-
- expect(pubspec.transformers[0].single.id.package, equals("foo"));
- });
-
- test("allows a transformer from a dependency override", () {
- var pubspec = new Pubspec.parse('''
-name: pkg
-dependency_overrides:
- foo:
- mock: ok
-transformers:
-- foo''', sources);
-
- expect(pubspec.transformers[0].single.id.package, equals("foo"));
- });
-
- test("allows comment-only files", () {
- var pubspec = new Pubspec.parse('''
-# No external dependencies yet
-# Including for completeness
-# ...and hoping the spec expands to include details about author, version, etc
-# See http://www.dartlang.org/docs/pub-package-manager/ for details
-''', sources);
- expect(pubspec.version, equals(Version.none));
- expect(pubspec.dependencies, isEmpty);
- });
-
- test("throws a useful error for unresolvable path dependencies", () {
- expectPubspecException('''
-name: pkg
-dependencies:
- from_path: {path: non_local_path}
-''',
- (pubspec) => pubspec.dependencies,
- '"non_local_path" is a relative path, but this isn\'t a local ' 'pubspec.');
- });
-
- group("environment", () {
- test("defaults to any SDK constraint if environment is omitted", () {
- var pubspec = new Pubspec.parse('', sources);
- expect(pubspec.environment.sdkVersion, equals(VersionConstraint.any));
- });
-
- test("allows an empty environment map", () {
- var pubspec = new Pubspec.parse('''
-environment:
-''', sources);
- expect(pubspec.environment.sdkVersion, equals(VersionConstraint.any));
- });
-
- test("throws if the environment value isn't a map", () {
- expectPubspecException(
- 'environment: []',
- (pubspec) => pubspec.environment);
- });
-
- test("allows a version constraint for the sdk", () {
- var pubspec = new Pubspec.parse('''
-environment:
- sdk: ">=1.2.3 <2.3.4"
-''', sources);
- expect(
- pubspec.environment.sdkVersion,
- equals(new VersionConstraint.parse(">=1.2.3 <2.3.4")));
- });
-
- test("throws if the sdk isn't a string", () {
- expectPubspecException(
- 'environment: {sdk: []}',
- (pubspec) => pubspec.environment);
- expectPubspecException(
- 'environment: {sdk: 1.0}',
- (pubspec) => pubspec.environment);
- });
-
- test("throws if the sdk isn't a valid version constraint", () {
- expectPubspecException(
- 'environment: {sdk: "oopies"}',
- (pubspec) => pubspec.environment);
- });
- });
-
- group("publishTo", () {
- test("defaults to null if omitted", () {
- var pubspec = new Pubspec.parse('', sources);
- expect(pubspec.publishTo, isNull);
- });
-
- test("throws if not a string", () {
- expectPubspecException(
- 'publish_to: 123',
- (pubspec) => pubspec.publishTo);
- });
-
- test("allows a URL", () {
- var pubspec = new Pubspec.parse('''
-publish_to: http://example.com
-''', sources);
- expect(pubspec.publishTo, equals("http://example.com"));
- });
-
- test("allows none", () {
- var pubspec = new Pubspec.parse('''
-publish_to: none
-''', sources);
- expect(pubspec.publishTo, equals("none"));
- });
-
- test("throws on other strings", () {
- expectPubspecException(
- 'publish_to: http://bad.url:not-port',
- (pubspec) => pubspec.publishTo);
- });
- });
-
- group("executables", () {
- test("defaults to an empty map if omitted", () {
- var pubspec = new Pubspec.parse('', sources);
- expect(pubspec.executables, isEmpty);
- });
-
- test("allows simple names for keys and most characters in values", () {
- var pubspec = new Pubspec.parse('''
-executables:
- abcDEF-123_: "abc DEF-123._"
-''', sources);
- expect(pubspec.executables['abcDEF-123_'], equals('abc DEF-123._'));
- });
-
- test("throws if not a map", () {
- expectPubspecException(
- 'executables: not map',
- (pubspec) => pubspec.executables);
- });
-
- test("throws if key is not a string", () {
- expectPubspecException(
- 'executables: {123: value}',
- (pubspec) => pubspec.executables);
- });
-
- test("throws if a key isn't a simple name", () {
- expectPubspecException(
- 'executables: {funny/name: ok}',
- (pubspec) => pubspec.executables);
- });
-
- test("throws if a value is not a string", () {
- expectPubspecException(
- 'executables: {command: 123}',
- (pubspec) => pubspec.executables);
- });
-
- test("throws if a value contains a path separator", () {
- expectPubspecException(
- 'executables: {command: funny_name/part}',
- (pubspec) => pubspec.executables);
- });
-
- test("throws if a value contains a windows path separator", () {
- expectPubspecException(
- r'executables: {command: funny_name\part}',
- (pubspec) => pubspec.executables);
- });
-
- test("uses the key if the value is null", () {
- var pubspec = new Pubspec.parse('''
-executables:
- command:
-''', sources);
- expect(pubspec.executables['command'], equals('command'));
- });
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/real_version_test.dart b/sdk/lib/_internal/pub_generated/test/real_version_test.dart
deleted file mode 100644
index f9a6074..0000000
--- a/sdk/lib/_internal/pub_generated/test/real_version_test.dart
+++ /dev/null
@@ -1,41 +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 pub_tests;
-
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../lib/src/exit_codes.dart' as exit_codes;
-import '../lib/src/sdk.dart' as sdk;
-import 'test_pub.dart';
-
-main() {
- initConfig();
-
- // This test is a bit funny.
- //
- // Pub parses the "version" file that gets generated and shipped with the SDK.
- // We want to make sure that the actual version file that gets created is
- // also one pub can parse. If this test fails, it means the version file's
- // format has changed in a way pub didn't expect.
- //
- // Note that this test expects to be invoked from a Dart executable that is
- // in the built SDK's "bin" directory. Note also that this invokes pub from
- // the built SDK directory, and not the live pub code directly in the repo.
- integration('parse the real SDK "version" file', () {
- // Get the path to the pub binary in the SDK.
- var pubPath = path.join(
- sdk.rootDirectory,
- 'bin',
- Platform.operatingSystem == "windows" ? "pub.bat" : "pub");
-
- var pub = new ScheduledProcess.start(pubPath, ['version']);
- pub.stdout.expect(startsWith("Pub"));
- pub.shouldExit(exit_codes.SUCCESS);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/allows_dart_extension_test.dart b/sdk/lib/_internal/pub_generated/test/run/allows_dart_extension_test.dart
deleted file mode 100644
index 90d1d8a..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/allows_dart_extension_test.dart
+++ /dev/null
@@ -1,30 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SCRIPT = """
-import 'dart:io';
-
-main() {
- stdout.writeln("stdout output");
- stderr.writeln("stderr output");
- exitCode = 123;
-}
-""";
-
-main() {
- initConfig();
- integration('allows a ".dart" extension on the argument', () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("bin", [d.file("script.dart", SCRIPT)])]).create();
-
- var pub = pubRun(args: ["script.dart"]);
- pub.stdout.expect("stdout output");
- pub.stderr.expect("stderr output");
- pub.shouldExit(123);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/app_can_read_from_stdin_test.dart b/sdk/lib/_internal/pub_generated/test/run/app_can_read_from_stdin_test.dart
deleted file mode 100644
index 9eab3a7..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/app_can_read_from_stdin_test.dart
+++ /dev/null
@@ -1,38 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SCRIPT = """
-import 'dart:io';
-
-main() {
- print("started");
- var line1 = stdin.readLineSync();
- print("between");
- var line2 = stdin.readLineSync();
- print(line1);
- print(line2);
-}
-""";
-
-main() {
- initConfig();
- integration('the spawned application can read from stdin', () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("bin", [d.file("script.dart", SCRIPT)])]).create();
-
- var pub = pubRun(args: ["script"]);
-
- pub.stdout.expect("started");
- pub.writeLine("first");
- pub.stdout.expect("between");
- pub.writeLine("second");
- pub.stdout.expect("first");
- pub.stdout.expect("second");
- pub.shouldExit(0);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/displays_transformer_logs_test.dart b/sdk/lib/_internal/pub_generated/test/run/displays_transformer_logs_test.dart
deleted file mode 100644
index 05af330..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/displays_transformer_logs_test.dart
+++ /dev/null
@@ -1,85 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SCRIPT = """
-import "package:myapp/lib.dart";
-main() {
- callLib();
-}
-""";
-
-const LIB = """
-callLib() {
- print("lib");
-}
-""";
-
-// Make it lazy so that "lib.dart" isn't transformed until after the process
-// is started. Otherwise, since this tranformer modifies .dart files, it will
-// be run while the transformers themselves are loading during pub run's
-// startup.
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class LoggingTransformer extends Transformer implements LazyTransformer {
- LoggingTransformer.asPlugin();
-
- String get allowedExtensions => '.dart';
-
- void apply(Transform transform) {
- transform.logger.info('\${transform.primaryInput.id}.');
- transform.logger.warning('\${transform.primaryInput.id}.');
- }
-
- void declareOutputs(DeclaringTransform transform) {
- // TODO(rnystrom): Remove this when #19408 is fixed.
- transform.declareOutput(transform.primaryId);
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration('displays transformer log messages', () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.file("lib.dart", LIB),
- d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("bin", [d.file("script.dart", SCRIPT)])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = pubRun(args: ["script"]);
-
- // Note that the info log is only displayed here because the test
- // harness runs pub in verbose mode. By default, only the warning would
- // be shown.
- pub.stdout.expect("[Info from Logging]:");
- pub.stdout.expect("myapp|bin/script.dart.");
-
- pub.stderr.expect("[Warning from Logging]:");
- pub.stderr.expect("myapp|bin/script.dart.");
-
- pub.stdout.expect("[Info from Logging]:");
- pub.stdout.expect("myapp|lib/lib.dart.");
-
- pub.stderr.expect("[Warning from Logging]:");
- pub.stderr.expect("myapp|lib/lib.dart.");
-
- pub.stdout.expect("lib");
- pub.shouldExit();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/does_not_run_on_transformer_error_test.dart b/sdk/lib/_internal/pub_generated/test/run/does_not_run_on_transformer_error_test.dart
deleted file mode 100644
index 7d3bb78..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/does_not_run_on_transformer_error_test.dart
+++ /dev/null
@@ -1,54 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SCRIPT = """
-main() {
- print("should not get here!");
-}
-""";
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class FailingTransformer extends Transformer {
- FailingTransformer.asPlugin();
-
- String get allowedExtensions => '.dart';
-
- void apply(Transform transform) {
- // Don't run on the transformer itself.
- if (transform.primaryInput.id.path.startsWith("lib")) return;
- transform.logger.error('\${transform.primaryInput.id}.');
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration('does not run if a transformer has an error', () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("bin", [d.file("script.dart", SCRIPT)])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = pubRun(args: ["script"]);
-
- pub.stderr.expect("[Error from Failing]:");
- pub.stderr.expect("myapp|bin/script.dart.");
-
- // Note: no output from the script.
- pub.shouldExit();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/doesnt_load_an_unnecessary_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/run/doesnt_load_an_unnecessary_transformer_test.dart
deleted file mode 100644
index fefb202..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/doesnt_load_an_unnecessary_transformer_test.dart
+++ /dev/null
@@ -1,54 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class BrokenTransformer extends Transformer {
- RewriteTransformer.asPlugin() {
- throw 'This transformer is broken!';
- }
-
- String get allowedExtensions => '.txt';
-
- void apply(Transform transform) {}
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("doesn't load an unnecessary transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- r"$include": "lib/myapp.dart"
- }
- }]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", ""),
- d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("bin", [d.file("hi.dart", "void main() => print('Hello!');")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- // This shouldn't load the transformer, since it doesn't transform
- // anything that the entrypoint imports. If it did load the transformer,
- // we'd know since it would throw an exception.
- var pub = pubRun(args: ["hi"]);
- pub.stdout.expect("Hello!");
- pub.shouldExit();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/errors_if_no_executable_is_given_test.dart b/sdk/lib/_internal/pub_generated/test/run/errors_if_no_executable_is_given_test.dart
deleted file mode 100644
index 0ba4378..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/errors_if_no_executable_is_given_test.dart
+++ /dev/null
@@ -1,25 +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 '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('Errors if the executable does not exist.', () {
- d.dir(appPath, [d.appPubspec()]).create();
-
- schedulePub(args: ["run"], error: """
-Must specify an executable to run.
-
-Usage: pub run <executable> [args...]
--h, --help Print this usage information.
- --mode Mode to run transformers in.
- (defaults to "release" for dependencies, "debug" for entrypoint)
-
-Run "pub help" to see global options.
-""", exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/errors_if_only_transitive_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/errors_if_only_transitive_dependency_test.dart
deleted file mode 100644
index 4e95e04..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/errors_if_only_transitive_dependency_test.dart
+++ /dev/null
@@ -1,37 +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 '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('Errors if the script is in a non-immediate dependency.', () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("bar.dart", "main() => print('foobar');")])]).create();
-
- d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: {
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- d.dir(appPath, [d.appPubspec({
- "bar": {
- "path": "../bar"
- }
- })]).create();
-
- pubGet();
-
- var pub = pubRun(args: ["foo:script"]);
- pub.stderr.expect('Package "foo" is not an immediate dependency.');
- pub.stderr.expect('Cannot run executables in transitive dependencies.');
- pub.shouldExit(exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/errors_if_path_in_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/errors_if_path_in_dependency_test.dart
deleted file mode 100644
index 15cf766..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/errors_if_path_in_dependency_test.dart
+++ /dev/null
@@ -1,33 +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 '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- 'Errors if the executable is in a subdirectory in a ' 'dependency.',
- () {
- d.dir("foo", [d.libPubspec("foo", "1.0.0")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- schedulePub(args: ["run", "foo:sub/dir"], error: """
-Cannot run an executable in a subdirectory of a dependency.
-
-Usage: pub run <executable> [args...]
--h, --help Print this usage information.
- --mode Mode to run transformers in.
- (defaults to "release" for dependencies, "debug" for entrypoint)
-
-Run "pub help" to see global options.
-""", exitCode: exit_codes.USAGE);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/ignores_explicit_dart2js_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/run/ignores_explicit_dart2js_transformer_test.dart
deleted file mode 100644
index e3286e7..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/ignores_explicit_dart2js_transformer_test.dart
+++ /dev/null
@@ -1,21 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("doesn't choke on an explicit dart2js transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [r"$dart2js"]
- }),
- d.dir("bin", [d.file("script.dart", "main() => print('Hello!');")])]).create();
-
- var pub = pubRun(args: ["script"]);
- pub.stdout.expect("Hello!");
- pub.shouldExit(0);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/includes_parent_directories_of_entrypoint_test.dart b/sdk/lib/_internal/pub_generated/test/run/includes_parent_directories_of_entrypoint_test.dart
deleted file mode 100644
index d00de270..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/includes_parent_directories_of_entrypoint_test.dart
+++ /dev/null
@@ -1,41 +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:path/path.dart' as path;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SCRIPT = r"""
-import '../../a.dart';
-import '../b.dart';
-main() {
- print("$a $b");
-}
-""";
-
-main() {
- initConfig();
- integration(
- 'allows assets in parent directories of the entrypoint to be' 'accessed',
- () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "tool",
- [
- d.file("a.dart", "var a = 'a';"),
- d.dir(
- "a",
- [
- d.file("b.dart", "var b = 'b';"),
- d.dir("b", [d.file("app.dart", SCRIPT)])])])]).create();
-
- var pub = pubRun(args: [path.join("tool", "a", "b", "app")]);
- pub.stdout.expect("a b");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/mode_test.dart b/sdk/lib/_internal/pub_generated/test/run/mode_test.dart
deleted file mode 100644
index cff439f..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/mode_test.dart
+++ /dev/null
@@ -1,92 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class DartTransformer extends Transformer {
- final BarbackSettings _settings;
-
- DartTransformer.asPlugin(this._settings);
-
- String get allowedExtensions => '.in';
-
- void apply(Transform transform) {
- transform.addOutput(new Asset.fromString(
- new AssetId(transform.primaryInput.id.package, "bin/script.dart"),
- "void main() => print('\${_settings.mode.name}');"));
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration('runs a local script with customizable modes', () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [
- d.file("transformer.dart", TRANSFORMER),
- d.file("primary.in", "")])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- // By default it should run in debug mode.
- var pub = pubRun(args: ["script"]);
- pub.stdout.expect("debug");
- pub.shouldExit();
-
- // A custom mode should be specifiable.
- pub = pubRun(args: ["--mode", "custom-mode", "script"]);
- pub.stdout.expect("custom-mode");
- pub.shouldExit();
- });
-
- integration('runs a dependency script with customizable modes', () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.2.3",
- "transformers": ["foo/src/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [
- d.file("transformer.dart", TRANSFORMER),
- d.file("primary.in", "")])])]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo"
- }
- }).create();
-
- createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']);
-
- // By default it should run in release mode.
- var pub = pubRun(args: ["foo:script"]);
- pub.stdout.expect("release");
- pub.shouldExit();
-
- // A custom mode should be specifiable.
- pub = pubRun(args: ["--mode", "custom-mode", "foo:script"]);
- pub.stdout.expect("custom-mode");
- pub.shouldExit();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/nonexistent_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/nonexistent_dependency_test.dart
deleted file mode 100644
index f57ce49..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/nonexistent_dependency_test.dart
+++ /dev/null
@@ -1,19 +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 '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('Errors if the script is in an unknown package.', () {
- d.dir(appPath, [d.appPubspec()]).create();
-
- var pub = pubRun(args: ["foo:script"]);
- pub.stderr.expect(
- 'Could not find package "foo". Did you forget to add a ' 'dependency?');
- pub.shouldExit(exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_in_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_in_dependency_test.dart
deleted file mode 100644
index eaeb26c..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_in_dependency_test.dart
+++ /dev/null
@@ -1,29 +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:path/path.dart' as p;
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('Errors if the script in a dependency does not exist.', () {
- d.dir("foo", [d.libPubspec("foo", "1.0.0")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubGet();
-
- var pub = pubRun(args: ["foo:script"]);
- pub.stderr.expect(
- "Could not find ${p.join("bin", "script.dart")} in package foo.");
- pub.shouldExit(exit_codes.NO_INPUT);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_test.dart b/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_test.dart
deleted file mode 100644
index 5018572..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_test.dart
+++ /dev/null
@@ -1,20 +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:path/path.dart' as p;
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('Errors if the script does not exist.', () {
- d.dir(appPath, [d.appPubspec()]).create();
-
- var pub = pubRun(args: ["script"]);
- pub.stderr.expect("Could not find ${p.join("bin", "script.dart")}.");
- pub.shouldExit(exit_codes.NO_INPUT);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/passes_along_arguments_test.dart b/sdk/lib/_internal/pub_generated/test/run/passes_along_arguments_test.dart
deleted file mode 100644
index f6fe879..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/passes_along_arguments_test.dart
+++ /dev/null
@@ -1,28 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SCRIPT = """
-main(List<String> args) {
- print(args.join(" "));
-}
-""";
-
-main() {
- initConfig();
- integration('passes arguments to the spawned script', () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("bin", [d.file("args.dart", SCRIPT)])]).create();
-
- // Use some args that would trip up pub's arg parser to ensure that it
- // isn't trying to look at them.
- var pub = pubRun(args: ["args", "--verbose", "-m", "--", "help"]);
-
- pub.stdout.expect("--verbose -m -- help");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_a_generated_script_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_a_generated_script_test.dart
deleted file mode 100644
index 4794c37..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/runs_a_generated_script_test.dart
+++ /dev/null
@@ -1,51 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class DartTransformer extends Transformer {
- DartTransformer.asPlugin();
-
- String get allowedExtensions => '.in';
-
- void apply(Transform transform) {
- transform.addOutput(new Asset.fromString(
- new AssetId("myapp", "bin/script.dart"),
- "void main() => print('generated');"));
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration('runs a script generated from scratch by a transformer', () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [
- d.file("transformer.dart", TRANSFORMER),
- d.file("primary.in", "")])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = pubRun(args: ["script"]);
-
- pub.stdout.expect("generated");
- pub.shouldExit();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_app_in_directory_in_entrypoint_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_app_in_directory_in_entrypoint_test.dart
deleted file mode 100644
index 488bff6..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/runs_app_in_directory_in_entrypoint_test.dart
+++ /dev/null
@@ -1,31 +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:path/path.dart' as path;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('runs a Dart application in the entrypoint package', () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "tool",
- [
- d.file("app.dart", "main() => print('tool');"),
- d.dir("sub", [d.file("app.dart", "main() => print('sub');")])])]).create();
-
- var pub = pubRun(args: [path.join("tool", "app")]);
- pub.stdout.expect("tool");
- pub.shouldExit();
-
- pub = pubRun(args: [path.join("tool", "sub", "app")]);
- pub.stdout.expect("sub");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_app_in_entrypoint_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_app_in_entrypoint_test.dart
deleted file mode 100644
index f4c7a6b..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/runs_app_in_entrypoint_test.dart
+++ /dev/null
@@ -1,30 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SCRIPT = """
-import 'dart:io';
-
-main() {
- stdout.writeln("stdout output");
- stderr.writeln("stderr output");
- exitCode = 123;
-}
-""";
-
-main() {
- initConfig();
- integration('runs a Dart application in the entrypoint package', () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("bin", [d.file("script.dart", SCRIPT)])]).create();
-
- var pub = pubRun(args: ["script"]);
- pub.stdout.expect("stdout output");
- pub.stderr.expect("stderr output");
- pub.shouldExit(123);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dependency_test.dart
deleted file mode 100644
index 9a02aba..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dependency_test.dart
+++ /dev/null
@@ -1,29 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('runs a named Dart application in a dependency', () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("bar.dart", "main() => print('foobar');")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubGet();
-
- var pub = pubRun(args: ["foo:bar"]);
- pub.stdout.expect("foobar");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dev_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dev_dependency_test.dart
deleted file mode 100644
index 8bf4c87..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dev_dependency_test.dart
+++ /dev/null
@@ -1,32 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration('runs a named Dart application in a dev dependency', () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("bin", [d.file("bar.dart", "main() => print('foobar');")])]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dev_dependencies": {
- "foo": {
- "path": "../foo"
- }
- }
- })]).create();
-
- pubGet();
-
- var pub = pubRun(args: ["foo:bar"]);
- pub.stdout.expect("foobar");
- pub.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_the_script_in_checked_mode_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_the_script_in_checked_mode_test.dart
deleted file mode 100644
index 56c3ad4..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/runs_the_script_in_checked_mode_test.dart
+++ /dev/null
@@ -1,28 +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:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SCRIPT = """
-main() {
- int a = true;
-}
-""";
-
-main() {
- initConfig();
- integration('runs the script in checked mode by default', () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("bin", [d.file("script.dart", SCRIPT)])]).create();
-
- schedulePub(
- args: ["run", "script"],
- error: contains("'bool' is not a subtype of type 'int' of 'a'"),
- exitCode: 255);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_transformer_in_entrypoint_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_transformer_in_entrypoint_test.dart
deleted file mode 100644
index fc154a1..0000000
--- a/sdk/lib/_internal/pub_generated/test/run/runs_transformer_in_entrypoint_test.dart
+++ /dev/null
@@ -1,37 +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 '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const SCRIPT = """
-const TOKEN = "hi";
-main() {
- print(TOKEN);
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration('runs transformers in the entrypoint package', () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [d.dir("src", [d.file("transformer.dart", dartTransformer("transformed"))])]),
- d.dir("bin", [d.file("hi.dart", SCRIPT)])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = pubRun(args: ["hi"]);
-
- pub.stdout.expect("(hi, transformed)");
- pub.shouldExit();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/404_page_test.dart b/sdk/lib/_internal/pub_generated/test/serve/404_page_test.dart
deleted file mode 100644
index b8f3e9a..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/404_page_test.dart
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- setUp(() {
- d.dir(appPath, [d.appPubspec()]).create();
- });
-
- integration("the 404 page describes the missing asset", () {
- pubServe();
-
- scheduleRequest("packages/foo/missing.txt").then((response) {
- expect(response.statusCode, equals(404));
-
- // Should mention the asset that can't be found.
- expect(response.body, contains("foo"));
- expect(response.body, contains("missing.txt"));
- });
-
- endPubServe();
- });
-
- integration("the 404 page describes the error", () {
- pubServe();
-
- scheduleRequest("packages").then((response) {
- expect(response.statusCode, equals(404));
-
- // Should mention the asset that can't be found.
- expect(response.body, contains('"/packages"'));
- });
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/allows_arbitrary_modes_test.dart b/sdk/lib/_internal/pub_generated/test/serve/allows_arbitrary_modes_test.dart
deleted file mode 100644
index 6e48433..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/allows_arbitrary_modes_test.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class ModeTransformer extends Transformer {
- final BarbackSettings settings;
- ModeTransformer.asPlugin(this.settings);
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return new Future.value().then((_) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, settings.mode.toString()));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("allows user-defined mode names", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe(args: ["--mode", "depeche"]);
- requestShouldSucceed("foo.out", "depeche");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/defaults_to_debug_mode_test.dart b/sdk/lib/_internal/pub_generated/test/serve/defaults_to_debug_mode_test.dart
deleted file mode 100644
index 16b7de1..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/defaults_to_debug_mode_test.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class ModeTransformer extends Transformer {
- final BarbackSettings settings;
- ModeTransformer.asPlugin(this.settings);
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return new Future.value().then((_) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, settings.mode.toString()));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("defaults to debug mode", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "debug");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_crash_if_an_unused_dart_file_has_a_syntax_error_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_crash_if_an_unused_dart_file_has_a_syntax_error_test.dart
deleted file mode 100644
index dc2812d..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/does_not_crash_if_an_unused_dart_file_has_a_syntax_error_test.dart
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("doesn't crash if an unused .dart file has a syntax error", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [
- d.file("transformer.dart", REWRITE_TRANSFORMER),
- d.file("unused.dart", "(*&^#@")])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_a_dependency_is_removed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_a_dependency_is_removed_test.dart
deleted file mode 100644
index 25cb7e9..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_a_dependency_is_removed_test.dart
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("does not get if a dependency is removed", () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create();
-
- // Get "foo" into the lock file.
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
- pubGet();
-
- // Remove it from the pubspec.
- d.dir(appPath, [d.appPubspec()]).create();
-
- pubServe(shouldGetFirst: false);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_git_url_did_not_change_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_git_url_did_not_change_test.dart
deleted file mode 100644
index 5bf1869..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_git_url_did_not_change_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("does not get first if a git dependency's url is unchanged", () {
- d.git('foo.git', [d.libPubspec('foo', '1.0.0'), d.libDir("foo")]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
- pubServe(shouldGetFirst: false);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_matches_override_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_matches_override_test.dart
deleted file mode 100644
index 8dc2f4b..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_matches_override_test.dart
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- // This is a regression test for https://dartbug.com/15180.
- initConfig();
- integration("does not get if the locked version matches the override", () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create();
-
- // Get "foo" into the lock file.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "any"
- },
- "dependency_overrides": {
- "foo": {
- "path": "../foo",
- "version": ">=0.0.1"
- }
- }
- })]).create();
- pubGet();
-
- pubServe(shouldGetFirst: false);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_version_matches_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_version_matches_test.dart
deleted file mode 100644
index 67c8c64..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_version_matches_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- "does not get if the locked version of a dependency is allowed "
- "by the pubspec's constraint",
- () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create();
-
- // Get "foo" into the lock file.
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo",
- "version": ">=0.0.1"
- },
- })]).create();
- pubGet();
-
- // Change the version.
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo",
- "version": "<2.0.0"
- },
- })]).create();
-
- pubServe(shouldGetFirst: false);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_dart_in_release_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_dart_in_release_test.dart
deleted file mode 100644
index 45418cf..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_dart_in_release_test.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("does not serve .dart files in release mode", () {
-
- d.dir(
- "foo",
- [d.libPubspec("foo", "0.0.1"), d.dir("lib", [d.file("foo.dart", """
- library foo;
- foo() => 'foo';
- """)])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }),
- d.dir("lib", [d.file("lib.dart", "lib() => print('hello');"),]),
- d.dir("web", [d.file("file.dart", """
- import 'package:foo/foo.dart';
- main() => print('hello');
- """),
- d.dir("sub", [d.file("sub.dart", "main() => 'foo';"),])])]).create();
-
- pubServe(shouldGetFirst: true, args: ["--mode", "release"]);
- requestShould404("file.dart");
- requestShould404("packages/myapp/lib.dart");
- requestShould404("packages/foo/foo.dart");
- requestShould404("sub/sub.dart");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_hidden_assets_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_hidden_assets_test.dart
deleted file mode 100644
index 26981c1..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_hidden_assets_test.dart
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("doesn't serve hidden assets", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.file(".outer.txt", "outer contents"),
- d.dir(".dir", [d.file("inner.txt", "inner contents"),])])]).create();
-
- pubServe();
- requestShould404(".outer.txt");
- requestShould404(".dir/inner.txt");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_watch_compiled_js_files_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_watch_compiled_js_files_test.dart
deleted file mode 100644
index 41b7568..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/does_not_watch_compiled_js_files_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("does not watch changes to compiled JS files in the package", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create();
-
- pubServe();
- waitForBuildSuccess();
- requestShouldSucceed("index.html", "body");
-
- d.dir(
- appPath,
- [
- d.dir(
- "web",
- [
- d.file('file.dart', 'void main() => print("hello");'),
- d.file("other.dart.js", "should be ignored"),
- d.file("other.dart.js.map", "should be ignored"),
- d.file("other.dart.precompiled.js", "should be ignored")])]).create();
-
- waitForBuildSuccess();
- requestShouldSucceed("file.dart", 'void main() => print("hello");');
- requestShould404("other.dart.js");
- requestShould404("other.dart.js.map");
- requestShould404("other.dart.precompiled.js");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_added_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_added_test.dart
deleted file mode 100644
index a7ea6a0..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_added_test.dart
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("gets first if a dependency is not in the lock file", () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create();
-
- // Create a lock file without "foo".
- d.dir(appPath, [d.appPubspec()]).create();
- pubGet();
-
- // Add it to the pubspec.
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_is_not_installed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_is_not_installed_test.dart
deleted file mode 100644
index ba72760..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_is_not_installed_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("gets first if a dependency is not installed", () {
- servePackages((builder) => builder.serve("foo", "1.2.3"));
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- // Run pub to get a lock file.
- pubGet();
-
- // Delete the system cache so it isn't installed any more.
- schedule(() => deleteEntry(path.join(sandboxDir, cachePath)));
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo 1.2.3";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_version_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_version_changed_test.dart
deleted file mode 100644
index 8a5b294..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_version_changed_test.dart
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- "gets first if a dependency's version doesn't match the one in "
- "the lock file",
- () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo",
- "version": "0.0.1"
- }
- }).create();
-
- pubGet();
-
- // Change the version in the pubspec and package.
- d.appDir({
- "foo": {
- "path": "../foo",
- "version": "0.0.2"
- }
- }).create();
-
- d.dir("foo", [d.libPubspec("foo", "0.0.2"), d.libDir("foo")]).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dev_dependency_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dev_dependency_changed_test.dart
deleted file mode 100644
index 69e8f66..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dev_dependency_changed_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:convert';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("gets first if a dev dependency has changed", () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create();
-
- // Create a pubspec with "foo" and a lock file without it.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dev_dependencies": {
- "foo": {
- "path": "../foo"
- }
- }
- }), d.file("pubspec.lock", JSON.encode({
- 'packages': {}
- }))]).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_ref_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_ref_changed_test.dart
deleted file mode 100644
index 2b43f9f..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_ref_changed_test.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- "gets first if a git dependency's ref doesn't match the one in "
- "the lock file",
- () {
- var repo =
- d.git('foo.git', [d.libDir('foo', 'before'), d.libPubspec('foo', '1.0.0')]);
- repo.create();
- var commit1 = repo.revParse('HEAD');
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'after'), d.libPubspec('foo', '1.0.0')]).commit();
-
- var commit2 = repo.revParse('HEAD');
-
- // Lock it to the ref of the first commit.
- d.appDir({
- "foo": {
- "git": {
- "url": "../foo.git",
- "ref": commit1
- }
- }
- }).create();
-
- pubGet();
-
- // Change the commit in the pubspec.
- d.appDir({
- "foo": {
- "git": {
- "url": "../foo.git",
- "ref": commit2
- }
- }
- }).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "after";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_url_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_url_changed_test.dart
deleted file mode 100644
index c41af7d..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_url_changed_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- "gets first if a git dependency's url doesn't match the one in "
- "the lock file",
- () {
- d.git(
- "foo-before.git",
- [d.libPubspec("foo", "1.0.0"), d.libDir("foo", "before")]).create();
-
- d.git(
- "foo-after.git",
- [d.libPubspec("foo", "1.0.0"), d.libDir("foo", "after")]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo-before.git"
- }
- }).create();
-
- pubGet();
-
- // Change the path in the pubspec.
- d.appDir({
- "foo": {
- "git": "../foo-after.git"
- }
- }).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "after";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_no_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_no_lockfile_test.dart
deleted file mode 100644
index a823db7..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_no_lockfile_test.dart
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("gets first if there is no lockfile", () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo"
- }
- }).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_path_dependency_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_path_dependency_changed_test.dart
deleted file mode 100644
index 156e18d..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_path_dependency_changed_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- "gets first if a path dependency's path doesn't match the one in "
- "the lock file",
- () {
- d.dir(
- "foo-before",
- [d.libPubspec("foo", "0.0.1"), d.libDir("foo", "before")]).create();
-
- d.dir(
- "foo-after",
- [d.libPubspec("foo", "0.0.1"), d.libDir("foo", "after")]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo-before"
- }
- }).create();
-
- pubGet();
-
- // Change the path in the pubspec.
- d.appDir({
- "foo": {
- "path": "../foo-after"
- }
- }).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "after";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_source_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_source_changed_test.dart
deleted file mode 100644
index f960ad6..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_source_changed_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:convert';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration(
- "gets first if a dependency's source doesn't match the one in " "the lock file",
- () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create();
-
- d.dir(appPath, [// A pubspec with a path source.
- d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }), // A lock file with the hosted source.
- d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'foo': {
- 'version': '0.0.0',
- 'source': 'hosted',
- 'description': 'foo'
- }
- }
- }))]).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_transitive_dependency_is_not_installed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_transitive_dependency_is_not_installed_test.dart
deleted file mode 100644
index 90c76ea..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_transitive_dependency_is_not_installed_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("gets first if a transitive dependency is not installed", () {
- servePackages((builder) => builder.serve("bar", "1.2.3"));
-
- d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: {
- "bar": "any"
- }), d.libDir("foo")]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo"
- }
- }).create();
-
- // Run pub to install everything.
- pubGet();
-
- // Delete the system cache so bar isn't installed any more.
- schedule(() => deleteEntry(path.join(sandboxDir, cachePath)));
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/bar/bar.dart", 'main() => "bar 1.2.3";');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/invalid_method_test.dart b/sdk/lib/_internal/pub_generated/test/serve/invalid_method_test.dart
deleted file mode 100644
index cccad88..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/invalid_method_test.dart
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("responds with a 405 for an invalid method", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "<body>"),])]).create();
-
- pubServe();
-
- postShould405("index.html");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/invalid_urls_test.dart b/sdk/lib/_internal/pub_generated/test/serve/invalid_urls_test.dart
deleted file mode 100644
index ece122e..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/invalid_urls_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("responds with a 404 on incomplete special URLs", () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }),
- d.dir(
- "lib",
- [// Make a file that maps to the special "packages" directory to ensure
- // it is *not* found.
- d.file("packages")]), d.dir("web", [d.file("packages")])]).create();
-
- pubGet();
- pubServe();
- requestShould404("packages");
- requestShould404("packages/");
- requestShould404("packages/myapp");
- requestShould404("packages/myapp/");
- requestShould404("packages/foo");
- requestShould404("packages/foo/");
- requestShould404("packages/unknown");
- requestShould404("packages/unknown/");
- endPubServe();
- });
-
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/missing_asset_test.dart b/sdk/lib/_internal/pub_generated/test/serve/missing_asset_test.dart
deleted file mode 100644
index 8bb69b0..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/missing_asset_test.dart
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("responds with a 404 for missing assets", () {
- d.dir(appPath, [d.appPubspec()]).create();
-
- pubServe();
- requestShould404("index.html");
- requestShould404("packages/myapp/nope.dart");
- requestShould404("dir/packages/myapp/nope.dart");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/missing_dependency_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/missing_dependency_file_test.dart
deleted file mode 100644
index 2fe60a4..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/missing_dependency_file_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("responds with a 404 for a missing files in dependencies", () {
- d.dir("foo", [d.libPubspec("foo", "0.0.1")]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubGet();
- pubServe();
- requestShould404("packages/foo/nope.dart");
- requestShould404("dir/packages/foo/nope.dart");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/missing_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/missing_file_test.dart
deleted file mode 100644
index 737fb34..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/missing_file_test.dart
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("responds with a 404 for missing source files", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("lib", [d.file("nope.dart", "nope")]),
- d.dir("web", [d.file("index.html", "<body>"),])]).create();
-
- // Start the server with the files present so that it creates barback
- // assets for them.
- pubServe();
-
- // Now delete them.
- schedule(() {
- deleteEntry(path.join(sandboxDir, appPath, "lib", "nope.dart"));
- deleteEntry(path.join(sandboxDir, appPath, "web", "index.html"));
- }, "delete files");
-
- // Now request them.
- // TODO(rnystrom): It's possible for these requests to happen quickly
- // enough that the file system hasn't notified for the deletions yet. If
- // that happens, we can probably just add a short delay here.
-
- requestShould404("index.html");
- requestShould404("packages/myapp/nope.dart");
- requestShould404("dir/packages/myapp/nope.dart");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/native_watch_added_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/native_watch_added_file_test.dart
deleted file mode 100644
index 7a25f5a..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/native_watch_added_file_test.dart
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-// TODO(nweiz): Default to testing the native watcher and add an explicit test
-// for the polling watcher when issue 14941 is fixed.
-
-main() {
- initConfig();
- integration(
- "picks up files added after serving started when using the " "native watcher",
- () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create();
-
- pubServe(args: ["--no-force-poll"]);
- waitForBuildSuccess();
- requestShouldSucceed("index.html", "body");
-
- d.dir(appPath, [d.dir("web", [d.file("other.html", "added")])]).create();
-
- waitForBuildSuccess();
- requestShouldSucceed("other.html", "added");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/native_watch_modified_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/native_watch_modified_file_test.dart
deleted file mode 100644
index 41a9eac..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/native_watch_modified_file_test.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-// TODO(nweiz): Default to testing the native watcher and add an explicit test
-// for the polling watcher when issue 14941 is fixed.
-
-main() {
- initConfig();
- integration(
- "watches modifications to files when using the native watcher",
- () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "before")])]).create();
-
- pubServe(args: ["--no-force-poll"]);
- requestShouldSucceed("index.html", "before");
-
- d.dir(appPath, [d.dir("web", [d.file("index.html", "after")])]).create();
-
- waitForBuildSuccess();
- requestShouldSucceed("index.html", "after");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/native_watch_removed_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/native_watch_removed_file_test.dart
deleted file mode 100644
index 8aef493..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/native_watch_removed_file_test.dart
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-// TODO(nweiz): Default to testing the native watcher and add an explicit test
-// for the polling watcher when issue 14941 is fixed.
-
-main() {
- initConfig();
- integration(
- "stop serving a file that is removed when using the native " "watcher",
- () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create();
-
- pubServe(args: ["--no-force-poll"]);
- requestShouldSucceed("index.html", "body");
-
- schedule(
- () => deleteEntry(path.join(sandboxDir, appPath, "web", "index.html")));
-
- waitForBuildSuccess();
- requestShould404("index.html");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/native_watch_replaced_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/native_watch_replaced_file_test.dart
deleted file mode 100644
index b257216..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/native_watch_replaced_file_test.dart
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:async';
-import 'dart:io';
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- // This is a regression test for http://dartbug.com/21402.
- initConfig();
- withBarbackVersions("any", () {
- integration(
- "picks up files replaced after serving started when using the "
- "native watcher",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir("web", [d.file("file.txt", "before"),]),
- d.file("other", "after")]).create();
-
- createLockFile("myapp", pkg: ["barback"]);
-
- pubServe(args: ["--no-force-poll"]);
- waitForBuildSuccess();
- requestShouldSucceed("file.out", "before.out");
-
- schedule(() {
- // Replace file.txt by renaming other on top of it.
- return new File(
- p.join(
- sandboxDir,
- appPath,
- "other")).rename(p.join(sandboxDir, appPath, "web", "file.txt"));
- });
-
- // Read the transformed file to ensure the change is actually noticed by
- // pub and not that we just get the new file contents piped through
- // without pub realizing they've changed.
- waitForBuildSuccess();
- requestShouldSucceed("file.out", "after.out");
-
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_lib_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_lib_test.dart
deleted file mode 100644
index 2204ff6..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_lib_test.dart
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("'packages' URLs look in the app's lib directory", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "lib",
- [
- d.file("lib.dart", "foo() => 'foo';"),
- d.dir("sub", [d.file("lib.dart", "bar() => 'bar';"),])])]).create();
-
- pubServe();
- requestShouldSucceed("packages/myapp/lib.dart", "foo() => 'foo';");
- requestShouldSucceed("packages/myapp/sub/lib.dart", "bar() => 'bar';");
-
- // "packages" can be in a subpath of the URL:
- requestShouldSucceed("foo/packages/myapp/lib.dart", "foo() => 'foo';");
- requestShouldSucceed("a/b/packages/myapp/sub/lib.dart", "bar() => 'bar';");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_web_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_web_test.dart
deleted file mode 100644
index e7661d43..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_web_test.dart
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("finds files in the app's web directory", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.file("index.html", "<body>"),
- d.file("file.dart", "main() => print('hello');"),
- d.dir(
- "sub",
- [
- d.file("file.html", "<body>in subdir</body>"),
- d.file("lib.dart", "main() => 'foo';"),])])]).create();
-
- pubServe();
- requestShouldSucceed("index.html", "<body>");
- requestShouldSucceed("file.dart", "main() => print('hello');");
- requestShouldSucceed("sub/file.html", "<body>in subdir</body>");
- requestShouldSucceed("sub/lib.dart", "main() => 'foo';");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/serve_from_dependency_lib_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serve_from_dependency_lib_test.dart
deleted file mode 100644
index 034e168..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/serve_from_dependency_lib_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("'packages' URLs look in the dependency's lib directory", () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "0.0.1"),
- d.dir(
- "lib",
- [
- d.file("lib.dart", "foo() => 'foo';"),
- d.dir("sub", [d.file("lib.dart", "bar() => 'bar';"),])])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- pubServe(shouldGetFirst: true);
- requestShouldSucceed("packages/foo/lib.dart", "foo() => 'foo';");
- requestShouldSucceed("packages/foo/sub/lib.dart", "bar() => 'bar';");
-
- // "packages" can be in a subpath of the URL:
- requestShouldSucceed("foo/packages/foo/lib.dart", "foo() => 'foo';");
- requestShouldSucceed("a/b/packages/foo/sub/lib.dart", "bar() => 'bar';");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/serves_file_with_space_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serves_file_with_space_test.dart
deleted file mode 100644
index d2421cf..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/serves_file_with_space_test.dart
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("serves a filename with a space", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.file("foo bar.txt", "outer contents"),
- d.dir("sub dir", [d.file("inner.txt", "inner contents"),])])]).create();
-
- pubServe();
- requestShouldSucceed("foo%20bar.txt", "outer contents");
- requestShouldSucceed("sub%20dir/inner.txt", "inner contents");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/serves_index_html_for_directories_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serves_index_html_for_directories_test.dart
deleted file mode 100644
index c02db48..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/serves_index_html_for_directories_test.dart
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("serves index.html for directories", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.file("index.html", "<body>super"),
- d.dir("sub", [d.file("index.html", "<body>sub")])])]).create();
-
- pubServe();
- requestShouldSucceed("", "<body>super");
- requestShouldSucceed("sub/", "<body>sub");
- requestShouldRedirect("sub", "/sub/");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/serves_web_and_test_dirs_by_default_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serves_web_and_test_dirs_by_default_test.dart
deleted file mode 100644
index a15c6cb..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/serves_web_and_test_dirs_by_default_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("serves web/ and test/ dirs by default", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("web", [d.file("foo", "contents")]),
- d.dir("test", [d.file("bar", "contents")]),
- d.dir("example", [d.file("baz", "contents")])]).create();
-
- pubServe();
- requestShouldSucceed("foo", "contents", root: "web");
- requestShouldSucceed("bar", "contents", root: "test");
- requestShould404("baz", root: "web");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/supports_cross_origin_header_test.dart b/sdk/lib/_internal/pub_generated/test/serve/supports_cross_origin_header_test.dart
deleted file mode 100644
index 9059393..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/supports_cross_origin_header_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("sends responses that allow cross-origin requests", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- pubServe();
- requestShouldSucceed(
- "index.html",
- "<body>",
- headers: containsPair("access-control-allow-origin", "*"));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_declaring_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_declaring_transformers_test.dart
deleted file mode 100644
index f14da0d..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_declaring_transformers_test.dart
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-const DECLARING_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class DeclaringRewriteTransformer extends Transformer
- implements DeclaringTransformer {
- DeclaringRewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.out';
-
- Future apply(Transform transform) {
- transform.logger.info('Rewriting \${transform.primaryInput.id}.');
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".final");
- transform.addOutput(new Asset.fromString(id, "\$contents.final"));
- });
- }
-
- Future declareOutputs(DeclaringTransform transform) {
- transform.declareOutput(transform.primaryId.changeExtension(".final"));
- return new Future.value();
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("supports a user-defined declaring transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/lazy", "myapp/src/declaring"]
- }),
- d.dir(
- "lib",
- [d.dir("src", [// Include a lazy transformer before the declaring transformer,
- // because otherwise its behavior is indistinguishable from a normal
- // transformer.
- d.file("lazy.dart", LAZY_TRANSFORMER),
- d.file("declaring.dart", DECLARING_TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- // The build should complete without either transformer logging anything.
- server.stdout.expect('Build completed successfully');
-
- requestShouldSucceed("foo.final", "foo.out.final");
- server.stdout.expect(
- emitsLines(
- '[Info from LazyRewrite]:\n' 'Rewriting myapp|web/foo.txt.\n'
- '[Info from DeclaringRewrite]:\n' 'Rewriting myapp|web/foo.out.'));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_lazy_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_lazy_transformers_test.dart
deleted file mode 100644
index 3c19427..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_lazy_transformers_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("supports a user-defined lazy transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", LAZY_TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- // The build should complete without the transformer logging anything.
- server.stdout.expect('Build completed successfully');
-
- requestShouldSucceed("foo.out", "foo.out");
- server.stdout.expect(
- emitsLines('[Info from LazyRewrite]:\n' 'Rewriting myapp|web/foo.txt.'));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/unknown_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/serve/unknown_dependency_test.dart
deleted file mode 100644
index daa3c44..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/unknown_dependency_test.dart
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("responds with a 404 unknown dependencies", () {
- d.dir(appPath, [d.appPubspec()]).create();
-
- pubServe();
- requestShould404("packages/foo/nope.dart");
- requestShould404("assets/foo/nope.png");
- requestShould404("dir/packages/foo/nope.dart");
- requestShould404("dir/assets/foo/nope.png");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/uses_appropriate_mime_types_test.dart b/sdk/lib/_internal/pub_generated/test/serve/uses_appropriate_mime_types_test.dart
deleted file mode 100644
index bef5217..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/uses_appropriate_mime_types_test.dart
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("uses appropriate mime types", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.file("index.html", "<body>"),
- d.file("file.dart", "main() => print('hello');"),
- d.file("file.js", "console.log('hello');"),
- d.file("file.css", "body {color: blue}")])]).create();
-
- pubServe();
- requestShouldSucceed(
- "index.html",
- anything,
- headers: containsPair('content-type', 'text/html'));
- requestShouldSucceed(
- "file.dart",
- anything,
- headers: containsPair('content-type', 'application/dart'));
- requestShouldSucceed(
- "file.js",
- anything,
- headers: containsPair('content-type', 'application/javascript'));
- requestShouldSucceed(
- "file.css",
- anything,
- headers: containsPair('content-type', 'text/css'));
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/utils.dart b/sdk/lib/_internal/pub_generated/test/serve/utils.dart
deleted file mode 100644
index a0ac7cc..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/utils.dart
+++ /dev/null
@@ -1,491 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:http/http.dart' as http;
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:stack_trace/stack_trace.dart';
-
-import '../../lib/src/utils.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-/// The pub process running "pub serve".
-ScheduledProcess _pubServer;
-
-/// The ephemeral port assign to the running admin server.
-int _adminPort;
-
-/// The ephemeral ports assigned to the running servers, associated with the
-/// directories they're serving.
-final _ports = new Map<String, int>();
-
-/// A completer that completes when the server has been started and the served
-/// ports are known.
-Completer _portsCompleter;
-
-/// The web socket connection to the running pub process, or `null` if no
-/// connection has been made.
-WebSocket _webSocket;
-Stream _webSocketBroadcastStream;
-
-/// The code for a transformer that renames ".txt" files to ".out" and adds a
-/// ".out" suffix.
-const REWRITE_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, "\$contents.out"));
- });
- }
-}
-""";
-
-/// The code for a lazy version of [REWRITE_TRANSFORMER].
-const LAZY_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class LazyRewriteTransformer extends Transformer implements LazyTransformer {
- LazyRewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- transform.logger.info('Rewriting \${transform.primaryInput.id}.');
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, "\$contents.out"));
- });
- }
-
- Future declareOutputs(DeclaringTransform transform) {
- transform.declareOutput(transform.primaryId.changeExtension(".out"));
- return new Future.value();
- }
-}
-""";
-
-/// The web socket error code for a directory not being served.
-const NOT_SERVED = 1;
-
-/// Returns the source code for a Dart library defining a Transformer that
-/// rewrites Dart files.
-///
-/// The transformer defines a constant named TOKEN whose value is [id]. When the
-/// transformer transforms another Dart file, it will look for a "TOKEN"
-/// constant definition there and modify it to include *this* transformer's
-/// TOKEN value as well.
-///
-/// If [import] is passed, it should be the name of a package that defines its
-/// own TOKEN constant. The primary library of that package will be imported
-/// here and its TOKEN value will be added to this library's.
-///
-/// This transformer takes one configuration field: "addition". This is
-/// concatenated to its TOKEN value before adding it to the output library.
-String dartTransformer(String id, {String import}) {
- if (import != null) {
- id = '$id imports \${$import.TOKEN}';
- import = 'import "package:$import/$import.dart" as $import;';
- } else {
- import = '';
- }
-
- return """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-$import
-
-import 'dart:io';
-
-const TOKEN = "$id";
-
-final _tokenRegExp = new RegExp(r'^const TOKEN = "(.*?)";\$', multiLine: true);
-
-class DartTransformer extends Transformer {
- final BarbackSettings _settings;
-
- DartTransformer.asPlugin(this._settings);
-
- String get allowedExtensions => '.dart';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- transform.addOutput(new Asset.fromString(transform.primaryInput.id,
- contents.replaceAllMapped(_tokenRegExp, (match) {
- var token = TOKEN;
- var addition = _settings.configuration["addition"];
- if (addition != null) token += addition;
- return 'const TOKEN = "(\${match[1]}, \$token)";';
- })));
- });
- }
-}
-""";
-}
-
-/// Schedules starting the `pub serve` process.
-///
-/// Unlike [pubServe], this doesn't determine the port number of the server, and
-/// so may be used to test for errors in the initialization process.
-///
-/// Returns the `pub serve` process.
-ScheduledProcess startPubServe({Iterable<String> args, bool createWebDir: true})
- {
- var pubArgs = ["serve", "--port=0", // Use port 0 to get an ephemeral port.
- "--force-poll", "--log-admin-url"];
-
- if (args != null) pubArgs.addAll(args);
-
- // Dart2js can take a long time to compile dart code, so we increase the
- // timeout to cope with that.
- currentSchedule.timeout *= 1.5;
-
- if (createWebDir) d.dir(appPath, [d.dir("web")]).create();
- return startPub(args: pubArgs);
-}
-
-/// Schedules starting the "pub serve" process and records its port number for
-/// future requests.
-///
-/// If [shouldGetFirst] is `true`, validates that pub get is run first.
-///
-/// If [createWebDir] is `true`, creates a `web/` directory if one doesn't exist
-/// so pub doesn't complain about having nothing to serve.
-///
-/// Returns the `pub serve` process.
-ScheduledProcess pubServe({bool shouldGetFirst: false, bool createWebDir: true,
- Iterable<String> args}) {
- _pubServer = startPubServe(args: args, createWebDir: createWebDir);
- _portsCompleter = new Completer();
-
- currentSchedule.onComplete.schedule(() {
- _portsCompleter = null;
- _ports.clear();
-
- if (_webSocket != null) {
- _webSocket.close();
- _webSocket = null;
- _webSocketBroadcastStream = null;
- }
- });
-
- if (shouldGetFirst) {
- _pubServer.stdout.expect(
- consumeThrough(
- anyOf(["Got dependencies!", matches(new RegExp(r"^Changed \d+ dependenc"))])));
- }
-
- _pubServer.stdout.expect(startsWith("Loading source assets..."));
- _pubServer.stdout.expect(consumeWhile(matches("Loading .* transformers...")));
-
- _pubServer.stdout.expect(predicate(_parseAdminPort));
-
- // The server should emit one or more ports.
- _pubServer.stdout.expect(
- consumeWhile(predicate(_parsePort, 'emits server url')));
- schedule(() {
- expect(_ports, isNot(isEmpty));
- _portsCompleter.complete();
- });
-
- return _pubServer;
-}
-
-/// The regular expression for parsing pub's output line describing the URL for
-/// the server.
-final _parsePortRegExp = new RegExp(r"([^ ]+) +on http://localhost:(\d+)");
-
-/// Parses the port number from the "Running admin server on localhost:1234"
-/// line printed by pub serve.
-bool _parseAdminPort(String line) {
- var match = _parsePortRegExp.firstMatch(line);
- if (match == null) return false;
- _adminPort = int.parse(match[2]);
- return true;
-}
-
-/// Parses the port number from the "Serving blah on localhost:1234" line
-/// printed by pub serve.
-bool _parsePort(String line) {
- var match = _parsePortRegExp.firstMatch(line);
- if (match == null) return false;
- _ports[match[1]] = int.parse(match[2]);
- return true;
-}
-
-void endPubServe() {
- _pubServer.kill();
-}
-
-/// Schedules an HTTP request to the running pub server with [urlPath] and
-/// invokes [callback] with the response.
-///
-/// [root] indicates which server should be accessed, and defaults to "web".
-Future<http.Response> scheduleRequest(String urlPath, {String root}) {
- return schedule(() {
- return http.get(_getServerUrlSync(root, urlPath));
- }, "request $urlPath");
-}
-
-/// Schedules an HTTP request to the running pub server with [urlPath] and
-/// verifies that it responds with a body that matches [expectation].
-///
-/// [expectation] may either be a [Matcher] or a string to match an exact body.
-/// [root] indicates which server should be accessed, and defaults to "web".
-/// [headers] may be either a [Matcher] or a map to match an exact headers map.
-void requestShouldSucceed(String urlPath, expectation, {String root, headers}) {
- scheduleRequest(urlPath, root: root).then((response) {
- expect(response.statusCode, equals(200));
- if (expectation != null) expect(response.body, expectation);
- if (headers != null) expect(response.headers, headers);
- });
-}
-
-/// Schedules an HTTP request to the running pub server with [urlPath] and
-/// verifies that it responds with a 404.
-///
-/// [root] indicates which server should be accessed, and defaults to "web".
-void requestShould404(String urlPath, {String root}) {
- scheduleRequest(urlPath, root: root).then((response) {
- expect(response.statusCode, equals(404));
- });
-}
-
-/// Schedules an HTTP request to the running pub server with [urlPath] and
-/// verifies that it responds with a redirect to the given [redirectTarget].
-///
-/// [redirectTarget] may be either a [Matcher] or a string to match an exact
-/// URL. [root] indicates which server should be accessed, and defaults to
-/// "web".
-void requestShouldRedirect(String urlPath, redirectTarget, {String root}) {
- schedule(() {
- var request =
- new http.Request("GET", Uri.parse(_getServerUrlSync(root, urlPath)));
- request.followRedirects = false;
- return request.send().then((response) {
- expect(response.statusCode ~/ 100, equals(3));
- expect(response.headers, containsPair('location', redirectTarget));
- });
- }, "request $urlPath");
-}
-
-/// Schedules an HTTP POST to the running pub server with [urlPath] and verifies
-/// that it responds with a 405.
-///
-/// [root] indicates which server should be accessed, and defaults to "web".
-void postShould405(String urlPath, {String root}) {
- schedule(() {
- return http.post(_getServerUrlSync(root, urlPath)).then((response) {
- expect(response.statusCode, equals(405));
- });
- }, "request $urlPath");
-}
-
-/// Schedules an HTTP request to the (theoretically) running pub server with
-/// [urlPath] and verifies that it cannot be connected to.
-///
-/// [root] indicates which server should be accessed, and defaults to "web".
-void requestShouldNotConnect(String urlPath, {String root}) {
- schedule(() {
- return expect(
- http.get(_getServerUrlSync(root, urlPath)),
- throwsA(new isInstanceOf<SocketException>()));
- }, "request $urlPath");
-}
-
-/// Reads lines from pub serve's stdout until it prints the build success
-/// message.
-///
-/// The schedule will not proceed until the output is found. If not found, it
-/// will eventually time out.
-void waitForBuildSuccess() =>
- _pubServer.stdout.expect(consumeThrough(contains("successfully")));
-
-/// Schedules opening a web socket connection to the currently running pub
-/// serve.
-Future _ensureWebSocket() {
- // Use the existing one if already connected.
- if (_webSocket != null) return new Future.value();
-
- // Server should already be running.
- expect(_pubServer, isNotNull);
- expect(_adminPort, isNotNull);
-
- return WebSocket.connect("ws://localhost:$_adminPort").then((socket) {
- _webSocket = socket;
- // TODO(rnystrom): Works around #13913.
- _webSocketBroadcastStream = _webSocket.map(JSON.decode).asBroadcastStream();
- });
-}
-
-/// Schedules closing the web socket connection to the currently-running pub
-/// serve.
-void closeWebSocket() {
- schedule(() {
- return _ensureWebSocket().then((_) => _webSocket.close()).then((_) => _webSocket =
- null);
- }, "closing web socket");
-}
-
-/// Sends a JSON RPC 2.0 request to the running pub serve's web socket
-/// connection.
-///
-/// This calls a method named [method] with the given [params] (or no
-/// parameters, if it's not passed). [params] may contain Futures, in which case
-/// this will wait until they've completed before sending the request.
-///
-/// This schedules the request, but doesn't block the schedule on the response.
-/// It returns the response as a [Future].
-Future<Map> webSocketRequest(String method, [Map params]) {
- var completer = new Completer();
- schedule(() {
- return Future.wait(
- [_ensureWebSocket(), awaitObject(params),]).then((results) {
- var resolvedParams = results[1];
- chainToCompleter(
- currentSchedule.wrapFuture(_jsonRpcRequest(method, resolvedParams)),
- completer);
- });
- }, "send $method with $params to web socket");
- return completer.future;
-}
-
-/// Sends a JSON RPC 2.0 request to the running pub serve's web socket
-/// connection, waits for a reply, then verifies the result.
-///
-/// This calls a method named [method] with the given [params]. [params] may
-/// contain Futures, in which case this will wait until they've completed before
-/// sending the request.
-///
-/// The result is validated using [result], which may be a [Matcher] or a [Map]
-/// containing [Matcher]s and [Future]s. This will wait until any futures are
-/// completed before sending the request.
-///
-/// Returns a [Future] that completes to the call's result.
-Future<Map> expectWebSocketResult(String method, Map params, result) {
- return schedule(() {
- return Future.wait(
- [webSocketRequest(method, params), awaitObject(result)]).then((results) {
- var response = results[0];
- var resolvedResult = results[1];
- expect(response["result"], resolvedResult);
- return response["result"];
- });
- }, "send $method with $params to web socket and expect $result");
-}
-
-/// Sends a JSON RPC 2.0 request to the running pub serve's web socket
-/// connection, waits for a reply, then verifies the error response.
-///
-/// This calls a method named [method] with the given [params]. [params] may
-/// contain Futures, in which case this will wait until they've completed before
-/// sending the request.
-///
-/// The error response is validated using [errorCode] and [errorMessage]. Both
-/// of these must be provided. The error code is checked against [errorCode] and
-/// the error message is checked against [errorMessage]. Either of these may be
-/// matchers.
-///
-/// If [data] is provided, it is a JSON value or matcher used to validate the
-/// "data" value of the error response.
-///
-/// Returns a [Future] that completes to the error's [data] field.
-Future expectWebSocketError(String method, Map params, errorCode, errorMessage,
- {data}) {
- return schedule(() {
- return webSocketRequest(method, params).then((response) {
- expect(response["error"]["code"], errorCode);
- expect(response["error"]["message"], errorMessage);
-
- if (data != null) {
- expect(response["error"]["data"], data);
- }
-
- return response["error"]["data"];
- });
- }, "send $method with $params to web socket and expect error $errorCode");
-}
-
-/// Validates that [root] was not bound to a port when pub serve started.
-Future expectNotServed(String root) {
- return schedule(() {
- expect(_ports.containsKey(root), isFalse);
- });
-}
-
-/// The next id to use for a JSON-RPC 2.0 request.
-var _rpcId = 0;
-
-/// Sends a JSON-RPC 2.0 request calling [method] with [params].
-///
-/// Returns the response object.
-Future<Map> _jsonRpcRequest(String method, [Map params]) {
- var id = _rpcId++;
- var message = {
- "jsonrpc": "2.0",
- "method": method,
- "id": id
- };
- if (params != null) message["params"] = params;
- _webSocket.add(JSON.encode(message));
-
- return _webSocketBroadcastStream.firstWhere(
- (response) => response["id"] == id).then((value) {
- currentSchedule.addDebugInfo(
- "Web Socket request $method with params $params\n" "Result: $value");
-
- expect(value["id"], equals(id));
- return value;
- });
-}
-
-/// Returns a [Future] that completes to a URL string for the server serving
-/// [path] from [root].
-///
-/// If [root] is omitted, defaults to "web". If [path] is omitted, no path is
-/// included. The Future will complete once the server is up and running and
-/// the bound ports are known.
-Future<String> getServerUrl([String root, String path]) =>
- _portsCompleter.future.then((_) => _getServerUrlSync(root, path));
-
-/// Records that [root] has been bound to [port].
-///
-/// Used for testing the Web Socket API for binding new root directories to
-/// ports after pub serve has been started.
-registerServerPort(String root, int port) {
- _ports[root] = port;
-}
-
-/// Returns a URL string for the server serving [path] from [root].
-///
-/// If [root] is omitted, defaults to "web". If [path] is omitted, no path is
-/// included. Unlike [getServerUrl], this should only be called after the ports
-/// are known.
-String _getServerUrlSync([String root, String path]) {
- if (root == null) root = 'web';
- expect(_ports, contains(root));
- var url = "http://localhost:${_ports[root]}";
- if (path != null) url = "$url/$path";
- return url;
-}
-
diff --git a/sdk/lib/_internal/pub_generated/test/serve/watch_added_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/watch_added_file_test.dart
deleted file mode 100644
index fa2063c..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/watch_added_file_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("picks up files added after serving started", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create();
-
- pubServe();
- waitForBuildSuccess();
- requestShouldSucceed("index.html", "body");
-
- d.dir(appPath, [d.dir("web", [d.file("other.html", "added")])]).create();
-
- waitForBuildSuccess();
- requestShouldSucceed("other.html", "added");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/watch_modified_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/watch_modified_file_test.dart
deleted file mode 100644
index a423737..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/watch_modified_file_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("watches modifications to files", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "before")])]).create();
-
- pubServe();
- requestShouldSucceed("index.html", "before");
-
- d.dir(appPath, [d.dir("web", [d.file("index.html", "after")])]).create();
-
- waitForBuildSuccess();
- requestShouldSucceed("index.html", "after");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/watch_removed_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/watch_removed_file_test.dart
deleted file mode 100644
index 222a4e3..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/watch_removed_file_test.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-main() {
- initConfig();
- integration("stop serving a file that is removed", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create();
-
- pubServe();
- requestShouldSucceed("index.html", "body");
-
- schedule(
- () => deleteEntry(path.join(sandboxDir, appPath, "web", "index.html")));
-
- waitForBuildSuccess();
- requestShould404("index.html");
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/exit_on_close_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/exit_on_close_test.dart
deleted file mode 100644
index 7e76bc4..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/exit_on_close_test.dart
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration("exits when the connection closes", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- var server = pubServe();
-
- // Make sure the web socket is active.
- expectWebSocketResult("urlToAssetId", {
- "url": getServerUrl("web", "index.html")
- }, {
- "package": "myapp",
- "path": "web/index.html"
- });
-
- expectWebSocketResult("exitOnClose", null, null);
-
- // Close the web socket.
- closeWebSocket();
-
- server.stdout.expect("Build completed successfully");
- server.stdout.expect("WebSocket connection closed, terminating.");
- server.shouldExit(0);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_errors_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_errors_test.dart
deleted file mode 100644
index 7774636..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_errors_test.dart
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:json_rpc_2/error_code.dart' as rpc_error_code;
-import 'package:path/path.dart' as p;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- // TODO(rnystrom): Split into independent tests.
- initConfig();
- integration("pathToUrls errors on bad inputs", () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }),
- d.file("top-level.txt", "top-level"),
- d.dir("bin", [d.file("foo.txt", "foo"),]),
- d.dir("lib", [d.file("myapp.dart", "myapp"),])]).create();
-
- pubServe(shouldGetFirst: true);
-
- // Bad arguments.
- expectWebSocketError("pathToUrls", {
- "path": 123
- },
- rpc_error_code.INVALID_PARAMS,
- 'Parameter "path" for method "pathToUrls" must be a string, but was ' '123.');
-
- expectWebSocketError("pathToUrls", {
- "path": "main.dart",
- "line": 12.34
- },
- rpc_error_code.INVALID_PARAMS,
- 'Parameter "line" for method "pathToUrls" must be an integer, but was '
- '12.34.');
-
- // Unserved directories.
- expectNotServed(p.join('bin', 'foo.txt'));
- expectNotServed(p.join('nope', 'foo.txt'));
- expectNotServed(p.join("..", "bar", "lib", "bar.txt"));
- expectNotServed(p.join("..", "foo", "web", "foo.txt"));
-
- endPubServe();
- });
-}
-
-void expectNotServed(String path) {
- expectWebSocketError("pathToUrls", {
- "path": path
- }, NOT_SERVED, 'Asset path "$path" is not currently being served.');
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_test.dart
deleted file mode 100644
index 820d552..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_test.dart
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as p;
-
-import '../../../lib/src/io.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- // TODO(rnystrom): Split into independent tests.
- initConfig();
- integration("pathToUrls converts asset ids to matching URL paths", () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.0.0"),
- d.dir("lib", [d.file("foo.dart", "foo() => null;")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }),
- d.dir(
- "test",
- [d.file("index.html", "<body>"), d.dir("sub", [d.file("bar.html", "bar"),])]),
- d.dir("lib", [d.file("app.dart", "app() => null;")]),
- d.dir(
- "web",
- [d.file("index.html", "<body>"), d.dir("sub", [d.file("bar.html", "bar"),])]),
- d.dir("randomdir", [d.file("index.html", "<body>")])]).create();
-
- pubServe(args: ["test", "web", "randomdir"], shouldGetFirst: true);
-
- // Paths in web/.
- expectWebSocketResult("pathToUrls", {
- "path": p.join("web", "index.html")
- }, {
- "urls": [getServerUrl("web", "index.html")]
- });
-
- expectWebSocketResult("pathToUrls", {
- "path": p.join("web", "sub", "bar.html")
- }, {
- "urls": [getServerUrl("web", "sub/bar.html")]
- });
-
- // Paths in test/.
- expectWebSocketResult("pathToUrls", {
- "path": p.join("test", "index.html")
- }, {
- "urls": [getServerUrl("test", "index.html")]
- });
-
- expectWebSocketResult("pathToUrls", {
- "path": p.join("test", "sub", "bar.html")
- }, {
- "urls": [getServerUrl("test", "sub/bar.html")]
- });
-
- // A non-default directory.
- expectWebSocketResult("pathToUrls", {
- "path": p.join("randomdir", "index.html")
- }, {
- "urls": [getServerUrl("randomdir", "index.html")]
- });
-
- // A path in lib/.
- expectWebSocketResult("pathToUrls", {
- "path": p.join("lib", "app.dart")
- }, {
- "urls": [
- getServerUrl("test", "packages/myapp/app.dart"),
- getServerUrl("web", "packages/myapp/app.dart"),
- getServerUrl("randomdir", "packages/myapp/app.dart")]
- });
-
- // A path to this package in packages/.
- expectWebSocketResult("pathToUrls", {
- "path": p.join("packages", "myapp", "app.dart")
- }, {
- "urls": [
- getServerUrl("test", "packages/myapp/app.dart"),
- getServerUrl("web", "packages/myapp/app.dart"),
- getServerUrl("randomdir", "packages/myapp/app.dart")]
- });
-
- // A path to another package in packages/.
- expectWebSocketResult("pathToUrls", {
- "path": p.join("packages", "foo", "foo.dart")
- }, {
- "urls": [
- getServerUrl("test", "packages/foo/foo.dart"),
- getServerUrl("web", "packages/foo/foo.dart"),
- getServerUrl("randomdir", "packages/foo/foo.dart")]
- });
-
- // A relative path to another package's lib/ directory.
- expectWebSocketResult("pathToUrls", {
- "path": p.join("..", "foo", "lib", "foo.dart")
- }, {
- "urls": [
- getServerUrl("test", "packages/foo/foo.dart"),
- getServerUrl("web", "packages/foo/foo.dart"),
- getServerUrl("randomdir", "packages/foo/foo.dart")]
- });
-
- // Note: Using canonicalize here because pub gets the path to the
- // entrypoint package from the working directory, which has had symlinks
- // resolve. On Mac, "/tmp" is actually a symlink to "/private/tmp", so we
- // need to accomodate that.
-
- // An absolute path to another package's lib/ directory.
- expectWebSocketResult("pathToUrls", {
- "path": canonicalize(p.join(sandboxDir, "foo", "lib", "foo.dart"))
- }, {
- "urls": [
- getServerUrl("test", "packages/foo/foo.dart"),
- getServerUrl("web", "packages/foo/foo.dart"),
- getServerUrl("randomdir", "packages/foo/foo.dart")]
- });
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_with_line_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_with_line_test.dart
deleted file mode 100644
index 4e2f244..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_with_line_test.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as p;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration("pathToUrls provides output line if given source", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("main.dart", "main"),])]).create();
-
- pubServe();
-
- expectWebSocketResult("pathToUrls", {
- "path": p.join("web", "main.dart"),
- "line": 12345
- }, {
- "urls": [getServerUrl("web", "main.dart")],
- "line": 12345
- });
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_already_served_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_already_served_test.dart
deleted file mode 100644
index 6e27e86..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_already_served_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration("returns the old URL if the directory is already served", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- pubServe();
-
- expectWebSocketResult("serveDirectory", {
- "path": "web"
- }, {
- "url": getServerUrl("web")
- });
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_request_asset_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_request_asset_test.dart
deleted file mode 100644
index 19db307..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_request_asset_test.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration(
- "binds a directory to a new port and immediately requests an "
- "asset URL from that server",
- () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("test", [d.file("index.html", "<test body>")]),
- d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- pubServe(args: ["web"]);
-
- // Bind the new directory.
- expect(webSocketRequest("serveDirectory", {
- "path": "test"
- }), completes);
-
- expectWebSocketResult("pathToUrls", {
- "path": "test/index.html"
- }, {
- "urls": [endsWith("/index.html")]
- });
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_serve_again_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_serve_again_test.dart
deleted file mode 100644
index 0de5877..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_serve_again_test.dart
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:async';
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration(
- "binds a directory to a new port and immediately binds that " "directory again",
- () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("test", [d.file("index.html", "<test body>")]),
- d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- pubServe(args: ["web"]);
-
- schedule(() {
- return Future.wait([webSocketRequest("serveDirectory", {
- "path": "test"
- }), webSocketRequest("serveDirectory", {
- "path": "test"
- })]).then((results) {
- expect(results[0], contains("result"));
- expect(results[1], contains("result"));
- expect(results[0]["result"], equals(results[1]["result"]));
- });
- });
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_unserve_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_unserve_test.dart
deleted file mode 100644
index 7266680..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_unserve_test.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:async';
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration(
- "binds a directory to a new port and immediately unbinds that " "directory",
- () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("test", [d.file("index.html", "<test body>")]),
- d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- pubServe(args: ["web"]);
-
- // We call [webSocketRequest] outside of the [schedule] call below because
- // we need it to schedule the sending of the request to guarantee that the
- // serve is sent before the unserve.
- var serveRequest = webSocketRequest("serveDirectory", {
- "path": "test"
- });
- var unserveRequest = webSocketRequest("unserveDirectory", {
- "path": "test"
- });
-
- schedule(() {
- return Future.wait([serveRequest, unserveRequest]).then((results) {
- expect(results[0], contains("result"));
- expect(results[1], contains("result"));
- // These results should be equal since "serveDirectory" returns the URL
- // of the new server and "unserveDirectory" returns the URL of the
- // server that was turned off. We're asserting that the same server was
- // both started and stopped.
- expect(results[0]["result"]["url"], matches(r"http://localhost:\d+"));
- expect(results[0]["result"], equals(results[1]["result"]));
- });
- });
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_arg_errors_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_arg_errors_test.dart
deleted file mode 100644
index 7a6374d..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_arg_errors_test.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:json_rpc_2/error_code.dart' as rpc_error_code;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "<body>")])]).create();
- });
-
- integration("responds with an error if 'path' is not a string", () {
- pubServe();
- expectWebSocketError("serveDirectory", {
- "path": 123
- },
- rpc_error_code.INVALID_PARAMS,
- 'Parameter "path" for method "serveDirectory" must be a string, but '
- 'was 123.');
- endPubServe();
- });
-
- integration("responds with an error if 'path' is absolute", () {
- pubServe();
- expectWebSocketError("serveDirectory", {
- "path": "/absolute.txt"
- },
- rpc_error_code.INVALID_PARAMS,
- '"path" must be a relative path. Got "/absolute.txt".');
- endPubServe();
- });
-
- integration("responds with an error if 'path' reaches out", () {
- pubServe();
- expectWebSocketError("serveDirectory", {
- "path": "a/../../bad.txt"
- },
- rpc_error_code.INVALID_PARAMS,
- '"path" cannot reach out of its containing directory. Got '
- '"a/../../bad.txt".');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_overlapping_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_overlapping_test.dart
deleted file mode 100644
index 6902531..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_overlapping_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration("fails if the directory overlaps one already being served", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir(
- "web",
- [
- d.file("index.html", "<body>"),
- d.dir("sub", [d.file("index.html", "<sub>"),])])]).create();
-
- pubServe();
-
- var webSub = path.join("web", "sub");
- expectWebSocketError("serveDirectory", {
- "path": webSub
- },
- 2,
- 'Path "$webSub" overlaps already served directory "web".',
- data: containsPair("directories", ["web"]));
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_test.dart
deleted file mode 100644
index 5738eb2..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_test.dart
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration("binds a directory to a new port", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("test", [d.file("index.html", "<test body>")]),
- d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- pubServe(args: ["web"]);
-
- // Bind the new directory.
- expectWebSocketResult("serveDirectory", {
- "path": "test"
- }, {
- "url": matches(r"http://localhost:\d+")
- }).then((response) {
- var url = Uri.parse(response["url"]);
- registerServerPort("test", url.port);
- });
-
- // It should be served now.
- requestShouldSucceed("index.html", "<test body>", root: "test");
-
- // And watched.
- d.dir(appPath, [d.dir("test", [d.file("index.html", "after")])]).create();
-
- waitForBuildSuccess();
- requestShouldSucceed("index.html", "after", root: "test");
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_arg_errors_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_arg_errors_test.dart
deleted file mode 100644
index 25fd234..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_arg_errors_test.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:json_rpc_2/error_code.dart' as rpc_error_code;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
-
- setUp(() {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "<body>")])]).create();
- });
-
- integration("responds with an error if 'path' is not a string", () {
- pubServe();
- expectWebSocketError("unserveDirectory", {
- "path": 123
- },
- rpc_error_code.INVALID_PARAMS,
- 'Parameter "path" for method "unserveDirectory" must be a string, but '
- 'was 123.');
- endPubServe();
- });
-
- integration("responds with an error if 'path' is absolute", () {
- pubServe();
- expectWebSocketError("unserveDirectory", {
- "path": "/absolute.txt"
- },
- rpc_error_code.INVALID_PARAMS,
- '"path" must be a relative path. Got "/absolute.txt".');
- endPubServe();
- });
-
- integration("responds with an error if 'path' reaches out", () {
- pubServe();
- expectWebSocketError("unserveDirectory", {
- "path": "a/../../bad.txt"
- },
- rpc_error_code.INVALID_PARAMS,
- '"path" cannot reach out of its containing directory. Got '
- '"a/../../bad.txt".');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_not_served_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_not_served_test.dart
deleted file mode 100644
index 528f051..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_not_served_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration("errors if the directory is not served", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- pubServe();
-
- // Unbind the directory.
- expectWebSocketError("unserveDirectory", {
- "path": "test"
- }, NOT_SERVED, 'Directory "test" is not bound to a server.');
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_test.dart
deleted file mode 100644
index c182e57..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_test.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration("unbinds a directory from a port", () {
- d.dir(
- appPath,
- [
- d.appPubspec(),
- d.dir("test", [d.file("index.html", "<test body>")]),
- d.dir("web", [d.file("index.html", "<body>")])]).create();
-
- pubServe();
-
- requestShouldSucceed("index.html", "<body>");
- requestShouldSucceed("index.html", "<test body>", root: "test");
-
- // Unbind the directory.
- expectWebSocketResult("unserveDirectory", {
- "path": "test"
- }, {
- "url": getServerUrl("test")
- });
-
- // "test" should not be served now.
- requestShouldNotConnect("index.html", root: "test");
-
- // "web" is still fine.
- requestShouldSucceed("index.html", "<body>");
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_errors_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_errors_test.dart
deleted file mode 100644
index 4892bf3..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_errors_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- setUp(() {
- d.dir(appPath, [d.appPubspec()]).create();
- });
-
- integration("responds with NOT_SERVED for an unknown domain", () {
- pubServe();
- expectWebSocketError("urlToAssetId", {
- "url": "http://example.com:80/index.html"
- }, NOT_SERVED, '"example.com:80" is not being served by pub.');
- endPubServe();
- });
-
- integration("responds with NOT_SERVED for an unknown port", () {
- pubServe();
- expectWebSocketError("urlToAssetId", {
- "url": "http://localhost:80/index.html"
- }, NOT_SERVED, '"localhost:80" is not being served by pub.');
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_test.dart
deleted file mode 100644
index a572772..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_test.dart
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- // TODO(rnystrom): Split into independent tests.
- initConfig();
- setUp(() {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "0.0.1"),
- d.dir("lib", [d.file("foo.dart", "foo")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }),
- d.dir("lib", [d.file("myapp.dart", "myapp"),]),
- d.dir(
- "test",
- [d.file("index.html", "<body>"), d.dir("sub", [d.file("bar.html", "bar"),])]),
- d.dir(
- "web",
- [
- d.file("index.html", "<body>"),
- d.dir("sub", [d.file("bar.html", "bar"),])])]).create();
- });
-
- integration("converts URLs to matching asset ids in web/", () {
- pubServe(shouldGetFirst: true);
- expectWebSocketResult("urlToAssetId", {
- "url": getServerUrl("web", "index.html")
- }, {
- "package": "myapp",
- "path": "web/index.html"
- });
- endPubServe();
- });
-
- integration(
- "converts URLs to matching asset ids in subdirectories of web/",
- () {
- pubServe(shouldGetFirst: true);
- expectWebSocketResult("urlToAssetId", {
- "url": getServerUrl("web", "sub/bar.html")
- }, {
- "package": "myapp",
- "path": "web/sub/bar.html"
- });
- endPubServe();
- });
-
- integration("converts URLs to matching asset ids in test/", () {
- pubServe(shouldGetFirst: true);
- expectWebSocketResult("urlToAssetId", {
- "url": getServerUrl("test", "index.html")
- }, {
- "package": "myapp",
- "path": "test/index.html"
- });
- endPubServe();
- });
-
- integration(
- "converts URLs to matching asset ids in subdirectories of test/",
- () {
- pubServe(shouldGetFirst: true);
- expectWebSocketResult("urlToAssetId", {
- "url": getServerUrl("test", "sub/bar.html")
- }, {
- "package": "myapp",
- "path": "test/sub/bar.html"
- });
- endPubServe();
- });
-
- integration(
- "converts URLs to matching asset ids in the entrypoint's lib/",
- () {
- // Path in root package's lib/.
- pubServe(shouldGetFirst: true);
- expectWebSocketResult("urlToAssetId", {
- "url": getServerUrl("web", "packages/myapp/myapp.dart")
- }, {
- "package": "myapp",
- "path": "lib/myapp.dart"
- });
- endPubServe();
- });
-
- integration("converts URLs to matching asset ids in a dependency's lib/", () {
- // Path in lib/.
- pubServe(shouldGetFirst: true);
- expectWebSocketResult("urlToAssetId", {
- "url": getServerUrl("web", "packages/foo/foo.dart")
- }, {
- "package": "foo",
- "path": "lib/foo.dart"
- });
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_with_line_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_with_line_test.dart
deleted file mode 100644
index da13fc5..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_with_line_test.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../utils.dart';
-
-main() {
- initConfig();
- integration("provides output line number if given source one", () {
- d.dir(
- appPath,
- [d.appPubspec(), d.dir("web", [d.file("main.dart", "main")])]).create();
-
- pubServe();
-
- // Paths in web/.
- expectWebSocketResult("urlToAssetId", {
- "url": getServerUrl("web", "main.dart"),
- "line": 12345
- }, {
- "package": "myapp",
- "path": "web/main.dart",
- "line": 12345
- });
-
- endPubServe();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/serve_packages.dart b/sdk/lib/_internal/pub_generated/test/serve_packages.dart
deleted file mode 100644
index 2fad96d..0000000
--- a/sdk/lib/_internal/pub_generated/test/serve_packages.dart
+++ /dev/null
@@ -1,192 +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.
-
-library serve_packages;
-
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:path/path.dart' as p;
-import 'package:pub_semver/pub_semver.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:yaml/yaml.dart';
-
-import '../lib/src/io.dart';
-import '../lib/src/utils.dart';
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-/// The [d.DirectoryDescriptor] describing the server layout of `/api/packages`
-/// on the test server.
-///
-/// This contains metadata for packages that are being served via
-/// [servePackages]. It's `null` if [servePackages] has not yet been called for
-/// this test.
-d.DirectoryDescriptor _servedApiPackageDir;
-
-/// The [d.DirectoryDescriptor] describing the server layout of `/packages` on
-/// the test server.
-///
-/// This contains the tarballs for packages that are being served via
-/// [servePackages]. It's `null` if [servePackages] has not yet been called for
-/// this test.
-d.DirectoryDescriptor _servedPackageDir;
-
-/// The current [PackageServerBuilder] that a user uses to specify which package
-/// to serve.
-///
-/// This is preserved over multiple calls to [servePackages] within the same
-/// test so that additional packages can be added.
-PackageServerBuilder _builder;
-
-/// Creates an HTTP server that replicates the structure of pub.dartlang.org.
-///
-/// Calls [callback] with a [PackageServerBuilder] that's used to specify
-/// which packages to serve.
-///
-/// If [replace] is false, subsequent calls to [servePackages] will add to the
-/// set of packages that are being served. Previous packages will continue to be
-/// served. Otherwise, the previous packages will no longer be served.
-void servePackages(void callback(PackageServerBuilder builder), {bool replace:
- false}) {
- if (_servedPackageDir == null) {
- _builder = new PackageServerBuilder();
- _servedApiPackageDir = d.dir('packages', []);
- _servedPackageDir = d.dir('packages', []);
- serve([d.dir('api', [_servedApiPackageDir]), _servedPackageDir]);
-
- currentSchedule.onComplete.schedule(() {
- _builder = null;
- _servedApiPackageDir = null;
- _servedPackageDir = null;
- }, 'cleaning up served packages');
- }
-
- schedule(() {
- if (replace) _builder = new PackageServerBuilder();
- callback(_builder);
- return _builder._await().then((resolvedPubspecs) {
- _servedApiPackageDir.contents.clear();
- _servedPackageDir.contents.clear();
- _builder._packages.forEach((name, versions) {
- _servedApiPackageDir.contents.addAll([d.file('$name', JSON.encode({
- 'name': name,
- 'uploaders': ['nweiz@google.com'],
- 'versions': versions.map(
- (version) => packageVersionApiMap(version.pubspec)).toList()
- })), d.dir(name, [d.dir('versions', versions.map((version) {
- return d.file(
- version.version.toString(),
- JSON.encode(packageVersionApiMap(version.pubspec, full: true)));
- }))])]);
-
- _servedPackageDir.contents.add(
- d.dir(
- name,
- [
- d.dir(
- 'versions',
- versions.map(
- (version) => d.tar('${version.version}.tar.gz', version.contents)))]));
- });
- });
- }, 'initializing the package server');
-}
-
-/// Like [servePackages], but instead creates an empty server with no packages
-/// registered.
-///
-/// This will always replace a previous server.
-void serveNoPackages() => servePackages((_) {}, replace: true);
-
-/// A builder for specifying which packages should be served by [servePackages].
-class PackageServerBuilder {
- /// A map from package names to a list of concrete packages to serve.
- final _packages = new Map<String, List<_ServedPackage>>();
-
- /// A group of futures from [serve] calls.
- ///
- /// This should be accessed by calling [_awair].
- var _futures = new FutureGroup();
-
- /// Specifies that a package named [name] with [version] should be served.
- ///
- /// If [deps] is passed, it's used as the "dependencies" field of the pubspec.
- /// If [pubspec] is passed, it's used as the rest of the pubspec. Either of
- /// these may recursively contain Futures.
- ///
- /// If [contents] is passed, it's used as the contents of the package. By
- /// default, a package just contains a dummy lib directory.
- void serve(String name, String version, {Map deps, Map pubspec,
- Iterable<d.Descriptor> contents}) {
- _futures.add(
- Future.wait([awaitObject(deps), awaitObject(pubspec)]).then((pair) {
- var resolvedDeps = pair.first;
- var resolvedPubspec = pair.last;
-
- var pubspecFields = {
- "name": name,
- "version": version
- };
- if (resolvedPubspec != null) pubspecFields.addAll(resolvedPubspec);
- if (resolvedDeps != null) pubspecFields["dependencies"] = resolvedDeps;
-
- if (contents == null) contents = [d.libDir(name, "$name $version")];
- contents =
- [d.file("pubspec.yaml", yaml(pubspecFields))]..addAll(contents);
-
- var packages = _packages.putIfAbsent(name, () => []);
- packages.add(new _ServedPackage(pubspecFields, contents));
- }));
- }
-
- /// Serves the versions of [package] and all its dependencies that are
- /// currently checked into the Dart repository.
- void serveRepoPackage(String package) {
- _addPackage(name) {
- if (_packages.containsKey(name)) return;
- _packages[name] = [];
-
- var root = packagePath(name);
- var pubspec =
- new Map.from(loadYaml(readTextFile(p.join(root, 'pubspec.yaml'))));
-
- // Remove any SDK constraints since we don't have a valid SDK version
- // while testing.
- pubspec.remove('environment');
-
- _packages[name].add(
- new _ServedPackage(
- pubspec,
- [
- d.file('pubspec.yaml', yaml(pubspec)),
- new d.DirectoryDescriptor.fromFilesystem('lib', p.join(root, 'lib'))]));
-
- if (pubspec.containsKey('dependencies')) {
- pubspec['dependencies'].keys.forEach(_addPackage);
- }
- }
-
- _addPackage(package);
- }
-
- /// Returns a Future that completes once all the [serve] calls have been fully
- /// processed.
- Future _await() {
- if (_futures.futures.isEmpty) return new Future.value();
- return _futures.future.then((_) {
- _futures = new FutureGroup();
- });
- }
-}
-
-/// A package that's intended to be served.
-class _ServedPackage {
- final Map pubspec;
- final List<d.Descriptor> contents;
-
- Version get version => new Version.parse(pubspec['version']);
-
- _ServedPackage(this.pubspec, this.contents);
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_for_immediate_and_transitive_dep_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_for_immediate_and_transitive_dep_test.dart
deleted file mode 100644
index c9a5034..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_for_immediate_and_transitive_dep_test.dart
+++ /dev/null
@@ -1,64 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "creates a snapshot for an immediate dependency that's also a "
- "transitive dependency",
- () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.2.3",
- contents: [
- d.dir(
- "bin",
- [
- d.file("hello.dart", "void main() => print('hello!');"),
- d.file("goodbye.dart", "void main() => print('goodbye!');"),
- d.file("shell.sh", "echo shell"),
- d.dir("subdir", [d.file("sub.dart", "void main() => print('sub!');")])])]);
- builder.serve("bar", "1.2.3", deps: {
- "foo": "1.2.3"
- });
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(
- output: allOf(
- [contains("Precompiled foo:hello."), contains("Precompiled foo:goodbye.")]));
-
- d.dir(
- p.join(appPath, '.pub', 'bin'),
- [
- d.file('sdk-version', '0.1.2+3\n'),
- d.dir(
- 'foo',
- [
- d.matcherFile('hello.dart.snapshot', contains('hello!')),
- d.matcherFile('goodbye.dart.snapshot', contains('goodbye!')),
- d.nothing('shell.sh.snapshot'),
- d.nothing('subdir')])]).validate();
-
- var process = pubRun(args: ['foo:hello']);
- process.stdout.expect("hello!");
- process.shouldExit();
-
- process = pubRun(args: ['foo:goodbye']);
- process.stdout.expect("goodbye!");
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_test.dart
deleted file mode 100644
index 553829d..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "creates a snapshot for an immediate dependency's executables",
- () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.2.3",
- contents: [
- d.dir(
- "bin",
- [
- d.file("hello.dart", "void main() => print('hello!');"),
- d.file("goodbye.dart", "void main() => print('goodbye!');"),
- d.file("shell.sh", "echo shell"),
- d.dir("subdir", [d.file("sub.dart", "void main() => print('sub!');")])])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(
- output: allOf(
- [contains("Precompiled foo:hello."), contains("Precompiled foo:goodbye.")]));
-
- d.dir(
- p.join(appPath, '.pub', 'bin'),
- [
- d.file('sdk-version', '0.1.2+3\n'),
- d.dir(
- 'foo',
- [
- d.matcherFile('hello.dart.snapshot', contains('hello!')),
- d.matcherFile('goodbye.dart.snapshot', contains('goodbye!')),
- d.nothing('shell.sh.snapshot'),
- d.nothing('subdir')])]).validate();
-
- var process = pubRun(args: ['foo:hello']);
- process.stdout.expect("hello!");
- process.shouldExit();
-
- process = pubRun(args: ['foo:goodbye']);
- process.stdout.expect("goodbye!");
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_load_irrelevant_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_load_irrelevant_transformers_test.dart
deleted file mode 100644
index 7759718..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_load_irrelevant_transformers_test.dart
+++ /dev/null
@@ -1,63 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const BROKEN_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class BrokenTransformer extends Transformer {
- BrokenTransformer.asPlugin();
-
- // This file intentionally has a syntax error so that any attempt to load it
- // will crash.
-""";
-
-main() {
- initConfig();
-
- // Regression test for issue 20917.
- integration("snapshots the transformed version of an executable", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve(
- "foo",
- "1.2.3",
- contents: [
- d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]);
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "1.2.3",
- "barback": "any"
- },
- "transformers": ["myapp"]
- }),
- d.dir("lib", [d.file("transformer.dart", BROKEN_TRANSFORMER)])]).create();
-
- pubGet(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin'),
- [
- d.dir(
- 'foo',
- [d.matcherFile('hello.dart.snapshot', contains('hello!'))])]).validate();
-
- var process = pubRun(args: ['foo:hello']);
- process.stdout.expect("hello!");
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_resnapshot_when_a_dependency_is_unchanged_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_resnapshot_when_a_dependency_is_unchanged_test.dart
deleted file mode 100644
index b19f060..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_resnapshot_when_a_dependency_is_unchanged_test.dart
+++ /dev/null
@@ -1,43 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "doesn't recreate a snapshot when no dependencies of a package " "have changed",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3", deps: {
- "bar": "any"
- },
- contents: [
- d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]);
- builder.serve("bar", "1.2.3");
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(output: contains("Precompiled foo:hello."));
-
- pubUpgrade(output: isNot(contains("Precompiled foo:hello.")));
-
- d.dir(
- p.join(appPath, '.pub', 'bin'),
- [
- d.file('sdk-version', '0.1.2+3\n'),
- d.dir(
- 'foo',
- [d.matcherFile('hello.dart.snapshot', contains('hello!'))])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_an_entrypoint_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_an_entrypoint_dependency_test.dart
deleted file mode 100644
index 60998e1..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_an_entrypoint_dependency_test.dart
+++ /dev/null
@@ -1,39 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "doesn't create a snapshot for a package that depends on the " "entrypoint",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3", deps: {
- 'bar': '1.2.3'
- },
- contents: [
- d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]);
- builder.serve("bar", "1.2.3", deps: {
- 'myapp': 'any'
- });
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet();
-
- // No local cache should be created, since all dependencies transitively
- // depend on the entrypoint.
- d.nothing(p.join(appPath, '.pub', 'bin')).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_path_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_path_dependency_test.dart
deleted file mode 100644
index 6542ab1..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_path_dependency_test.dart
+++ /dev/null
@@ -1,37 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("doesn't create a snapshot for a path dependency", () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", "1.2.3"),
- d.dir(
- "bin",
- [
- d.dir(
- "bin",
- [d.file("hello.dart", "void main() => print('hello!');")])])]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo"
- }
- }).create();
-
- pubGet();
-
- d.nothing(p.join(appPath, '.pub', 'bin')).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_transitive_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_transitive_dependencies_test.dart
deleted file mode 100644
index 3ea2d22..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_transitive_dependencies_test.dart
+++ /dev/null
@@ -1,37 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "doesn't create a snapshot for transitive dependencies' " "executables",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3", deps: {
- 'bar': '1.2.3'
- });
- builder.serve(
- "bar",
- "1.2.3",
- contents: [
- d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet();
-
- d.nothing(p.join(appPath, '.pub', 'bin', 'bar')).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/prints_errors_for_broken_snapshots_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/prints_errors_for_broken_snapshots_test.dart
deleted file mode 100644
index 60b5e1c..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/prints_errors_for_broken_snapshots_test.dart
+++ /dev/null
@@ -1,66 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("prints errors for broken snapshot compilation", () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.2.3",
- contents: [
- d.dir(
- "bin",
- [
- d.file("hello.dart", "void main() { no closing brace"),
- d.file("goodbye.dart", "void main() { no closing brace"),])]);
- builder.serve(
- "bar",
- "1.2.3",
- contents: [
- d.dir(
- "bin",
- [
- d.file("hello.dart", "void main() { no closing brace"),
- d.file("goodbye.dart", "void main() { no closing brace"),])]);
- });
-
- d.appDir({
- "foo": "1.2.3",
- "bar": "1.2.3"
- }).create();
-
- // This should still have a 0 exit code, since installation succeeded even
- // if precompilation didn't.
- pubGet(
- error: allOf(
- [
- contains("Failed to precompile foo:hello"),
- contains("Failed to precompile foo:goodbye"),
- contains("Failed to precompile bar:hello"),
- contains("Failed to precompile bar:goodbye")]),
- exitCode: 0);
-
- d.dir(
- p.join(appPath, '.pub', 'bin'),
- [
- d.file('sdk-version', '0.1.2+3\n'),
- d.dir(
- 'foo',
- [d.nothing('hello.dart.snapshot'), d.nothing('goodbye.dart.snapshot')]),
- d.dir(
- 'bar',
- [
- d.nothing('hello.dart.snapshot'),
- d.nothing('goodbye.dart.snapshot')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/recompiles_if_the_sdk_is_out_of_date_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/recompiles_if_the_sdk_is_out_of_date_test.dart
deleted file mode 100644
index f10098f..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/recompiles_if_the_sdk_is_out_of_date_test.dart
+++ /dev/null
@@ -1,53 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "creates a snapshot for an immediate dependency's executables",
- () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "5.6.7",
- contents: [
- d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]);
- });
-
- d.appDir({
- "foo": "5.6.7"
- }).create();
-
- pubGet(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin'),
- [d.dir('foo', [d.outOfDateSnapshot('hello.dart.snapshot')])]).create();
-
- var process = pubRun(args: ['foo:hello']);
-
- // In the real world this would just print "hello!", but since we collect
- // all output we see the precompilation messages as well.
- process.stdout.expect("Precompiling executables...");
- process.stdout.expect(consumeThrough("hello!"));
- process.shouldExit();
-
- d.dir(
- p.join(appPath, '.pub', 'bin'),
- [
- d.file('sdk-version', '0.1.2+3'),
- d.dir(
- 'foo',
- [d.matcherFile('hello.dart.snapshot', contains('hello!'))])]).create();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/snapshots_transformed_code_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/snapshots_transformed_code_test.dart
deleted file mode 100644
index 6defffb..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/snapshots_transformed_code_test.dart
+++ /dev/null
@@ -1,69 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const REPLACE_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class ReplaceTransformer extends Transformer {
- ReplaceTransformer.asPlugin();
-
- String get allowedExtensions => '.dart';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- transform.addOutput(new Asset.fromString(transform.primaryInput.id,
- contents.replaceAll("REPLACE ME", "hello!")));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- integration("snapshots the transformed version of an executable", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- "barback": "any"
- }, pubspec: {
- 'transformers': ['foo']
- },
- contents: [
- d.dir("lib", [d.file("foo.dart", REPLACE_TRANSFORMER)]),
- d.dir("bin", [d.file("hello.dart", """
-final message = 'REPLACE ME';
-
-void main() => print(message);
-"""),])]);
- });
-
- d.appDir({
- "foo": "1.2.3"
- }).create();
-
- pubGet(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin'),
- [
- d.dir(
- 'foo',
- [d.matcherFile('hello.dart.snapshot', contains('hello!'))])]).validate();
-
- var process = pubRun(args: ['foo:hello']);
- process.stdout.expect("hello!");
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/updates_snapshot_for_git_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/updates_snapshot_for_git_dependency_test.dart
deleted file mode 100644
index b370c80..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/updates_snapshot_for_git_dependency_test.dart
+++ /dev/null
@@ -1,55 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("upgrades a snapshot when a git dependency is upgraded", () {
- ensureGit();
-
- d.git('foo.git', [d.pubspec({
- "name": "foo",
- "version": "0.0.1"
- }),
- d.dir(
- "bin",
- [d.file("hello.dart", "void main() => print('Hello!');")])]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin', 'foo'),
- [d.matcherFile('hello.dart.snapshot', contains('Hello!'))]).validate();
-
- d.git(
- 'foo.git',
- [
- d.dir(
- "bin",
- [d.file("hello.dart", "void main() => print('Goodbye!');")])]).commit();
-
- pubUpgrade(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin', 'foo'),
- [d.matcherFile('hello.dart.snapshot', contains('Goodbye!'))]).validate();
-
- var process = pubRun(args: ['foo:hello']);
- process.stdout.expect("Goodbye!");
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_for_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_for_dependency_test.dart
deleted file mode 100644
index 0749c5e..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_for_dependency_test.dart
+++ /dev/null
@@ -1,59 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("upgrades a snapshot when a dependency is upgraded", () {
- servePackages((builder) {
- builder.serve("foo", "1.2.3", pubspec: {
- "dependencies": {
- "bar": "any"
- }
- }, contents: [d.dir("bin", [d.file("hello.dart", """
-import 'package:bar/bar.dart';
-
-void main() => print(message);
-""")])]);
- builder.serve(
- "bar",
- "1.2.3",
- contents: [d.dir("lib", [d.file("bar.dart", "final message = 'hello!';")])]);
- });
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin', 'foo'),
- [d.matcherFile('hello.dart.snapshot', contains('hello!'))]).validate();
-
- servePackages((builder) {
- builder.serve(
- "bar",
- "1.2.4",
- contents: [d.dir("lib", [d.file("bar.dart", "final message = 'hello 2!';")]),]);
- });
-
- pubUpgrade(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin', 'foo'),
- [d.matcherFile('hello.dart.snapshot', contains('hello 2!'))]).validate();
-
- var process = pubRun(args: ['foo:hello']);
- process.stdout.expect("hello 2!");
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_test.dart
deleted file mode 100644
index bd8150f..0000000
--- a/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_test.dart
+++ /dev/null
@@ -1,52 +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.
-
-library pub_tests;
-
-import 'package:path/path.dart' as p;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("upgrades a snapshot when its package is upgraded", () {
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.2.3",
- contents: [
- d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]);
- });
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin', 'foo'),
- [d.matcherFile('hello.dart.snapshot', contains('hello!'))]).validate();
-
- servePackages((builder) {
- builder.serve(
- "foo",
- "1.2.4",
- contents: [
- d.dir("bin", [d.file("hello.dart", "void main() => print('hello 2!');")])]);
- });
-
- pubUpgrade(output: contains("Precompiled foo:hello."));
-
- d.dir(
- p.join(appPath, '.pub', 'bin', 'foo'),
- [d.matcherFile('hello.dart.snapshot', contains('hello 2!'))]).validate();
-
- var process = pubRun(args: ['foo:hello']);
- process.stdout.expect("hello 2!");
- process.shouldExit();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/test_pub.dart b/sdk/lib/_internal/pub_generated/test/test_pub.dart
deleted file mode 100644
index 1fcc8d6..0000000
--- a/sdk/lib/_internal/pub_generated/test/test_pub.dart
+++ /dev/null
@@ -1,1015 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// Test infrastructure for testing pub.
-///
-/// Unlike typical unit tests, most pub tests are integration tests that stage
-/// some stuff on the file system, run pub, and then validate the results. This
-/// library provides an API to build tests like that.
-library test_pub;
-
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-import 'dart:math';
-
-import 'package:http/testing.dart';
-import 'package:path/path.dart' as p;
-import 'package:pub_semver/pub_semver.dart';
-import 'package:scheduled_test/scheduled_process.dart';
-import 'package:scheduled_test/scheduled_server.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart' hide fail;
-import 'package:shelf/shelf.dart' as shelf;
-import 'package:shelf/shelf_io.dart' as shelf_io;
-import 'package:unittest/compact_vm_config.dart';
-import 'package:yaml/yaml.dart';
-
-import '../lib/src/entrypoint.dart';
-import '../lib/src/exit_codes.dart' as exit_codes;
-// TODO(rnystrom): Using "gitlib" as the prefix here is ugly, but "git" collides
-// with the git descriptor method. Maybe we should try to clean up the top level
-// scope a bit?
-import '../lib/src/git.dart' as gitlib;
-import '../lib/src/http.dart';
-import '../lib/src/io.dart';
-import '../lib/src/lock_file.dart';
-import '../lib/src/log.dart' as log;
-import '../lib/src/package.dart';
-import '../lib/src/pubspec.dart';
-import '../lib/src/source/hosted.dart';
-import '../lib/src/source/path.dart';
-import '../lib/src/source_registry.dart';
-import '../lib/src/system_cache.dart';
-import '../lib/src/utils.dart';
-import '../lib/src/validator.dart';
-import 'descriptor.dart' as d;
-import 'serve_packages.dart';
-
-export 'serve_packages.dart';
-
-/// This should be called at the top of a test file to set up an appropriate
-/// test configuration for the machine running the tests.
-initConfig() {
- useCompactVMConfiguration();
- filterStacks = true;
- unittestConfiguration.timeout = null;
-}
-
-/// The current [HttpServer] created using [serve].
-var _server;
-
-/// The list of paths that have been requested from the server since the last
-/// call to [getRequestedPaths].
-final _requestedPaths = <String>[];
-
-/// The cached value for [_portCompleter].
-Completer<int> _portCompleterCache;
-
-/// A [Matcher] that matches JavaScript generated by dart2js with minification
-/// enabled.
-Matcher isMinifiedDart2JSOutput =
- isNot(contains("// The code supports the following hooks"));
-
-/// A [Matcher] that matches JavaScript generated by dart2js with minification
-/// disabled.
-Matcher isUnminifiedDart2JSOutput =
- contains("// The code supports the following hooks");
-
-/// A map from package names to paths from which those packages should be loaded
-/// for [createLockFile].
-///
-/// This allows older versions of dependencies than those that exist in the repo
-/// to be used when testing pub.
-Map<String, String> _packageOverrides;
-
-/// A map from barback versions to the paths of directories in the repo
-/// containing them.
-///
-/// This includes the latest version of barback from pkg as well as all old
-/// versions of barback in third_party.
-final _barbackVersions = _findBarbackVersions();
-
-/// Some older barback versions require older versions of barback's dependencies
-/// than those that are in the repo.
-///
-/// This is a map from barback version ranges to the dependencies for those
-/// barback versions. Each dependency version listed here should be included in
-/// third_party/pkg.
-final _barbackDeps = {
- new VersionConstraint.parse("<0.15.0"): {
- "source_maps": "0.9.4"
- }
-};
-
-/// Populates [_barbackVersions].
-Map<Version, String> _findBarbackVersions() {
- var versions = {};
- var currentBarback = p.join(repoRoot, 'third_party', 'pkg', 'barback');
- versions[new Pubspec.load(currentBarback, new SourceRegistry()).version] =
- currentBarback;
-
- for (var dir in listDir(p.join(repoRoot, 'third_party', 'pkg'))) {
- var basename = p.basename(dir);
- if (!basename.startsWith('barback-')) continue;
- versions[new Version.parse(split1(basename, '-').last)] = dir;
- }
-
- return versions;
-}
-
-/// Runs the tests in [callback] against all versions of barback in the repo
-/// that match [versionConstraint].
-///
-/// This is used to test that pub doesn't accidentally break older versions of
-/// barback that it's committed to supporting. Only versions `0.13.0` and later
-/// will be tested.
-void withBarbackVersions(String versionConstraint, void callback()) {
- var constraint = new VersionConstraint.parse(versionConstraint);
-
- var validVersions = _barbackVersions.keys.where(constraint.allows);
- if (validVersions.isEmpty) {
- throw new ArgumentError(
- 'No available barback version matches "$versionConstraint".');
- }
-
- for (var version in validVersions) {
- group("with barback $version", () {
- setUp(() {
- _packageOverrides = {};
- _packageOverrides['barback'] = _barbackVersions[version];
- _barbackDeps.forEach((constraint, deps) {
- if (!constraint.allows(version)) return;
- deps.forEach((packageName, version) {
- _packageOverrides[packageName] =
- p.join(repoRoot, 'third_party', 'pkg', '$packageName-$version');
- });
- });
-
- currentSchedule.onComplete.schedule(() {
- _packageOverrides = null;
- });
- });
-
- callback();
- });
- }
-}
-
-/// The completer for [port].
-Completer<int> get _portCompleter {
- if (_portCompleterCache != null) return _portCompleterCache;
- _portCompleterCache = new Completer<int>();
- currentSchedule.onComplete.schedule(() {
- _portCompleterCache = null;
- }, 'clearing the port completer');
- return _portCompleterCache;
-}
-
-/// A future that will complete to the port used for the current server.
-Future<int> get port => _portCompleter.future;
-
-/// Gets the list of paths that have been requested from the server since the
-/// last time this was called (or since the server was first spun up).
-Future<List<String>> getRequestedPaths() {
- return schedule(() {
- var paths = _requestedPaths.toList();
- _requestedPaths.clear();
- return paths;
- }, "get previous network requests");
-}
-
-/// Creates an HTTP server to serve [contents] as static files.
-///
-/// This server will exist only for the duration of the pub run. Subsequent
-/// calls to [serve] replace the previous server.
-void serve([List<d.Descriptor> contents]) {
- var baseDir = d.dir("serve-dir", contents);
-
- _hasServer = true;
-
- schedule(() {
- return _closeServer().then((_) {
- return shelf_io.serve((request) {
- currentSchedule.heartbeat();
- var path = p.posix.fromUri(request.url.path.replaceFirst("/", ""));
- _requestedPaths.add(path);
-
- return validateStream(
- baseDir.load(
- path)).then((stream) => new shelf.Response.ok(stream)).catchError((error) {
- return new shelf.Response.notFound('File "$path" not found.');
- });
- }, 'localhost', 0).then((server) {
- _server = server;
- _portCompleter.complete(_server.port);
- currentSchedule.onComplete.schedule(_closeServer);
- });
- });
- }, 'starting a server serving:\n${baseDir.describe()}');
-}
-
-/// Closes [_server].
-///
-/// Returns a [Future] that completes after the [_server] is closed.
-Future _closeServer() {
- if (_server == null) return new Future.value();
- var future = _server.close();
- _server = null;
- _hasServer = false;
- _portCompleterCache = null;
- return future;
-}
-
-/// `true` if the current test spins up an HTTP server.
-bool _hasServer = false;
-
-/// Converts [value] into a YAML string.
-String yaml(value) => JSON.encode(value);
-
-/// The full path to the created sandbox directory for an integration test.
-String get sandboxDir => _sandboxDir;
-String _sandboxDir;
-
-/// The path of the package cache directory used for tests, relative to the
-/// sandbox directory.
-final String cachePath = "cache";
-
-/// The path of the mock app directory used for tests, relative to the sandbox
-/// directory.
-final String appPath = "myapp";
-
-/// The path of the packages directory in the mock app used for tests, relative
-/// to the sandbox directory.
-final String packagesPath = "$appPath/packages";
-
-/// Set to true when the current batch of scheduled events should be aborted.
-bool _abortScheduled = false;
-
-/// Enum identifying a pub command that can be run with a well-defined success
-/// output.
-class RunCommand {
- static final get = new RunCommand(
- 'get',
- new RegExp(r'Got dependencies!|Changed \d+ dependenc(y|ies)!'));
- static final upgrade = new RunCommand(
- 'upgrade',
- new RegExp(r'(No dependencies changed\.|Changed \d+ dependenc(y|ies)!)$'));
- static final downgrade = new RunCommand(
- 'downgrade',
- new RegExp(r'(No dependencies changed\.|Changed \d+ dependenc(y|ies)!)$'));
-
- final String name;
- final RegExp success;
- RunCommand(this.name, this.success);
-}
-
-/// Runs the tests defined within [callback] using both pub get and pub upgrade.
-///
-/// Many tests validate behavior that is the same between pub get and
-/// upgrade have the same behavior. Instead of duplicating those tests, this
-/// takes a callback that defines get/upgrade agnostic tests and runs them
-/// with both commands.
-void forBothPubGetAndUpgrade(void callback(RunCommand command)) {
- group(RunCommand.get.name, () => callback(RunCommand.get));
- group(RunCommand.upgrade.name, () => callback(RunCommand.upgrade));
-}
-
-/// Schedules an invocation of pub [command] and validates that it completes
-/// in an expected way.
-///
-/// By default, this validates that the command completes successfully and
-/// understands the normal output of a successful pub command. If [warning] is
-/// given, it expects the command to complete successfully *and* print
-/// [warning] to stderr. If [error] is given, it expects the command to *only*
-/// print [error] to stderr. [output], [error], and [warning] may be strings,
-/// [RegExp]s, or [Matcher]s.
-///
-/// If [exitCode] is given, expects the command to exit with that code.
-// TODO(rnystrom): Clean up other tests to call this when possible.
-void pubCommand(RunCommand command, {Iterable<String> args, output, error,
- warning, int exitCode}) {
- if (error != null && warning != null) {
- throw new ArgumentError("Cannot pass both 'error' and 'warning'.");
- }
-
- var allArgs = [command.name];
- if (args != null) allArgs.addAll(args);
-
- if (output == null) output = command.success;
-
- if (error != null && exitCode == null) exitCode = 1;
-
- // No success output on an error.
- if (error != null) output = null;
- if (warning != null) error = warning;
-
- schedulePub(args: allArgs, output: output, error: error, exitCode: exitCode);
-}
-
-void pubGet({Iterable<String> args, output, error, warning, int exitCode}) {
- pubCommand(
- RunCommand.get,
- args: args,
- output: output,
- error: error,
- warning: warning,
- exitCode: exitCode);
-}
-
-void pubUpgrade({Iterable<String> args, output, error, warning, int exitCode}) {
- pubCommand(
- RunCommand.upgrade,
- args: args,
- output: output,
- error: error,
- warning: warning,
- exitCode: exitCode);
-}
-
-void pubDowngrade({Iterable<String> args, output, error, warning, int exitCode})
- {
- pubCommand(
- RunCommand.downgrade,
- args: args,
- output: output,
- error: error,
- warning: warning,
- exitCode: exitCode);
-}
-
-/// Schedules starting the "pub [global] run" process and validates the
-/// expected startup output.
-///
-/// If [global] is `true`, this invokes "pub global run", otherwise it does
-/// "pub run".
-///
-/// Returns the `pub run` process.
-ScheduledProcess pubRun({bool global: false, Iterable<String> args}) {
- var pubArgs = global ? ["global", "run"] : ["run"];
- pubArgs.addAll(args);
- var pub = startPub(args: pubArgs);
-
- // Loading sources and transformers isn't normally printed, but the pub test
- // infrastructure runs pub in verbose mode, which enables this.
- pub.stdout.expect(consumeWhile(startsWith("Loading")));
-
- return pub;
-}
-
-/// Defines an integration test.
-///
-/// The [body] should schedule a series of operations which will be run
-/// asynchronously.
-void integration(String description, void body()) =>
- _integration(description, body, test);
-
-/// Like [integration], but causes only this test to run.
-void solo_integration(String description, void body()) =>
- _integration(description, body, solo_test);
-
-void _integration(String description, void body(), [Function testFn]) {
- testFn(description, () {
- // TODO(nweiz): remove this when issue 15362 is fixed.
- currentSchedule.timeout *= 2;
-
- // The windows bots are very slow, so we increase the default timeout.
- if (Platform.operatingSystem == "windows") {
- currentSchedule.timeout *= 2;
- }
-
- _sandboxDir = createSystemTempDir();
- d.defaultRoot = sandboxDir;
- currentSchedule.onComplete.schedule(
- () => deleteEntry(_sandboxDir),
- 'deleting the sandbox directory');
-
- // Schedule the test.
- body();
- });
-}
-
-/// Get the path to the root "pub/test" directory containing the pub
-/// tests.
-String get testDirectory => p.absolute(p.dirname(libraryPath('test_pub')));
-
-/// Schedules renaming (moving) the directory at [from] to [to], both of which
-/// are assumed to be relative to [sandboxDir].
-void scheduleRename(String from, String to) {
- schedule(
- () => renameDir(p.join(sandboxDir, from), p.join(sandboxDir, to)),
- 'renaming $from to $to');
-}
-
-/// Schedules creating a symlink at path [symlink] that points to [target],
-/// both of which are assumed to be relative to [sandboxDir].
-void scheduleSymlink(String target, String symlink) {
- schedule(
- () => createSymlink(p.join(sandboxDir, target), p.join(sandboxDir, symlink)),
- 'symlinking $target to $symlink');
-}
-
-/// Schedules a call to the Pub command-line utility.
-///
-/// Runs Pub with [args] and validates that its results match [output] (or
-/// [outputJson]), [error], and [exitCode].
-///
-/// [output] and [error] can be [String]s, [RegExp]s, or [Matcher]s.
-///
-/// If [outputJson] is given, validates that pub outputs stringified JSON
-/// matching that object, which can be a literal JSON object or any other
-/// [Matcher].
-///
-/// If [environment] is given, any keys in it will override the environment
-/// variables passed to the spawned process.
-void schedulePub({List args, output, error, outputJson, int exitCode:
- exit_codes.SUCCESS, Map<String, String> environment}) {
- // Cannot pass both output and outputJson.
- assert(output == null || outputJson == null);
-
- var pub = startPub(args: args, environment: environment);
- pub.shouldExit(exitCode);
-
- var failures = [];
- var stderr;
-
- expect(
- Future.wait(
- [pub.stdoutStream().toList(), pub.stderrStream().toList()]).then((results) {
- var stdout = results[0].join("\n");
- stderr = results[1].join("\n");
-
- if (outputJson == null) {
- _validateOutput(failures, 'stdout', output, stdout);
- return null;
- }
-
- // Allow the expected JSON to contain futures.
- return awaitObject(outputJson).then((resolved) {
- _validateOutputJson(failures, 'stdout', resolved, stdout);
- });
- }).then((_) {
- _validateOutput(failures, 'stderr', error, stderr);
-
- if (!failures.isEmpty) throw new TestFailure(failures.join('\n'));
- }), completes);
-}
-
-/// Like [startPub], but runs `pub lish` in particular with [server] used both
-/// as the OAuth2 server (with "/token" as the token endpoint) and as the
-/// package server.
-///
-/// Any futures in [args] will be resolved before the process is started.
-ScheduledProcess startPublish(ScheduledServer server, {List args}) {
- var tokenEndpoint =
- server.url.then((url) => url.resolve('/token').toString());
- if (args == null) args = [];
- args = flatten(['lish', '--server', tokenEndpoint, args]);
- return startPub(args: args, tokenEndpoint: tokenEndpoint);
-}
-
-/// Handles the beginning confirmation process for uploading a packages.
-///
-/// Ensures that the right output is shown and then enters "y" to confirm the
-/// upload.
-void confirmPublish(ScheduledProcess pub) {
- // TODO(rnystrom): This is overly specific and inflexible regarding different
- // test packages. Should validate this a little more loosely.
- pub.stdout.expect(startsWith('Publishing test_pkg 1.0.0 to '));
- pub.stdout.expect(
- emitsLines(
- "|-- LICENSE\n" "|-- lib\n" "| '-- test_pkg.dart\n" "'-- pubspec.yaml\n" "\n"
- "Looks great! Are you ready to upload your package (y/n)?"));
- pub.writeLine("y");
-}
-
-/// Gets the absolute path to [relPath], which is a relative path in the test
-/// sandbox.
-String _pathInSandbox(String relPath) {
- return p.join(p.absolute(sandboxDir), relPath);
-}
-
-/// Gets the environment variables used to run pub in a test context.
-Future<Map> getPubTestEnvironment([String tokenEndpoint]) {
- final completer0 = new Completer();
- scheduleMicrotask(() {
- try {
- var environment = {};
- environment['_PUB_TESTING'] = 'true';
- environment['PUB_CACHE'] = _pathInSandbox(cachePath);
- environment['_PUB_TEST_SDK_VERSION'] = "0.1.2+3";
- join0() {
- join1() {
- completer0.complete(environment);
- }
- if (_hasServer) {
- completer0.complete(port.then(((p) {
- environment['PUB_HOSTED_URL'] = "http://localhost:$p";
- return environment;
- })));
- } else {
- join1();
- }
- }
- if (tokenEndpoint != null) {
- environment['_PUB_TEST_TOKEN_ENDPOINT'] = tokenEndpoint.toString();
- join0();
- } else {
- join0();
- }
- } catch (e, s) {
- completer0.completeError(e, s);
- }
- });
- return completer0.future;
-}
-
-/// Starts a Pub process and returns a [ScheduledProcess] that supports
-/// interaction with that process.
-///
-/// Any futures in [args] will be resolved before the process is started.
-///
-/// If [environment] is given, any keys in it will override the environment
-/// variables passed to the spawned process.
-ScheduledProcess startPub({List args, Future<String> tokenEndpoint, Map<String,
- String> environment}) {
- ensureDir(_pathInSandbox(appPath));
-
- // Find a Dart executable we can use to spawn. Use the same one that was
- // used to run this script itself.
- var dartBin = Platform.executable;
-
- // If the executable looks like a path, get its full path. That way we
- // can still find it when we spawn it with a different working directory.
- if (dartBin.contains(Platform.pathSeparator)) {
- dartBin = p.absolute(dartBin);
- }
-
- // Always run pub from a snapshot. Since we require the SDK to be built, the
- // snapshot should be there. Note that this *does* mean that the snapshot has
- // to be manually updated when changing code before running the tests.
- // Otherwise, you will test against stale data.
- //
- // Using the snapshot makes running the tests much faster, which is why we
- // make this trade-off.
- var pubPath = p.join(p.dirname(dartBin), 'snapshots/pub.dart.snapshot');
- var dartArgs = [pubPath, '--verbose'];
- dartArgs.addAll(args);
-
- if (tokenEndpoint == null) tokenEndpoint = new Future.value();
- var environmentFuture = tokenEndpoint.then(
- (tokenEndpoint) => getPubTestEnvironment(tokenEndpoint)).then((pubEnvironment) {
- if (environment != null) pubEnvironment.addAll(environment);
- return pubEnvironment;
- });
-
- return new PubProcess.start(
- dartBin,
- dartArgs,
- environment: environmentFuture,
- workingDirectory: _pathInSandbox(appPath),
- description: args.isEmpty ? 'pub' : 'pub ${args.first}');
-}
-
-/// A subclass of [ScheduledProcess] that parses pub's verbose logging output
-/// and makes [stdout] and [stderr] work as though pub weren't running in
-/// verbose mode.
-class PubProcess extends ScheduledProcess {
- Stream<Pair<log.Level, String>> _log;
- Stream<String> _stdout;
- Stream<String> _stderr;
-
- PubProcess.start(executable, arguments, {workingDirectory, environment,
- String description, Encoding encoding: UTF8})
- : super.start(
- executable,
- arguments,
- workingDirectory: workingDirectory,
- environment: environment,
- description: description,
- encoding: encoding);
-
- Stream<Pair<log.Level, String>> _logStream() {
- if (_log == null) {
- _log = mergeStreams(
- _outputToLog(super.stdoutStream(), log.Level.MESSAGE),
- _outputToLog(super.stderrStream(), log.Level.ERROR));
- }
-
- var pair = tee(_log);
- _log = pair.first;
- return pair.last;
- }
-
- final _logLineRegExp = new RegExp(r"^([A-Z ]{4})[:|] (.*)$");
- final _logLevels = [
- log.Level.ERROR,
- log.Level.WARNING,
- log.Level.MESSAGE,
- log.Level.IO,
- log.Level.SOLVER,
- log.Level.FINE].fold(<String, log.Level>{}, (levels, level) {
- levels[level.name] = level;
- return levels;
- });
-
- Stream<Pair<log.Level, String>> _outputToLog(Stream<String> stream,
- log.Level defaultLevel) {
- var lastLevel;
- return stream.map((line) {
- var match = _logLineRegExp.firstMatch(line);
- if (match == null) return new Pair<log.Level, String>(defaultLevel, line);
-
- var level = _logLevels[match[1]];
- if (level == null) level = lastLevel;
- lastLevel = level;
- return new Pair<log.Level, String>(level, match[2]);
- });
- }
-
- Stream<String> stdoutStream() {
- if (_stdout == null) {
- _stdout = _logStream().expand((entry) {
- if (entry.first != log.Level.MESSAGE) return [];
- return [entry.last];
- });
- }
-
- var pair = tee(_stdout);
- _stdout = pair.first;
- return pair.last;
- }
-
- Stream<String> stderrStream() {
- if (_stderr == null) {
- _stderr = _logStream().expand((entry) {
- if (entry.first != log.Level.ERROR &&
- entry.first != log.Level.WARNING) {
- return [];
- }
- return [entry.last];
- });
- }
-
- var pair = tee(_stderr);
- _stderr = pair.first;
- return pair.last;
- }
-}
-
-/// The path to the `packages` directory from which pub loads its dependencies.
-String get _packageRoot => p.absolute(Platform.packageRoot);
-
-/// Fails the current test if Git is not installed.
-///
-/// We require machines running these tests to have git installed. This
-/// validation gives an easier-to-understand error when that requirement isn't
-/// met than just failing in the middle of a test when pub invokes git.
-///
-/// This also increases the [Schedule] timeout to 30 seconds on Windows,
-/// where Git runs really slowly.
-void ensureGit() {
- if (Platform.operatingSystem == "windows") {
- currentSchedule.timeout = new Duration(seconds: 30);
- }
-
- if (!gitlib.isInstalled) {
- throw new Exception("Git must be installed to run this test.");
- }
-}
-
-/// Schedules activating a global package [package] without running
-/// "pub global activate".
-///
-/// This is useful because global packages must be hosted, but the test hosted
-/// server doesn't serve barback. The other parameters here follow
-/// [createLockFile].
-void makeGlobalPackage(String package, String version,
- Iterable<d.Descriptor> contents, {Iterable<String> pkg, Map<String,
- String> hosted}) {
- // Start the server so we know what port to use in the cache directory name.
- serveNoPackages();
-
- // Create the package in the hosted cache.
- d.hostedCache([d.dir("$package-$version", contents)]).create();
-
- var lockFile = _createLockFile(pkg: pkg, hosted: hosted);
-
- // Add the root package to the lockfile.
- var id =
- new PackageId(package, "hosted", new Version.parse(version), package);
- lockFile.packages[package] = id;
-
- // Write the lockfile to the global cache.
- var sources = new SourceRegistry();
- sources.register(new HostedSource());
- sources.register(new PathSource());
-
- d.dir(
- cachePath,
- [
- d.dir(
- "global_packages",
- [d.file("$package.lock", lockFile.serialize(null, sources))])]).create();
-}
-
-/// Creates a lock file for [package] without running `pub get`.
-///
-/// [sandbox] is a list of path dependencies to be found in the sandbox
-/// directory. [pkg] is a list of packages in the Dart repo's "pkg" directory;
-/// each package listed here and all its dependencies will be linked to the
-/// version in the Dart repo.
-///
-/// [hosted] is a list of package names to version strings for dependencies on
-/// hosted packages.
-void createLockFile(String package, {Iterable<String> sandbox,
- Iterable<String> pkg, Map<String, String> hosted}) {
- var lockFile = _createLockFile(sandbox: sandbox, pkg: pkg, hosted: hosted);
-
- var sources = new SourceRegistry();
- sources.register(new HostedSource());
- sources.register(new PathSource());
-
- d.file(
- p.join(package, 'pubspec.lock'),
- lockFile.serialize(null, sources)).create();
-}
-
-/// Creates a lock file for [package] without running `pub get`.
-///
-/// [sandbox] is a list of path dependencies to be found in the sandbox
-/// directory. [pkg] is a list of packages in the Dart repo's "pkg" directory;
-/// each package listed here and all its dependencies will be linked to the
-/// version in the Dart repo.
-///
-/// [hosted] is a list of package names to version strings for dependencies on
-/// hosted packages.
-LockFile _createLockFile({Iterable<String> sandbox, Iterable<String> pkg,
- Map<String, String> hosted}) {
- var dependencies = {};
-
- if (sandbox != null) {
- for (var package in sandbox) {
- dependencies[package] = '../$package';
- }
- }
-
- if (pkg != null) {
- _addPackage(String package) {
- if (dependencies.containsKey(package)) return;
-
- var path;
- if (package == 'barback' && _packageOverrides == null) {
- throw new StateError(
- "createLockFile() can only create a lock file "
- "with a barback dependency within a withBarbackVersions() " "block.");
- }
-
- if (_packageOverrides.containsKey(package)) {
- path = _packageOverrides[package];
- } else {
- path = packagePath(package);
- }
-
- dependencies[package] = path;
- var pubspec = loadYaml(readTextFile(p.join(path, 'pubspec.yaml')));
- var packageDeps = pubspec['dependencies'];
- if (packageDeps == null) return;
- packageDeps.keys.forEach(_addPackage);
- }
-
- pkg.forEach(_addPackage);
- }
-
- var lockFile = new LockFile.empty();
- dependencies.forEach((name, dependencyPath) {
- var id = new PackageId(name, 'path', new Version(0, 0, 0), {
- 'path': dependencyPath,
- 'relative': p.isRelative(dependencyPath)
- });
- lockFile.packages[name] = id;
- });
-
- if (hosted != null) {
- hosted.forEach((name, version) {
- var id = new PackageId(name, 'hosted', new Version.parse(version), name);
- lockFile.packages[name] = id;
- });
- }
-
- return lockFile;
-}
-
-/// Returns the path to [package] within the repo.
-String packagePath(String package) =>
- dirExists(p.join(repoRoot, 'pkg', package)) ?
- p.join(repoRoot, 'pkg', package) :
- p.join(repoRoot, 'third_party', 'pkg', package);
-
-/// Uses [client] as the mock HTTP client for this test.
-///
-/// Note that this will only affect HTTP requests made via http.dart in the
-/// parent process.
-void useMockClient(MockClient client) {
- var oldInnerClient = innerHttpClient;
- innerHttpClient = client;
- currentSchedule.onComplete.schedule(() {
- innerHttpClient = oldInnerClient;
- }, 'de-activating the mock client');
-}
-
-/// Describes a map representing a library package with the given [name],
-/// [version], and [dependencies].
-Map packageMap(String name, String version, [Map dependencies]) {
- var package = {
- "name": name,
- "version": version,
- "author": "Natalie Weizenbaum <nweiz@google.com>",
- "homepage": "http://pub.dartlang.org",
- "description": "A package, I guess."
- };
-
- if (dependencies != null) package["dependencies"] = dependencies;
-
- return package;
-}
-
-/// Resolves [target] relative to the path to pub's `test/asset` directory.
-String testAssetPath(String target) {
- var libPath = libraryPath('test_pub');
-
- // We are running from the generated directory, but non-dart assets are only
- // in the canonical directory.
- // TODO(rnystrom): Remove this when #104 is fixed.
- libPath = libPath.replaceAll('pub_generated', 'pub');
-
- return p.join(p.dirname(libPath), 'asset', target);
-}
-
-/// Returns a Map in the format used by the pub.dartlang.org API to represent a
-/// package version.
-///
-/// [pubspec] is the parsed pubspec of the package version. If [full] is true,
-/// this returns the complete map, including metadata that's only included when
-/// requesting the package version directly.
-Map packageVersionApiMap(Map pubspec, {bool full: false}) {
- var name = pubspec['name'];
- var version = pubspec['version'];
- var map = {
- 'pubspec': pubspec,
- 'version': version,
- 'url': '/api/packages/$name/versions/$version',
- 'archive_url': '/packages/$name/versions/$version.tar.gz',
- 'new_dartdoc_url': '/api/packages/$name/versions/$version' '/new_dartdoc',
- 'package_url': '/api/packages/$name'
- };
-
- if (full) {
- map.addAll({
- 'downloads': 0,
- 'created': '2012-09-25T18:38:28.685260',
- 'libraries': ['$name.dart'],
- 'uploader': ['nweiz@google.com']
- });
- }
-
- return map;
-}
-
-/// Returns the name of the shell script for a binstub named [name].
-///
-/// Adds a ".bat" extension on Windows.
-String binStubName(String name) => Platform.isWindows ? '$name.bat' : name;
-
-/// Compares the [actual] output from running pub with [expected].
-///
-/// If [expected] is a [String], ignores leading and trailing whitespace
-/// differences and tries to report the offending difference in a nice way.
-///
-/// If it's a [RegExp] or [Matcher], just reports whether the output matches.
-void _validateOutput(List<String> failures, String pipe, expected,
- String actual) {
- if (expected == null) return;
-
- if (expected is String) {
- _validateOutputString(failures, pipe, expected, actual);
- } else {
- if (expected is RegExp) expected = matches(expected);
- expect(actual, expected);
- }
-}
-
-void _validateOutputString(List<String> failures, String pipe, String expected,
- String actual) {
- var actualLines = actual.split("\n");
- var expectedLines = expected.split("\n");
-
- // Strip off the last line. This lets us have expected multiline strings
- // where the closing ''' is on its own line. It also fixes '' expected output
- // to expect zero lines of output, not a single empty line.
- if (expectedLines.last.trim() == '') {
- expectedLines.removeLast();
- }
-
- var results = [];
- var failed = false;
-
- // Compare them line by line to see which ones match.
- var length = max(expectedLines.length, actualLines.length);
- for (var i = 0; i < length; i++) {
- if (i >= actualLines.length) {
- // Missing output.
- failed = true;
- results.add('? ${expectedLines[i]}');
- } else if (i >= expectedLines.length) {
- // Unexpected extra output.
- failed = true;
- results.add('X ${actualLines[i]}');
- } else {
- var expectedLine = expectedLines[i].trim();
- var actualLine = actualLines[i].trim();
-
- if (expectedLine != actualLine) {
- // Mismatched lines.
- failed = true;
- results.add('X ${actualLines[i]}');
- } else {
- // Output is OK, but include it in case other lines are wrong.
- results.add('| ${actualLines[i]}');
- }
- }
- }
-
- // If any lines mismatched, show the expected and actual.
- if (failed) {
- failures.add('Expected $pipe:');
- failures.addAll(expectedLines.map((line) => '| $line'));
- failures.add('Got:');
- failures.addAll(results);
- }
-}
-
-/// Validates that [actualText] is a string of JSON that matches [expected],
-/// which may be a literal JSON object, or any other [Matcher].
-void _validateOutputJson(List<String> failures, String pipe, expected,
- String actualText) {
- var actual;
- try {
- actual = JSON.decode(actualText);
- } on FormatException catch (error) {
- failures.add('Expected $pipe JSON:');
- failures.add(expected);
- failures.add('Got invalid JSON:');
- failures.add(actualText);
- }
-
- // Match against the expectation.
- expect(actual, expected);
-}
-
-/// A function that creates a [Validator] subclass.
-typedef Validator ValidatorCreator(Entrypoint entrypoint);
-
-/// Schedules a single [Validator] to run on the [appPath].
-///
-/// Returns a scheduled Future that contains the errors and warnings produced
-/// by that validator.
-Future<Pair<List<String>, List<String>>>
- schedulePackageValidation(ValidatorCreator fn) {
- return schedule(() {
- var cache =
- new SystemCache.withSources(rootDir: p.join(sandboxDir, cachePath));
-
- return new Future.sync(() {
- var validator = fn(new Entrypoint(p.join(sandboxDir, appPath), cache));
- return validator.validate().then((_) {
- return new Pair(validator.errors, validator.warnings);
- });
- });
- }, "validating package");
-}
-
-/// A matcher that matches a Pair.
-Matcher pairOf(Matcher firstMatcher, Matcher lastMatcher) =>
- new _PairMatcher(firstMatcher, lastMatcher);
-
-class _PairMatcher extends Matcher {
- final Matcher _firstMatcher;
- final Matcher _lastMatcher;
-
- _PairMatcher(this._firstMatcher, this._lastMatcher);
-
- bool matches(item, Map matchState) {
- if (item is! Pair) return false;
- return _firstMatcher.matches(item.first, matchState) &&
- _lastMatcher.matches(item.last, matchState);
- }
-
- Description describe(Description description) {
- return description.addAll("(", ", ", ")", [_firstMatcher, _lastMatcher]);
- }
-}
-
-/// A [StreamMatcher] that matches multiple lines of output.
-StreamMatcher emitsLines(String output) => inOrder(output.split("\n"));
diff --git a/sdk/lib/_internal/pub_generated/test/transcript_test.dart b/sdk/lib/_internal/pub_generated/test/transcript_test.dart
deleted file mode 100644
index 34ea130..0000000
--- a/sdk/lib/_internal/pub_generated/test/transcript_test.dart
+++ /dev/null
@@ -1,60 +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 version_test;
-
-import 'package:unittest/unittest.dart';
-import 'test_pub.dart';
-import '../lib/src/transcript.dart';
-
-main() {
- initConfig();
-
- test("discards from the middle once it reaches the maximum", () {
- var transcript = new Transcript<String>(4);
- forEachToString() {
- var result = "";
- transcript.forEach((entry) => result += entry, (n) => result += "[$n]");
- return result;
- }
-
- expect(forEachToString(), equals(""));
- transcript.add("a");
- expect(forEachToString(), equals("a"));
- transcript.add("b");
- expect(forEachToString(), equals("ab"));
- transcript.add("c");
- expect(forEachToString(), equals("abc"));
- transcript.add("d");
- expect(forEachToString(), equals("abcd"));
- transcript.add("e");
- expect(forEachToString(), equals("ab[1]de"));
- transcript.add("f");
- expect(forEachToString(), equals("ab[2]ef"));
- });
-
- test("does not discard if it doesn't reach the maximum", () {
- var transcript = new Transcript<String>(40);
- forEachToString() {
- var result = "";
- transcript.forEach((entry) => result += entry, (n) => result += "[$n]");
- return result;
- }
-
- expect(forEachToString(), equals(""));
- transcript.add("a");
- expect(forEachToString(), equals("a"));
- transcript.add("b");
- expect(forEachToString(), equals("ab"));
- transcript.add("c");
- expect(forEachToString(), equals("abc"));
- transcript.add("d");
- expect(forEachToString(), equals("abcd"));
- transcript.add("e");
- expect(forEachToString(), equals("abcde"));
- transcript.add("f");
- expect(forEachToString(), equals("abcdef"));
- });
-
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/a_transformer_rejects_its_config_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/a_transformer_rejects_its_config_test.dart
deleted file mode 100644
index 0ee0f1f..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/a_transformer_rejects_its_config_test.dart
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const REJECT_CONFIG_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RejectConfigTransformer extends Transformer {
- RejectConfigTransformer.asPlugin(BarbackSettings settings) {
- throw "I hate these settings!";
- }
-
- Future<bool> isPrimary(_) => new Future.value(true);
- Future apply(Transform transform) {}
-}
-""";
-
-main() {
- initConfig();
-
- withBarbackVersions("any", () {
- integration("a transformer can reject is configuration", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- 'foo': 'bar'
- }
- }]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [d.file("transformer.dart", REJECT_CONFIG_TRANSFORMER)])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = startPubServe();
- pub.stderr.expect(
- endsWith('Error loading transformer: I hate these ' 'settings!'));
- pub.shouldExit(1);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/asset_not_found_exceptions_are_detectable_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/asset_not_found_exceptions_are_detectable_test.dart
deleted file mode 100644
index 12e3816..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/asset_not_found_exceptions_are_detectable_test.dart
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:convert';
-
-import 'package:scheduled_test/scheduled_stream.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-final transformer = """
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:barback/barback.dart';
-
-class GetInputTransformer extends Transformer {
- GetInputTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.readInputAsString(new AssetId('myapp', 'nonexistent'))
- .catchError((error) {
- if (error is! AssetNotFoundException) throw error;
- transform.addOutput(new Asset.fromString(transform.primaryInput.id,
- JSON.encode({
- 'package': error.id.package,
- 'path': error.id.path
- })));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("AssetNotFoundExceptions are detectable", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- requestShouldSucceed("foo.txt", JSON.encode({
- "package": "myapp",
- "path": "nonexistent"
- }));
- endPubServe();
-
- // Since the AssetNotFoundException was caught and handled, the server
- // shouldn't print any error information for it.
- server.stderr.expect(isDone);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/cache_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/cache_test.dart
deleted file mode 100644
index fada25d..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/cache_test.dart
+++ /dev/null
@@ -1,341 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const REPLACE_FROM_LIBRARY_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:bar/bar.dart';
-
-class ReplaceTransformer extends Transformer {
- ReplaceTransformer.asPlugin();
-
- String get allowedExtensions => '.dart';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- transform.addOutput(new Asset.fromString(
- transform.primaryInput.id,
- contents.replaceAll("Hello", replacement)));
- });
- }
-}
-""";
-
-// TODO(nweiz): Currently scheduled_test.setUp doesn't play well with test_pub,
-// since it only assigns the sandbox directory once the main test body has
-// run. Fix this and move this to a real setUp call.
-void setUp() {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any'
- },
- contents: [
- d.dir(
- "lib",
- [d.file("transformer.dart", replaceTransformer("Hello", "Goodbye"))])]);
-
- builder.serve("bar", "1.2.3", deps: {
- 'barback': 'any'
- },
- contents: [
- d.dir(
- "lib",
- [d.file("transformer.dart", replaceTransformer("Goodbye", "See ya"))])]);
-
- builder.serve("baz", "1.2.3");
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "1.2.3",
- "bar": "1.2.3"
- },
- "transformers": ["foo"]
- }),
- d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create();
-
- pubGet();
-}
-
-main() {
- initConfig();
-
- integration("caches a transformer snapshot", () {
- setUp();
-
- var process = pubRun(args: ['myapp']);
- process.stdout.expect("Goodbye!");
- process.shouldExit();
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/transformers",
- [
- d.file("manifest.txt", "0.1.2+3\nfoo"),
- d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate();
-
- // Run the executable again to make sure loading the transformer from the
- // cache works.
- process = pubRun(args: ['myapp']);
- process.stdout.expect("Goodbye!");
- process.shouldExit();
- });
-
- integration("recaches if the SDK version is out-of-date", () {
- setUp();
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/transformers",
- [// The version 0.0.1 is different than the test version 0.1.2+3.
- d.file("manifest.txt", "0.0.1\nfoo"),
- d.file("transformers.snapshot", "junk")])]).create();
-
- var process = pubRun(args: ['myapp']);
- process.stdout.expect("Goodbye!");
- process.shouldExit();
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/transformers",
- [
- d.file("manifest.txt", "0.1.2+3\nfoo"),
- d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate();
- });
-
- integration("recaches if the transformers change", () {
- setUp();
-
- var process = pubRun(args: ['myapp']);
- process.stdout.expect("Goodbye!");
- process.shouldExit();
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/transformers",
- [
- d.file("manifest.txt", "0.1.2+3\nfoo"),
- d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "1.2.3",
- "bar": "1.2.3"
- },
- "transformers": ["foo", "bar"]
- }),
- d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create();
-
- process = pubRun(args: ['myapp']);
- process.stdout.expect("See ya!");
- process.shouldExit();
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/transformers",
- [
- d.file("manifest.txt", "0.1.2+3\nbar,foo"),
- d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate();
- });
-
- integration("recaches if the transformer version changes", () {
- setUp();
-
- var process = pubRun(args: ['myapp']);
- process.stdout.expect("Goodbye!");
- process.shouldExit();
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/transformers",
- [
- d.file("manifest.txt", "0.1.2+3\nfoo"),
- d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate();
-
- servePackages((builder) {
- builder.serve("foo", "2.0.0", deps: {
- 'barback': 'any'
- },
- contents: [
- d.dir(
- "lib",
- [d.file("transformer.dart", replaceTransformer("Hello", "New"))])]);
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "any"
- },
- "transformers": ["foo"]
- })]).create();
-
- pubUpgrade();
-
- process = pubRun(args: ['myapp']);
- process.stdout.expect("New!");
- process.shouldExit();
-
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/transformers",
- [
- d.file("manifest.txt", "0.1.2+3\nfoo"),
- d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate();
- });
-
- integration("recaches if a transitive dependency version changes", () {
- servePackages((builder) {
- builder.serveRepoPackage('barback');
-
- builder.serve("foo", "1.2.3", deps: {
- 'barback': 'any',
- 'bar': 'any'
- },
- contents: [
- d.dir("lib", [d.file("transformer.dart", REPLACE_FROM_LIBRARY_TRANSFORMER)])]);
-
- builder.serve(
- "bar",
- "1.2.3",
- contents: [
- d.dir("lib", [d.file("bar.dart", "final replacement = 'Goodbye';")])]);
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "1.2.3"
- },
- "transformers": ["foo"]
- }),
- d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create();
-
- pubGet();
-
- var process = pubRun(args: ['myapp']);
- process.stdout.expect("Goodbye!");
- process.shouldExit();
-
- servePackages((builder) {
- builder.serve(
- "bar",
- "2.0.0",
- contents: [
- d.dir("lib", [d.file("bar.dart", "final replacement = 'See ya';")])]);
- });
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "any"
- },
- "transformers": ["foo"]
- })]).create();
-
- pubUpgrade();
-
- process = pubRun(args: ['myapp']);
- process.stdout.expect("See ya!");
- process.shouldExit();
- });
-
- // Issue 21298.
- integration("doesn't recache when a transformer is removed", () {
- setUp();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "1.2.3",
- "bar": "1.2.3"
- },
- "transformers": ["foo", "bar"]
- }),
- d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create();
-
- var process = pubRun(args: ['myapp']);
- process.stdout.expect("See ya!");
- process.shouldExit();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": "1.2.3",
- // Add a new dependency to trigger another "pub get". This works
- // around issue 20498.
- "baz": "1.2.3"
- },
- "transformers": ["foo"]
- }),
- d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create();
-
- process = pubRun(args: ['myapp']);
- process.stdout.expect(
- "Your pubspec has changed, so we need to update your lockfile:");
- process.stdout.expect(consumeThrough("Goodbye!"));
- process.shouldExit();
-
- // "bar" should still be in the manifest, since there's no reason to
- // recompile the cache.
- d.dir(
- appPath,
- [
- d.dir(
- ".pub/transformers",
- [
- d.file("manifest.txt", "0.1.2+3\nbar,foo"),
- d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate();
- });
-}
-
-String replaceTransformer(String input, String output) {
- return """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class ReplaceTransformer extends Transformer {
- ReplaceTransformer.asPlugin();
-
- String get allowedExtensions => '.dart';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- transform.addOutput(new Asset.fromString(
- transform.primaryInput.id,
- contents.replaceAll("$input", "$output")));
- });
- }
-}
-""";
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_log_messages_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_log_messages_test.dart
deleted file mode 100644
index ca37e51..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/can_log_messages_test.dart
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-import 'package:scheduled_test/scheduled_stream.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-const SOURCE_MAPS_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:source_maps/source_maps.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- transform.logger.info('info!');
- transform.logger.warning('Warning!',
- asset: transform.primaryInput.id.changeExtension('.foo'));
- var sourceFile = new SourceFile.text(
- 'http://fake.com/not_real.dart',
- 'not a real\\ndart file');
- transform.logger.error('ERROR!', span: new FileSpan(sourceFile, 11));
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, "\$contents.out"));
- });
- }
-}
-""";
-
-const SOURCE_SPAN_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:source_span/source_span.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- transform.logger.info('info!');
- transform.logger.warning('Warning!',
- asset: transform.primaryInput.id.changeExtension('.foo'));
- var sourceFile = new SourceFile('not a real\\ndart file',
- url: 'http://fake.com/not_real.dart');
- transform.logger.error('ERROR!', span: sourceFile.span(11, 12));
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, "\$contents.out"));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- // This intentionally tests barback 0.14.2 with both transformers, since it
- // supports both types of span.
- withBarbackVersions("<0.15.0", () => runTest(SOURCE_MAPS_TRANSFORMER));
- withBarbackVersions(">=0.14.2", () => runTest(SOURCE_SPAN_TRANSFORMER));
-}
-
-void runTest(String transformerText) {
- integration("can log messages", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformerText)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = startPub(args: ["build"]);
- pub.stdout.expect(startsWith("Loading source assets..."));
- pub.stdout.expect(consumeWhile(matches("Loading .* transformers...")));
- pub.stdout.expect(startsWith("Building myapp..."));
-
- pub.stdout.expect(emitsLines("""
-[Rewrite on myapp|web/foo.txt]:
-info!"""));
-
- pub.stderr.expect(emitsLines("""
-[Rewrite on myapp|web/foo.txt with input myapp|web/foo.foo]:
-Warning!
-[Rewrite on myapp|web/foo.txt]:"""));
-
- // The details of the analyzer's error message change pretty frequently,
- // so instead of validating the entire line, just look for a couple of
- // salient bits of information.
- pub.stderr.expect(allOf([contains("2"), // The line number.
- contains("1"), // The column number.
- contains("http://fake.com/not_real.dart"), // The library.
- contains("ERROR"), // That it's an error.
- ]));
-
- // In barback >=0.15.0, the span will point to the location where the error
- // occurred.
- pub.stderr.expect(allow(inOrder(["d", "^"])));
-
- pub.stderr.expect("Build failed.");
-
- pub.shouldExit(exit_codes.DATA);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_use_consume_primary_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_use_consume_primary_test.dart
deleted file mode 100644
index 0bb8314..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/can_use_consume_primary_test.dart
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- transform.consumePrimary();
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- var asset = new Asset.fromString(id, "\$contents.out");
- transform.addOutput(asset);
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("a transform can use consumePrimary", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- requestShould404("foo.txt");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_use_has_input_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_use_has_input_test.dart
deleted file mode 100644
index 93f4a6e..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/can_use_has_input_test.dart
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return Future.wait([
- transform.hasInput(transform.primaryInput.id),
- transform.hasInput(new AssetId('hooble', 'whatsit'))
- ]).then((results) {
- var id = transform.primaryInput.id.changeExtension(".out");
- var asset = new Asset.fromString(id,
- "primary: \${results[0]}, secondary: \${results[1]}");
- transform.addOutput(asset);
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("a transform can use hasInput", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "primary: true, secondary: false");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_as_string_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_as_string_test.dart
deleted file mode 100644
index 0e54201..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_as_string_test.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.readInputAsString(transform.primaryInput.id)
- .then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, "\$contents.out"));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("a transform can use readInputAsString", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_test.dart
deleted file mode 100644
index e54fb6c..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_test.dart
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.readInput(transform.primaryInput.id).toList()
- .then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- var asset = new Asset.fromString(id, "\$contents.out");
- transform.addOutput(asset);
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("a transform can use readInputAsString", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "[[102, 111, 111]].out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/configuration/configuration_defaults_to_empty_map_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/configuration/configuration_defaults_to_empty_map_test.dart
deleted file mode 100644
index 514676e..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/configuration/configuration_defaults_to_empty_map_test.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:convert';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-final transformer = """
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:barback/barback.dart';
-
-class ConfigTransformer extends Transformer {
- final BarbackSettings settings;
-
- ConfigTransformer.asPlugin(this.settings);
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".json");
- transform.addOutput(
- new Asset.fromString(id, JSON.encode(settings.configuration)));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("configuration defaults to an empty map", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- requestShouldSucceed("foo.json", JSON.encode({}));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/configuration/passes_configuration_to_a_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/configuration/passes_configuration_to_a_transformer_test.dart
deleted file mode 100644
index 94da357..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/configuration/passes_configuration_to_a_transformer_test.dart
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:convert';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-final transformer = """
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:barback/barback.dart';
-
-class ConfigTransformer extends Transformer {
- final BarbackSettings settings;
-
- ConfigTransformer.asPlugin(this.settings);
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".json");
- transform.addOutput(
- new Asset.fromString(id, JSON.encode(settings.configuration)));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("passes configuration to a transformer", () {
- var configuration = {
- "param": ["list", "of", "values"]
- };
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": configuration
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- requestShouldSucceed("foo.json", JSON.encode(configuration));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/configuration/with_configuration_only_instantiates_configurable_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/configuration/with_configuration_only_instantiates_configurable_transformers_test.dart
deleted file mode 100644
index db40874..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/configuration/with_configuration_only_instantiates_configurable_transformers_test.dart
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'dart:convert';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-final transformer = """
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:barback/barback.dart';
-
-class ConfigTransformer extends Transformer {
- final BarbackSettings settings;
-
- ConfigTransformer.asPlugin(this.settings);
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".json");
- transform.addOutput(
- new Asset.fromString(id, JSON.encode(settings.configuration)));
- });
- }
-}
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".out");
- transform.addOutput(new Asset.fromString(id, "\$contents.out"));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration(
- "with configuration, only instantiates configurable " "transformers",
- () {
- var configuration = {
- "param": ["list", "of", "values"]
- };
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": configuration
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- requestShouldSucceed("foo.json", JSON.encode(configuration));
- requestShould404("foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/dart2js_transformer_before_another_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/dart2js_transformer_before_another_transformer_test.dart
deleted file mode 100644
index 5be8957..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/dart2js_transformer_before_another_transformer_test.dart
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-// Regression test for issue 21726.
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("runs a dart2js transformer before a local transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [r"$dart2js", "myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/does_not_run_a_transform_on_an_input_in_another_package_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/does_not_run_a_transform_on_an_input_in_another_package_test.dart
deleted file mode 100644
index c1d9c7c..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/does_not_run_a_transform_on_an_input_in_another_package_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("does not run a transform on an input in another package", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "0.0.1",
- "transformers": ["foo/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.file("transformer.dart", REWRITE_TRANSFORMER),
- d.file("foo.txt", "foo")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }), d.dir("lib", [d.file("bar.txt", "bar")])]).create();
-
- createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']);
-
- pubServe();
- requestShould404("packages/myapp/bar.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_glob_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_glob_test.dart
deleted file mode 100644
index 9bf9100..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_glob_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("allows a glob to exclude", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$exclude": "**/foo.txt"
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("foo.txt", "foo"),
- d.file("bar.txt", "bar"),
- d.dir("sub", [d.file("foo.txt", "foo"),])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShould404("foo.out");
- requestShouldSucceed("bar.out", "bar.out");
- requestShould404("sub/foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_list_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_list_test.dart
deleted file mode 100644
index 0c2295a..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_list_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("excludes a list of assets", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$exclude": ["web/foo.txt", "web/sub/foo.txt"]
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("foo.txt", "foo"),
- d.file("bar.txt", "bar"),
- d.dir("sub", [d.file("foo.txt", "foo"),])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShould404("foo.out");
- requestShould404("sub/foo.out");
- requestShouldSucceed("bar.out", "bar.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_prefix_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_prefix_test.dart
deleted file mode 100644
index 12bbfd2c..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_prefix_test.dart
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("allows a directory prefix to exclude", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$exclude": "web/sub"
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("foo.txt", "foo"),
- d.file("bar.txt", "bar"),
- d.dir("sub", [d.file("foo.txt", "foo"),]),
- d.dir("subbub", [d.file("foo.txt", "foo"),])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- requestShouldSucceed("bar.out", "bar.out");
- requestShouldSucceed("subbub/foo.out", "foo.out");
- requestShould404("sub/foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_string_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_string_test.dart
deleted file mode 100644
index a7d92c0..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_string_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("allows a single string as the asset to exclude", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$exclude": "web/foo.txt"
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("foo.txt", "foo"),
- d.file("bar.txt", "bar"),
- d.dir("sub", [d.file("foo.txt", "foo"),])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShould404("foo.out");
- requestShouldSucceed("sub/foo.out", "foo.out");
- requestShouldSucceed("bar.out", "bar.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_glob_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_glob_test.dart
deleted file mode 100644
index 07a4702..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_glob_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("allows a glob to include", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$include": "**/foo.txt"
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("foo.txt", "foo"),
- d.file("bar.txt", "bar"),
- d.dir("sub", [d.file("foo.txt", "foo"),])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- requestShould404("bar.out");
- requestShouldSucceed("sub/foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_list_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_list_test.dart
deleted file mode 100644
index eb2d29c..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_list_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("includes assets", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$include": ["web/foo.txt", "web/sub/foo.txt"]
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("foo.txt", "foo"),
- d.file("bar.txt", "bar"),
- d.dir("sub", [d.file("foo.txt", "foo"),])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- requestShouldSucceed("sub/foo.out", "foo.out");
- requestShould404("bar.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_prefix_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_prefix_test.dart
deleted file mode 100644
index 22f2c7e..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_prefix_test.dart
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("allows a directory prefix to include", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$include": "web/sub"
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("foo.txt", "foo"),
- d.file("bar.txt", "bar"),
- d.dir("sub", [d.file("foo.txt", "foo"),]),
- d.dir("subbub", [d.file("foo.txt", "foo"),])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShould404("foo.out");
- requestShould404("bar.out");
- requestShouldSucceed("sub/foo.out", "foo.out");
- requestShould404("subbub/foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_string_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_string_test.dart
deleted file mode 100644
index 761c017..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_string_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("allows a single string as the asset to include", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$include": "web/foo.txt"
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("foo.txt", "foo"),
- d.file("bar.txt", "bar"),
- d.dir("sub", [d.file("foo.txt", "foo"),])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- requestShould404("sub/foo.out");
- requestShould404("bar.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/includes_before_excludes_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/includes_before_excludes_test.dart
deleted file mode 100644
index 6df3ca0..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/includes_before_excludes_test.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("applies includes before excludes if both are present", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- "\$include": ["web/a.txt", "web/b.txt"],
- "\$exclude": "web/a.txt"
- }
- }]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir(
- "web",
- [
- d.file("a.txt", "a.txt"),
- d.file("b.txt", "b.txt"),
- d.file("c.txt", "c.txt")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShould404("a.out");
- requestShouldSucceed("b.out", "b.txt.out");
- requestShould404("c.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_aggregate_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_aggregate_transformer_test.dart
deleted file mode 100644
index 436aa6e..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_aggregate_transformer_test.dart
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-const AGGREGATE_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-
-class ManyToOneTransformer extends AggregateTransformer {
- ManyToOneTransformer.asPlugin();
-
- String classifyPrimary(AssetId id) {
- if (id.extension != '.txt') return null;
- return p.url.dirname(id.path);
- }
-
- Future apply(AggregateTransform transform) {
- return transform.primaryInputs.toList().then((assets) {
- assets.sort((asset1, asset2) => asset1.id.path.compareTo(asset2.id.path));
- return Future.wait(assets.map((asset) => asset.readAsString()));
- }).then((contents) {
- var id = new AssetId(transform.package,
- p.url.join(transform.key, 'out.txt'));
- transform.addOutput(new Asset.fromString(id, contents.join('\\n')));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions(">=0.14.1", () {
- integration("works on an aggregate transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp": {
- "\$include": ["web/a.txt", "web/b.txt", "web/c.txt"],
- "\$exclude": "web/a.txt"
- }
- }]
- }),
- d.dir("lib", [d.file("transformer.dart", AGGREGATE_TRANSFORMER),]),
- d.dir(
- "web",
- [
- d.file("a.txt", "a"),
- d.file("b.txt", "b"),
- d.file("c.txt", "c"),
- d.file("d.txt", "d")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("out.txt", "b\nc");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_dart2js_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_dart2js_test.dart
deleted file mode 100644
index 31c7e2e..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_dart2js_test.dart
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("works on the dart2js transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "\$dart2js": {
- "\$include": ["web/a.dart", "web/b.dart"],
- "\$exclude": "web/a.dart"
- }
- }]
- }),
- d.dir(
- "web",
- [
- d.file("a.dart", "void main() => print('hello');"),
- d.file("b.dart", "void main() => print('hello');"),
- d.file("c.dart", "void main() => print('hello');")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- // Dart2js should remain lazy.
- server.stdout.expect("Build completed successfully");
-
- requestShould404("a.dart.js");
- requestShouldSucceed("b.dart.js", isNot(isEmpty));
- server.stdout.expect(
- consumeThrough(
- emitsLines("[Info from Dart2JS]:\n" "Compiling myapp|web/b.dart...")));
- server.stdout.expect(consumeThrough("Build completed successfully"));
-
- requestShould404("c.dart.js");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_lazy_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_lazy_transformer_test.dart
deleted file mode 100644
index 5fcdeea..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_lazy_transformer_test.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("works on a lazy transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp": {
- "\$include": ["web/a.txt", "web/b.txt"],
- "\$exclude": "web/a.txt"
- }
- }]
- }),
- d.dir("lib", [d.file("transformer.dart", LAZY_TRANSFORMER)]),
- d.dir(
- "web",
- [d.file("a.txt", "a"), d.file("b.txt", "b"), d.file("c.txt", "c")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- // The transformer should remain lazy.
- server.stdout.expect("Build completed successfully");
-
- requestShould404("a.out");
- requestShouldSucceed("b.out", isNot(isEmpty));
- server.stdout.expect(
- consumeThrough(
- emitsLines("[Info from LazyRewrite]:\n" "Rewriting myapp|web/b.txt.")));
- server.stdout.expect(consumeThrough("Build completed successfully"));
-
- requestShould404("c.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_transformer_group_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_transformer_group_test.dart
deleted file mode 100644
index f4d6acb..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_transformer_group_test.dart
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-import '../../serve/utils.dart';
-
-const GROUP = """
-import 'package:barback/barback.dart';
-
-import 'transformer.dart';
-
-class RewriteGroup implements TransformerGroup {
- RewriteGroup.asPlugin();
-
- Iterable<Iterable> get phases => [[new RewriteTransformer.asPlugin()]];
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("works on a transformer group", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/group": {
- "\$include": ["web/a.txt", "web/b.txt"],
- "\$exclude": "web/a.txt"
- }
- }]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [
- d.file("transformer.dart", REWRITE_TRANSFORMER),
- d.file("group.dart", GROUP)])]),
- d.dir(
- "web",
- [
- d.file("a.txt", "a.txt"),
- d.file("b.txt", "b.txt"),
- d.file("c.txt", "c.txt")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShould404("a.out");
- requestShouldSucceed("b.out", "b.txt.out");
- requestShould404("c.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_file_that_defines_no_transforms_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_file_that_defines_no_transforms_test.dart
deleted file mode 100644
index f4cddcb..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_file_that_defines_no_transforms_test.dart
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
-
- withBarbackVersions("any", () {
- integration("fails to load a file that defines no transforms", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/transformer"]
- }),
- d.dir("lib", [d.file("transformer.dart", "library does_nothing;")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = startPubServe();
- pub.stderr.expect(startsWith('No transformers were defined in '));
- pub.stderr.expect(startsWith('required by myapp.'));
- pub.shouldExit(1);
- pub.stderr.expect(never(contains('This is an unexpected error')));
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_non_existent_transform_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_non_existent_transform_test.dart
deleted file mode 100644
index 9388b09..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_non_existent_transform_test.dart
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("fails to load a non-existent transform", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/transform"]
- })]).create();
-
- var pub = startPubServe();
- pub.stderr.expect(
- 'Transformer library "package:myapp/transform.dart" not found.');
- pub.shouldExit(1);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_pubspec_with_reserved_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_pubspec_with_reserved_transformer_test.dart
deleted file mode 100644
index a9eebf3..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_pubspec_with_reserved_transformer_test.dart
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
-
- withBarbackVersions("any", () {
- integration("fails to load a pubspec with reserved transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["\$nonexistent"]
- }),
- d.dir(
- "lib",
- [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = startPubServe();
- pub.stderr.expect(
- contains(
- 'Invalid transformer config: Unsupported '
- 'built-in transformer \$nonexistent.'));
- pub.shouldExit(exit_codes.DATA);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_from_a_non_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_from_a_non_dependency_test.dart
deleted file mode 100644
index ba4ea1a..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_from_a_non_dependency_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/exit_codes.dart' as exit_codes;
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("fails to load a transform from a non-dependency", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["foo"]
- })]).create();
-
- var pub = startPubServe();
- pub.stderr.expect(contains('"foo" is not a dependency.'));
- pub.shouldExit(exit_codes.DATA);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_a_syntax_error_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_a_syntax_error_test.dart
deleted file mode 100644
index 4e5052c..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_a_syntax_error_test.dart
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
-
- // A syntax error will cause the analyzer to fail to parse the transformer
- // when attempting to rewrite its imports.
- withBarbackVersions("any", () {
- integration("fails to load a transform with a syntax error", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [d.dir("src", [d.file("transformer.dart", "syntax error")])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = startPubServe();
- pub.stderr.expect(contains("unexpected token 'syntax'"));
- pub.shouldExit(1);
- pub.stderr.expect(never(contains('This is an unexpected error')));
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_an_import_error_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_an_import_error_test.dart
deleted file mode 100644
index 3f68f63..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_an_import_error_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
-
- // An import error will cause the isolate API to fail synchronously while
- // loading the transformer.
- withBarbackVersions("any", () {
- integration("fails to load a transform with an import error", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [d.file("transformer.dart", "import 'does/not/exist.dart';")])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
- var pub = startPubServe();
- pub.stderr.expect("Unhandled exception:");
- pub.stderr.expect(
- startsWith("Uncaught Error: Load Error: Failure getting "));
- pub.shouldExit(1);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_an_unconfigurable_transformer_when_config_is_passed_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_an_unconfigurable_transformer_when_config_is_passed_test.dart
deleted file mode 100644
index 7c20db7..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_an_unconfigurable_transformer_when_config_is_passed_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
-
- withBarbackVersions("any", () {
- integration(
- "fails to load an unconfigurable transformer when config is " "passed",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "myapp/src/transformer": {
- 'foo': 'bar'
- }
- }]
- }),
- d.dir(
- "lib",
- [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var pub = startPubServe();
- pub.stderr.expect(
- startsWith('No transformers that accept configuration ' 'were defined in '));
- pub.shouldExit(1);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_declaring_aggregate_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_a_declaring_aggregate_transformer_test.dart
deleted file mode 100644
index 07bc966..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_declaring_aggregate_transformer_test.dart
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const AGGREGATE_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-
-class ManyToOneTransformer extends AggregateTransformer
- implements DeclaringAggregateTransformer {
- ManyToOneTransformer.asPlugin();
-
- String classifyPrimary(AssetId id) {
- if (id.extension != '.out') return null;
- return p.url.dirname(id.path);
- }
-
- Future apply(AggregateTransform transform) {
- return transform.primaryInputs.toList().then((assets) {
- assets.sort((asset1, asset2) => asset1.id.path.compareTo(asset2.id.path));
- return Future.wait(assets.map((asset) => asset.readAsString()));
- }).then((contents) {
- var id = new AssetId(transform.package,
- p.url.join(transform.key, 'out.final'));
- transform.addOutput(new Asset.fromString(id, contents.join('\\n')));
- });
- }
-
- void declareOutputs(DeclaringAggregateTransform transform) {
- transform.declareOutput(new AssetId(transform.package,
- p.url.join(transform.key, 'out.final')));
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions(">=0.14.1", () {
- integration("loads a declaring aggregate transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/lazy", "myapp/aggregate"]
- }),
- d.dir(
- "lib",
- [
- d.file("lazy.dart", LAZY_TRANSFORMER),
- d.file("aggregate.dart", AGGREGATE_TRANSFORMER),]),
- d.dir("web", [d.file("foo.txt", "foo"), d.file("bar.txt", "bar")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- // The transformer should preserve laziness.
- server.stdout.expect("Build completed successfully");
-
- requestShouldSucceed("out.final", "bar.out\nfoo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_diamond_transformer_dependency_graph_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_a_diamond_transformer_dependency_graph_test.dart
deleted file mode 100644
index 2a970fe..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_diamond_transformer_dependency_graph_test.dart
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("loads a diamond transformer dependency graph", () {
- d.dir("top", [d.pubspec({
- "name": "top",
- "version": "1.0.0"
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer('top')),])]).create();
-
- d.dir("left", [d.pubspec({
- "name": "left",
- "version": "1.0.0",
- "transformers": ["top/transformer"],
- "dependencies": {
- "top": {
- "path": "../top"
- }
- }
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer('left')),])]).create();
-
- d.dir("right", [d.pubspec({
- "name": "right",
- "version": "1.0.0",
- "transformers": ["top/transformer"],
- "dependencies": {
- "top": {
- "path": "../top"
- }
- }
- }),
- d.dir(
- "lib",
- [d.file("transformer.dart", dartTransformer('right')),])]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [
- "left/transformer",
- "right/transformer",
- "myapp/transformer"],
- "dependencies": {
- 'left': {
- 'path': '../left'
- },
- 'right': {
- 'path': '../right'
- },
- }
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer('myapp'))]),
- d.dir("web", [d.file("main.dart", 'const TOKEN = "main.dart";')])]).create();
-
- createLockFile(
- 'myapp',
- sandbox: ['top', 'left', 'right'],
- pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed(
- "main.dart",
- 'const TOKEN = "(((main.dart, (left, top)), (right, top)), ((myapp, '
- '(left, top)), (right, top)))";');
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_lazy_aggregate_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_a_lazy_aggregate_transformer_test.dart
deleted file mode 100644
index d377c44..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_lazy_aggregate_transformer_test.dart
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const AGGREGATE_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-
-class ManyToOneTransformer extends AggregateTransformer
- implements LazyAggregateTransformer {
- ManyToOneTransformer.asPlugin();
-
- String classifyPrimary(AssetId id) {
- if (id.extension != '.txt') return null;
- return p.url.dirname(id.path);
- }
-
- Future apply(AggregateTransform transform) {
- return transform.primaryInputs.toList().then((assets) {
- assets.sort((asset1, asset2) => asset1.id.path.compareTo(asset2.id.path));
- return Future.wait(assets.map((asset) => asset.readAsString()));
- }).then((contents) {
- var id = new AssetId(transform.package,
- p.url.join(transform.key, 'out.txt'));
- transform.addOutput(new Asset.fromString(id, contents.join('\\n')));
- });
- }
-
- void declareOutputs(DeclaringAggregateTransform transform) {
- transform.declareOutput(new AssetId(transform.package,
- p.url.join(transform.key, 'out.txt')));
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions(">=0.14.1", () {
- integration("loads a lazy aggregate transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp"]
- }),
- d.dir("lib", [d.file("transformer.dart", AGGREGATE_TRANSFORMER),]),
- d.dir("web", [d.file("foo.txt", "foo"), d.file("bar.txt", "bar")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- // The transformer should preserve laziness.
- server.stdout.expect("Build completed successfully");
-
- requestShouldSucceed("out.txt", "bar\nfoo");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_transformer_defined_in_an_exported_library_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_a_transformer_defined_in_an_exported_library_test.dart
deleted file mode 100644
index a443592..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_transformer_defined_in_an_exported_library_test.dart
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("loads a transformer defined in an exported library", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("myapp.dart", "export 'src/transformer.dart';"),
- d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_an_aggregate_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_an_aggregate_transformer_test.dart
deleted file mode 100644
index 6872b8d..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/loads_an_aggregate_transformer_test.dart
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const AGGREGATE_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-import 'package:path/path.dart' as p;
-
-class ManyToOneTransformer extends AggregateTransformer {
- ManyToOneTransformer.asPlugin();
-
- String classifyPrimary(AssetId id) {
- if (id.extension != '.txt') return null;
- return p.url.dirname(id.path);
- }
-
- Future apply(AggregateTransform transform) {
- return transform.primaryInputs.toList().then((assets) {
- assets.sort((asset1, asset2) => asset1.id.path.compareTo(asset2.id.path));
- return Future.wait(assets.map((asset) => asset.readAsString()));
- }).then((contents) {
- var id = new AssetId(transform.package,
- p.url.join(transform.key, 'out.txt'));
- transform.addOutput(new Asset.fromString(id, contents.join('\\n')));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions(">=0.14.1", () {
- integration("loads an aggregate transformer", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp"]
- }),
- d.dir("lib", [d.file("transformer.dart", AGGREGATE_TRANSFORMER),]),
- d.dir("web", [d.file("foo.txt", "foo"), d.file("bar.txt", "bar")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("out.txt", "bar\nfoo");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_different_configurations_from_the_same_isolate_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_different_configurations_from_the_same_isolate_test.dart
deleted file mode 100644
index fc28509..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/loads_different_configurations_from_the_same_isolate_test.dart
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("loads different configurations from the same isolate", () {
- // If different configurations are loaded from different isolates, a
- // transformer can end up being loaded twice. It's even possible for the
- // second load to use code that's transformed by the first, which is
- // really bad. This tests sets up such a scenario.
- //
- // The foo package has two self-transformers: foo/first and foo/second,
- // loaded in that order. This means that *no instances of foo/first*
- // should ever have their code transformed by foo/second.
- //
- // The myapp package also has a reference to foo/first. This reference has
- // a different configuration than foo's, which means that if it's loaded
- // in a separate isolate, it will be loaded after all of foo's
- // transformers have run. This means that foo/first.dart will have been
- // transformed by foo/first and foo/second, causing it to have different
- // code than the previous instance. This tests asserts that that doesn't
- // happen.
-
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0",
- "transformers": [{
- "foo/first": {
- "addition": " in foo"
- }
- }, "foo/second"]
- }),
- d.dir(
- "lib",
- [
- d.file("first.dart", dartTransformer('foo/first')),
- d.file("second.dart", dartTransformer('foo/second'))])]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [{
- "foo/first": {
- "addition": " in myapp",
- "\$include": "web/first.dart"
- }
- }, {
- "foo/second": {
- "\$include": "web/second.dart"
- }
- }],
- "dependencies": {
- 'foo': {
- 'path': '../foo'
- }
- }
- }),
- d.dir("web", [// This is transformed by foo/first. It's used to see which
- // transformers ran on foo/first.
- d.file("first.dart", 'const TOKEN = "myapp/first";'),
- // This is transformed by foo/second. It's used to see which
- // transformers ran on foo/second.
- d.file("second.dart", 'const TOKEN = "myapp/second";')])]).create();
-
- createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']);
-
- pubServe();
-
- // The version of foo/first used on myapp should have myapp's
- // configuration and shouldn't be transformed by foo/second.
- requestShouldSucceed(
- "first.dart",
- 'const TOKEN = "(myapp/first, foo/first in myapp)";');
-
- // foo/second should be transformed by only foo/first.
- requestShouldSucceed(
- "second.dart",
- 'const TOKEN = "(myapp/second, (foo/second, foo/first in foo))";');
-
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/multiple_transformers_reject_their_config_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/multiple_transformers_reject_their_config_test.dart
deleted file mode 100644
index 6a87bcb..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/multiple_transformers_reject_their_config_test.dart
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import 'package:scheduled_test/scheduled_stream.dart';
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const REJECT_CONFIG_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RejectConfigTransformer extends Transformer {
- RejectConfigTransformer.asPlugin(BarbackSettings settings) {
- throw "I hate these settings!";
- }
-
- Future<bool> isPrimary(_) => new Future.value(true);
- Future apply(Transform transform) {}
-}
-""";
-
-main() {
- initConfig();
-
- withBarbackVersions("any", () {
- integration(
- "multiple transformers in the same phase reject their " "configurations",
- () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": [[{
- "myapp/src/transformer": {
- 'foo': 'bar'
- }
- }, {
- "myapp/src/transformer": {
- 'baz': 'bang'
- }
- }, {
- "myapp/src/transformer": {
- 'qux': 'fblthp'
- }
- }]]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [d.file("transformer.dart", REJECT_CONFIG_TRANSFORMER)])])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- // We should see three instances of the error message, once for each
- // use of the transformer.
- var pub = startPubServe();
- for (var i = 0; i < 3; i++) {
- pub.stderr.expect(
- consumeThrough(
- endsWith('Error loading transformer: ' 'I hate these settings!')));
- }
- pub.shouldExit(1);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/prefers_transformer_to_library_name_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/prefers_transformer_to_library_name_test.dart
deleted file mode 100644
index 53b8132..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/prefers_transformer_to_library_name_test.dart
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const WRONG_TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) {
- return transform.primaryInput.readAsString().then((contents) {
- var id = transform.primaryInput.id.changeExtension(".wrong");
- transform.addOutput(new Asset.fromString(id, "\$contents.wrong"));
- });
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("prefers transformer.dart to <package name>.dart", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp"]
- }),
- d.dir(
- "lib",
- [
- d.file("transformer.dart", REWRITE_TRANSFORMER),
- d.file("myapp.dart", WRONG_TRANSFORMER)]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- requestShould404("foo.wrong");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_error_in_apply_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_error_in_apply_test.dart
deleted file mode 100644
index af11872..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_error_in_apply_test.dart
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-final transformer = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-
- Future apply(Transform transform) => throw new Exception('oh no!');
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("prints a transform error in apply", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- server.stderr.expect(
- emitsLines(
- 'Build error:\n' 'Transform Rewrite on myapp|web/foo.txt threw error: oh no!'));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_interface_error_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_interface_error_test.dart
deleted file mode 100644
index 4a661f6..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_interface_error_test.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-final transformer = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer {
- RewriteTransformer.asPlugin();
-
- String get allowedExtensions => '.txt';
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("prints a transform interface error", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- var server = pubServe();
- server.stderr.expect(
- emitsLines(
- "Build error:\n" "Transform Rewrite on myapp|web/foo.txt threw error: Class "
- "'RewriteTransformer' has no instance method 'apply'."));
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_local_transform_on_the_application_package_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_local_transform_on_the_application_package_test.dart
deleted file mode 100644
index 714d8fb..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_local_transform_on_the_application_package_test.dart
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("runs a local transform on the application package", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transform_on_the_application_package_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transform_on_the_application_package_test.dart
deleted file mode 100644
index 2dcc5eb..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transform_on_the_application_package_test.dart
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("runs a third-party transform on the application package", () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", '1.0.0'),
- d.dir("lib", [d.file("foo.dart", REWRITE_TRANSFORMER)])]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- },
- "transformers": ["foo"]
- }), d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transformer_on_a_local_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transformer_on_a_local_transformer_test.dart
deleted file mode 100644
index 0227502..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transformer_on_a_local_transformer_test.dart
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("runs a third-party transformer on a local transformer", () {
- d.dir(
- "foo",
- [
- d.libPubspec("foo", '1.0.0'),
- d.dir("lib", [d.file("transformer.dart", dartTransformer('foo'))])]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["foo/transformer", "myapp/transformer"],
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- }
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer('myapp'))]),
- d.dir("web", [d.file("main.dart", 'const TOKEN = "main.dart";')])]).create();
-
- createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed(
- "main.dart",
- 'const TOKEN = "((main.dart, foo), (myapp, foo))";');
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_group_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_group_test.dart
deleted file mode 100644
index bdf8814..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_group_test.dart
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const GROUP = """
-import 'package:barback/barback.dart';
-
-import 'transformer.dart';
-
-class RewriteGroup implements TransformerGroup {
- RewriteGroup.asPlugin();
-
- Iterable<Iterable> get phases => [[new RewriteTransformer.asPlugin()]];
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("runs a transformer group", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/group"]
- }),
- d.dir(
- "lib",
- [
- d.dir(
- "src",
- [
- d.file("transformer.dart", REWRITE_TRANSFORMER),
- d.file("group.dart", GROUP)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_on_a_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_on_a_dependency_test.dart
deleted file mode 100644
index c19f180..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_on_a_dependency_test.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("runs a local transformer on a dependency", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "0.0.1",
- "transformers": ["foo/transformer"]
- }),
- d.dir(
- "lib",
- [
- d.file("transformer.dart", REWRITE_TRANSFORMER),
- d.file("foo.txt", "foo")])]).create();
-
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- }),]).create();
-
- createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("packages/foo/foo.out", "foo.out");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_one_third_party_transformer_on_another_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_one_third_party_transformer_on_another_test.dart
deleted file mode 100644
index 3bc5722..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/runs_one_third_party_transformer_on_another_test.dart
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("runs one third-party transformer on another", () {
- d.dir("foo", [d.pubspec({
- "name": "foo",
- "version": "1.0.0"
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer('foo')),])]).create();
-
- d.dir("bar", [d.pubspec({
- "name": "bar",
- "version": "1.0.0",
- "transformers": ["foo/transformer"],
- "dependencies": {
- "foo": {
- "path": "../foo"
- }
- }
- }),
- d.dir("lib", [d.file("transformer.dart", dartTransformer('bar')),])]).create();
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["bar/transformer"],
- "dependencies": {
- 'bar': {
- 'path': '../bar'
- }
- }
- }),
- d.dir("web", [d.file("main.dart", 'const TOKEN = "main.dart";')])]).create();
-
- createLockFile('myapp', sandbox: ['foo', 'bar'], pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed(
- "main.dart",
- 'const TOKEN = "(main.dart, (bar, foo))";');
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/transformer/supports_a_transformer_that_doesnt_return_futures_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/supports_a_transformer_that_doesnt_return_futures_test.dart
deleted file mode 100644
index 4c14c5b..0000000
--- a/sdk/lib/_internal/pub_generated/test/transformer/supports_a_transformer_that_doesnt_return_futures_test.dart
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.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 pub_tests;
-
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import '../serve/utils.dart';
-
-const TRANSFORMER = """
-import 'dart:async';
-
-import 'package:barback/barback.dart';
-
-class RewriteTransformer extends Transformer implements DeclaringTransformer {
- RewriteTransformer.asPlugin();
-
- bool isPrimary(AssetId id) => id.extension == '.txt';
-
- void apply(Transform transform) {
- transform.addOutput(new Asset.fromString(
- transform.primaryInput.id, "new contents"));
- }
-
- void declareOutputs(DeclaringTransform transform) {
- transform.declareOutput(transform.primaryId);
- }
-}
-""";
-
-main() {
- initConfig();
- withBarbackVersions("any", () {
- integration("supports a transformer that doesn't return futures", () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "transformers": ["myapp/src/transformer"]
- }),
- d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]),
- d.dir("web", [d.file("foo.txt", "foo")])]).create();
-
- createLockFile('myapp', pkg: ['barback']);
-
- pubServe();
- requestShouldSucceed("foo.txt", "new contents");
- endPubServe();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/unknown_source_test.dart b/sdk/lib/_internal/pub_generated/test/unknown_source_test.dart
deleted file mode 100644
index e760a66..0000000
--- a/sdk/lib/_internal/pub_generated/test/unknown_source_test.dart
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS d.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 d.file.
-
-library pub_tests;
-
-import 'dart:convert';
-
-import 'descriptor.dart' as d;
-import 'test_pub.dart';
-
-main() {
- initConfig();
-
- forBothPubGetAndUpgrade((command) {
- integration('fails gracefully on a dependency from an unknown source', () {
- d.appDir({
- "foo": {
- "bad": "foo"
- }
- }).create();
-
- pubCommand(
- command,
- error: 'Package myapp depends on foo from unknown source "bad".');
- });
-
- integration(
- 'fails gracefully on transitive dependency from an unknown ' 'source',
- () {
- d.dir(
- 'foo',
- [d.libDir('foo', 'foo 0.0.1'), d.libPubspec('foo', '0.0.1', deps: {
- "bar": {
- "bad": "bar"
- }
- })]).create();
-
- d.appDir({
- "foo": {
- "path": "../foo"
- }
- }).create();
-
- pubCommand(
- command,
- error: 'Package foo depends on bar from unknown source "bad".');
- });
-
- integration('ignores unknown source in lockfile', () {
- d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1')]).create();
-
- // Depend on "foo" from a valid source.
- d.dir(appPath, [d.appPubspec({
- "foo": {
- "path": "../foo"
- }
- })]).create();
-
- // But lock it to a bad one.
- d.dir(appPath, [d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'foo': {
- 'version': '0.0.0',
- 'source': 'bad',
- 'description': {
- 'name': 'foo'
- }
- }
- }
- }))]).create();
-
- pubCommand(command);
-
- // Should upgrade to the new one.
- d.dir(
- packagesPath,
- [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])]).validate();
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/dry_run_does_not_apply_changes_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/dry_run_does_not_apply_changes_test.dart
deleted file mode 100644
index fe9ce8b..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/dry_run_does_not_apply_changes_test.dart
+++ /dev/null
@@ -1,48 +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:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/io.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-
-main() {
- initConfig();
- integration("--dry-run shows report but does not apply changes", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0");
- builder.serve("foo", "2.0.0");
- });
-
- // Create the first lockfile.
- d.appDir({
- "foo": "1.0.0"
- }).create();
-
- pubGet();
-
- // Change the pubspec.
- d.appDir({
- "foo": "any"
- }).create();
-
- // Also delete the "packages" directory.
- schedule(() {
- deleteEntry(path.join(sandboxDir, appPath, "packages"));
- });
-
- // Do the dry run.
- pubUpgrade(
- args: ["--dry-run"],
- output: allOf(
- [contains("> foo 2.0.0 (was 1.0.0)"), contains("Would change 1 dependency.")]));
-
- d.dir(appPath, [// The lockfile should be unmodified.
- d.matcherFile("pubspec.lock", contains("1.0.0")),
- // The "packages" directory should not have been regenerated.
- d.nothing("packages")]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/do_not_upgrade_if_unneeded_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/do_not_upgrade_if_unneeded_test.dart
deleted file mode 100644
index 458717f..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/git/do_not_upgrade_if_unneeded_test.dart
+++ /dev/null
@@ -1,64 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "doesn't upgrade one locked Git package's dependencies if it's "
- "not necessary",
- () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec("foo", "1.0.0", deps: {
- "foo-dep": {
- "git": "../foo-dep.git"
- }
- })]).create();
-
- d.git(
- 'foo-dep.git',
- [d.libDir('foo-dep'), d.libPubspec('foo-dep', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir('foo', [d.file('foo.dart', 'main() => "foo";')]),
- d.dir('foo-dep', [d.file('foo-dep.dart', 'main() => "foo-dep";')])]).validate();
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec("foo", "1.0.0", deps: {
- "foo-dep": {
- "git": "../foo-dep.git"
- }
- })]).create();
-
- d.git(
- 'foo-dep.git',
- [d.libDir('foo-dep', 'foo-dep 2'), d.libPubspec('foo-dep', '1.0.0')]).commit();
-
- pubUpgrade(args: ['foo']);
-
- d.dir(
- packagesPath,
- [
- d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')]),
- d.dir(
- 'foo-dep',
- [d.file('foo-dep.dart', 'main() => "foo-dep";')]),]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_locked_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_locked_test.dart
deleted file mode 100644
index e047cfb..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_locked_test.dart
+++ /dev/null
@@ -1,52 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("upgrades locked Git packages", () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.git('bar.git', [d.libDir('bar'), d.libPubspec('bar', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- },
- "bar": {
- "git": "../bar.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir('foo', [d.file('foo.dart', 'main() => "foo";')]),
- d.dir('bar', [d.file('bar.dart', 'main() => "bar";')])]).validate();
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- d.git(
- 'bar.git',
- [d.libDir('bar', 'bar 2'), d.libPubspec('bar', '1.0.0')]).commit();
-
- pubUpgrade();
-
- d.dir(
- packagesPath,
- [
- d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')]),
- d.dir('bar', [d.file('bar.dart', 'main() => "bar 2";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_one_locked_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_one_locked_test.dart
deleted file mode 100644
index a9e78ef..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_one_locked_test.dart
+++ /dev/null
@@ -1,52 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("upgrades one locked Git package but no others", () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.git('bar.git', [d.libDir('bar'), d.libPubspec('bar', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- },
- "bar": {
- "git": "../bar.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [
- d.dir('foo', [d.file('foo.dart', 'main() => "foo";')]),
- d.dir('bar', [d.file('bar.dart', 'main() => "bar";')])]).validate();
-
- d.git(
- 'foo.git',
- [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit();
-
- d.git(
- 'bar.git',
- [d.libDir('bar', 'bar 2'), d.libPubspec('bar', '1.0.0')]).commit();
-
- pubUpgrade(args: ['foo']);
-
- d.dir(
- packagesPath,
- [
- d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')]),
- d.dir('bar', [d.file('bar.dart', 'main() => "bar";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_incompatible_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_incompatible_pubspec_test.dart
deleted file mode 100644
index 0d48281..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_incompatible_pubspec_test.dart
+++ /dev/null
@@ -1,42 +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 pub_tests;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../../lib/src/exit_codes.dart' as exit_codes;
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("upgrades Git packages to an incompatible pubspec", () {
- ensureGit();
-
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- d.git('foo.git', [d.libDir('zoo'), d.libPubspec('zoo', '1.0.0')]).commit();
-
- pubUpgrade(
- error: contains('"name" field doesn\'t match expected name ' '"foo".'),
- exitCode: exit_codes.DATA);
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_nonexistent_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_nonexistent_pubspec_test.dart
deleted file mode 100644
index 0a74757..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_nonexistent_pubspec_test.dart
+++ /dev/null
@@ -1,42 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("upgrades Git packages to a nonexistent pubspec", () {
- ensureGit();
-
- var repo =
- d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]);
- repo.create();
-
- d.appDir({
- "foo": {
- "git": "../foo.git"
- }
- }).create();
-
- pubGet();
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
-
- repo.runGit(['rm', 'pubspec.yaml']);
- repo.runGit(['commit', '-m', 'delete']);
-
- pubUpgrade(
- error: new RegExp(
- r'Could not find a file named "pubspec.yaml" ' r'in "[^\n]*"\.'));
-
- d.dir(
- packagesPath,
- [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_dependers_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_dependers_test.dart
deleted file mode 100644
index 2d97532..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_dependers_test.dart
+++ /dev/null
@@ -1,48 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "upgrades a locked package's dependers in order to get it to max " "version",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "bar": "<2.0.0"
- });
- builder.serve("bar", "1.0.0");
- });
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0"
- }).validate();
-
- servePackages((builder) {
- builder.serve("foo", "2.0.0", deps: {
- "bar": "<3.0.0"
- });
- builder.serve("bar", "2.0.0");
- });
-
- pubUpgrade(args: ['bar']);
-
- d.packagesDir({
- "foo": "2.0.0",
- "bar": "2.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_if_necessary_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_if_necessary_test.dart
deleted file mode 100644
index fb68469..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_if_necessary_test.dart
+++ /dev/null
@@ -1,47 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "upgrades one locked pub server package's dependencies if it's " "necessary",
- () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "foo_dep": "any"
- });
- builder.serve("foo_dep", "1.0.0");
- });
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubGet();
-
- d.packagesDir({
- "foo": "1.0.0",
- "foo_dep": "1.0.0"
- }).validate();
-
- servePackages((builder) {
- builder.serve("foo", "2.0.0", deps: {
- "foo_dep": ">1.0.0"
- });
- builder.serve("foo_dep", "2.0.0");
- });
-
- pubUpgrade(args: ['foo']);
-
- d.packagesDir({
- "foo": "2.0.0",
- "foo_dep": "2.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/upgrade_removed_constraints_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/hosted/upgrade_removed_constraints_test.dart
deleted file mode 100644
index b5194dd..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/upgrade_removed_constraints_test.dart
+++ /dev/null
@@ -1,49 +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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("upgrades dependencies whose constraints have been removed", () {
- servePackages((builder) {
- builder.serve("foo", "1.0.0", deps: {
- "shared-dep": "any"
- });
- builder.serve("bar", "1.0.0", deps: {
- "shared-dep": "<2.0.0"
- });
- builder.serve("shared-dep", "1.0.0");
- builder.serve("shared-dep", "2.0.0");
- });
-
- d.appDir({
- "foo": "any",
- "bar": "any"
- }).create();
-
- pubUpgrade();
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": "1.0.0",
- "shared-dep": "1.0.0"
- }).validate();
-
- d.appDir({
- "foo": "any"
- }).create();
-
- pubUpgrade();
-
- d.packagesDir({
- "foo": "1.0.0",
- "bar": null,
- "shared-dep": "2.0.0"
- }).validate();
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/describes_change_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/describes_change_test.dart
deleted file mode 100644
index 45eace9..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/report/describes_change_test.dart
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) 2013, 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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("shows how package changed from previous lockfile", () {
- servePackages((builder) {
- builder.serve("unchanged", "1.0.0");
- builder.serve("version_changed", "1.0.0");
- builder.serve("version_changed", "2.0.0");
- builder.serve("source_changed", "1.0.0");
- });
-
- d.dir(
- "source_changed",
- [d.libDir("source_changed"), d.libPubspec("source_changed", "2.0.0")]).create();
-
- d.dir(
- "description_changed_1",
- [
- d.libDir("description_changed"),
- d.libPubspec("description_changed", "1.0.0")]).create();
-
- d.dir(
- "description_changed_2",
- [
- d.libDir("description_changed"),
- d.libPubspec("description_changed", "1.0.0")]).create();
-
- // Create the first lockfile.
- d.appDir({
- "unchanged": "any",
- "version_changed": "1.0.0",
- "source_changed": "any",
- "description_changed": {
- "path": "../description_changed_1"
- }
- }).create();
-
- pubGet();
-
- // Change the pubspec.
- d.appDir({
- "unchanged": "any",
- "version_changed": "any",
- "source_changed": {
- "path": "../source_changed"
- },
- "description_changed": {
- "path": "../description_changed_2"
- }
- }).create();
-
- // Upgrade everything.
- pubUpgrade(output: new RegExp(r"""
-Resolving dependencies\.\.\..*
-. description_changed 1\.0\.0 from path \.\.[/\\]description_changed_2 \(was 1\.0\.0 from path \.\.[/\\]description_changed_1\)
-. source_changed 2\.0\.0 from path \.\.[/\\]source_changed \(was 1\.0\.0\)
-. unchanged 1\.0\.0
-. version_changed 2\.0\.0 \(was 1\.0\.0\)
-""", multiLine: true));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/does_not_show_newer_versions_for_locked_packages_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/does_not_show_newer_versions_for_locked_packages_test.dart
deleted file mode 100644
index 034f902..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/report/does_not_show_newer_versions_for_locked_packages_test.dart
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) 2013, 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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "does not show how many newer versions are available for "
- "packages that are locked and not being upgraded",
- () {
- servePackages((builder) {
- builder.serve("not_upgraded", "1.0.0");
- builder.serve("not_upgraded", "2.0.0");
- builder.serve("not_upgraded", "3.0.0-dev");
- builder.serve("upgraded", "1.0.0");
- builder.serve("upgraded", "2.0.0");
- builder.serve("upgraded", "3.0.0-dev");
- });
-
- // Constraint everything to the first version.
- d.appDir({
- "not_upgraded": "1.0.0",
- "upgraded": "1.0.0"
- }).create();
-
- pubGet();
-
- // Loosen the constraints.
- d.appDir({
- "not_upgraded": "any",
- "upgraded": "any"
- }).create();
-
- // Only upgrade "upgraded".
- pubUpgrade(args: ["upgraded"], output: new RegExp(r"""
-Resolving dependencies\.\.\..*
- not_upgraded 1\.0\.0
-. upgraded 2\.0\.0 \(was 1\.0\.0\) \(3\.0\.0-dev available\)
-""", multiLine: true));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/highlights_overrides_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/highlights_overrides_test.dart
deleted file mode 100644
index 4b567f4..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/report/highlights_overrides_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, 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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("highlights overridden packages", () {
- servePackages((builder) => builder.serve("overridden", "1.0.0"));
-
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependency_overrides": {
- "overridden": "any"
- }
- })]).create();
-
- // Upgrade everything.
- pubUpgrade(output: new RegExp(r"""
-Resolving dependencies\.\.\..*
-! overridden 1\.0\.0 \(overridden\)
-""", multiLine: true));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/leading_character_shows_change_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/leading_character_shows_change_test.dart
deleted file mode 100644
index bb567c2..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/report/leading_character_shows_change_test.dart
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright (c) 2013, 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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("the character before each package describes the change", () {
- servePackages((builder) {
- builder.serve("added", "1.0.0");
- builder.serve("downgraded", "1.0.0");
- builder.serve("downgraded", "2.0.0");
- builder.serve("overridden", "1.0.0");
- builder.serve("removed", "1.0.0");
- builder.serve("source_changed", "1.0.0");
- builder.serve("upgraded", "1.0.0");
- builder.serve("upgraded", "2.0.0");
- builder.serve("unchanged", "1.0.0");
- });
-
- d.dir(
- "description_changed_1",
- [
- d.libDir("description_changed"),
- d.libPubspec("description_changed", "1.0.0")]).create();
-
- d.dir(
- "description_changed_2",
- [
- d.libDir("description_changed"),
- d.libPubspec("description_changed", "1.0.0")]).create();
-
- d.dir(
- "source_changed",
- [d.libDir("source_changed"), d.libPubspec("source_changed", "1.0.0")]).create();
-
- // Create the first lockfile.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "description_changed": {
- "path": "../description_changed_1"
- },
- "downgraded": "2.0.0",
- "removed": "any",
- "source_changed": "any",
- "unchanged": "any",
- "upgraded": "1.0.0"
- },
- "dependency_overrides": {
- "overridden": "any"
- }
- })]).create();
-
- pubGet();
-
- // Change the pubspec.
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependencies": {
- "added": "any",
- "description_changed": {
- "path": "../description_changed_2"
- },
- "downgraded": "1.0.0",
- "source_changed": {
- "path": "../source_changed"
- },
- "unchanged": "any",
- "upgraded": "2.0.0"
- },
- "dependency_overrides": {
- "overridden": "any"
- }
- })]).create();
-
- // Upgrade everything.
- pubUpgrade(output: new RegExp(r"""
-Resolving dependencies\.\.\..*
-\+ added .*
-\* description_changed .*
-< downgraded .*
-! overridden .*
-\* source_changed .*
- unchanged .*
-> upgraded .*
-These packages are no longer being depended on:
-- removed .*
-""", multiLine: true));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_newer_available_versions_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_newer_available_versions_test.dart
deleted file mode 100644
index 9936447..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_newer_available_versions_test.dart
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright (c) 2013, 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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration("shows how many newer versions are available", () {
- servePackages((builder) {
- builder.serve("multiple_newer", "1.0.0");
- builder.serve("multiple_newer", "1.0.1-unstable.1");
- builder.serve("multiple_newer", "1.0.1");
- builder.serve("multiple_newer", "1.0.2-unstable.1");
- builder.serve("multiple_newer_stable", "1.0.0");
- builder.serve("multiple_newer_stable", "1.0.1");
- builder.serve("multiple_newer_stable", "1.0.2");
- builder.serve("multiple_newer_unstable", "1.0.0");
- builder.serve("multiple_newer_unstable", "1.0.1-unstable.1");
- builder.serve("multiple_newer_unstable", "1.0.1-unstable.2");
- builder.serve("no_newer", "1.0.0");
- builder.serve("one_newer_unstable", "1.0.0");
- builder.serve("one_newer_unstable", "1.0.1-unstable.1");
- builder.serve("one_newer_stable", "1.0.0");
- builder.serve("one_newer_stable", "1.0.1");
- });
-
- // Constraint everything to the first version.
- d.appDir({
- "multiple_newer": "1.0.0",
- "multiple_newer_stable": "1.0.0",
- "multiple_newer_unstable": "1.0.0",
- "no_newer": "1.0.0",
- "one_newer_unstable": "1.0.0",
- "one_newer_stable": "1.0.0"
- }).create();
-
- // Upgrade everything.
- pubUpgrade(output: new RegExp(r"""
-Resolving dependencies\.\.\..*
-. multiple_newer 1\.0\.0 \(1\.0\.1 available\)
-. multiple_newer_stable 1\.0\.0 \(1\.0\.2\ available\)
-. multiple_newer_unstable 1\.0\.0 \(1\.0\.1-unstable\.2 available\)
-. no_newer 1\.0\.0
-. one_newer_stable 1\.0\.0 \(1\.0\.1 available\)
-. one_newer_unstable 1\.0\.0 \(1\.0\.1-unstable\.1 available\)
-""", multiLine: true));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_number_of_changed_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_number_of_changed_dependencies_test.dart
deleted file mode 100644
index 2d0b6d7..0000000
--- a/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_number_of_changed_dependencies_test.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2013, 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 pub_tests;
-
-import '../../descriptor.dart' as d;
-import '../../test_pub.dart';
-
-main() {
- initConfig();
- integration(
- "does not show how many newer versions are available for "
- "packages that are locked and not being upgraded",
- () {
- servePackages((builder) {
- builder.serve("a", "1.0.0");
- builder.serve("b", "1.0.0");
- builder.serve("c", "2.0.0");
- });
-
- d.appDir({
- "a": "any"
- }).create();
-
- // One dependency changed.
- pubUpgrade(output: new RegExp(r"Changed 1 dependency!$"));
-
- // Remove one and add two.
- d.appDir({
- "b": "any",
- "c": "any"
- }).create();
-
- pubUpgrade(output: new RegExp(r"Changed 3 dependencies!$"));
-
- // Don't change anything.
- pubUpgrade(output: new RegExp(r"No dependencies changed.$"));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/utils_test.dart b/sdk/lib/_internal/pub_generated/test/utils_test.dart
deleted file mode 100644
index 178b7f7..0000000
--- a/sdk/lib/_internal/pub_generated/test/utils_test.dart
+++ /dev/null
@@ -1,105 +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 utils_test;
-
-import 'package:unittest/unittest.dart';
-import 'test_pub.dart';
-import '../lib/src/utils.dart';
-
-main() {
- initConfig();
-
- group('yamlToString()', () {
- test('null', () {
- expect(yamlToString(null), equals('null'));
- });
-
- test('numbers', () {
- expect(yamlToString(123), equals('123'));
- expect(yamlToString(12.34), equals('12.34'));
- });
-
- test('does not quote strings that do not need it', () {
- expect(yamlToString('a'), equals('a'));
- expect(yamlToString('some-string'), equals('some-string'));
- expect(yamlToString('hey123CAPS'), equals('hey123CAPS'));
- expect(yamlToString("_under_score"), equals('_under_score'));
- });
-
- test('quotes other strings', () {
- expect(yamlToString(''), equals('""'));
- expect(yamlToString('123'), equals('"123"'));
- expect(yamlToString('white space'), equals('"white space"'));
- expect(yamlToString('"quote"'), equals(r'"\"quote\""'));
- expect(yamlToString("apostrophe'"), equals('"apostrophe\'"'));
- expect(yamlToString("new\nline"), equals(r'"new\nline"'));
- expect(yamlToString("?unctu@t!on"), equals(r'"?unctu@t!on"'));
- });
-
- test('lists use JSON style', () {
- expect(yamlToString([1, 2, 3]), equals('[1,2,3]'));
- });
-
- test('uses indentation for maps', () {
- expect(yamlToString({
- 'a': {
- 'b': 1,
- 'c': 2
- },
- 'd': 3
- }), equals("""
-a:
- b: 1
- c: 2
-d: 3"""));
- });
-
- test('sorts map keys', () {
- expect(yamlToString({
- 'a': 1,
- 'c': 2,
- 'b': 3,
- 'd': 4
- }), equals("""
-a: 1
-b: 3
-c: 2
-d: 4"""));
- });
-
- test('quotes map keys as needed', () {
- expect(yamlToString({
- 'no': 1,
- 'yes!': 2,
- '123': 3
- }), equals("""
-"123": 3
-no: 1
-"yes!": 2"""));
- });
-
- test('handles non-string map keys', () {
- var map = new Map();
- map[null] = "null";
- map[123] = "num";
- map[true] = "bool";
-
- expect(yamlToString(map), equals("""
-123: num
-null: null
-true: bool"""));
- });
-
- test('handles empty maps', () {
- expect(yamlToString({}), equals("{}"));
- expect(yamlToString({
- 'a': {},
- 'b': {}
- }), equals("""
-a: {}
-b: {}"""));
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/compiled_dartdoc_test.dart b/sdk/lib/_internal/pub_generated/test/validator/compiled_dartdoc_test.dart
deleted file mode 100644
index cd0599d..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/compiled_dartdoc_test.dart
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/compiled_dartdoc.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator compiledDartdoc(Entrypoint entrypoint) =>
- new CompiledDartdocValidator(entrypoint);
-
-main() {
- initConfig();
-
- group('should consider a package valid if it', () {
- setUp(d.validPackage.create);
-
- integration('looks normal', () => expectNoValidationError(compiledDartdoc));
-
- integration('has most but not all files from compiling dartdoc', () {
- d.dir(
- appPath,
- [
- d.dir(
- "doc-out",
- [
- d.file("nav.json", ""),
- d.file("index.html", ""),
- d.file("styles.css", ""),
- d.file("dart-logo-small.png", "")])]).create();
- expectNoValidationError(compiledDartdoc);
- });
-
- integration('contains compiled dartdoc in a hidden directory', () {
- ensureGit();
-
- d.dir(
- appPath,
- [
- d.dir(
- ".doc-out",
- [
- d.file('nav.json', ''),
- d.file('index.html', ''),
- d.file('styles.css', ''),
- d.file('dart-logo-small.png', ''),
- d.file('client-live-nav.js', '')])]).create();
- expectNoValidationError(compiledDartdoc);
- });
-
- integration('contains compiled dartdoc in a gitignored directory', () {
- ensureGit();
-
- d.git(
- appPath,
- [
- d.dir(
- "doc-out",
- [
- d.file('nav.json', ''),
- d.file('index.html', ''),
- d.file('styles.css', ''),
- d.file('dart-logo-small.png', ''),
- d.file('client-live-nav.js', '')]),
- d.file(".gitignore", "/doc-out")]).create();
- expectNoValidationError(compiledDartdoc);
- });
- });
-
- group("should consider a package invalid if it", () {
- integration('contains compiled dartdoc', () {
- d.validPackage.create();
-
- d.dir(
- appPath,
- [
- d.dir(
- 'doc-out',
- [
- d.file('nav.json', ''),
- d.file('index.html', ''),
- d.file('styles.css', ''),
- d.file('dart-logo-small.png', ''),
- d.file('client-live-nav.js', '')])]).create();
-
- expectValidationWarning(compiledDartdoc);
- });
-
- integration(
- 'contains compiled dartdoc in a non-gitignored hidden ' 'directory',
- () {
- ensureGit();
-
- d.validPackage.create();
-
- d.git(
- appPath,
- [
- d.dir(
- '.doc-out',
- [
- d.file('nav.json', ''),
- d.file('index.html', ''),
- d.file('styles.css', ''),
- d.file('dart-logo-small.png', ''),
- d.file('client-live-nav.js', '')])]).create();
-
- expectValidationWarning(compiledDartdoc);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/dependency_override_test.dart b/sdk/lib/_internal/pub_generated/test/validator/dependency_override_test.dart
deleted file mode 100644
index 75a64f7b..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/dependency_override_test.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013, 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 '../../lib/src/entrypoint.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/dependency_override.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator dependencyOverride(Entrypoint entrypoint) =>
- new DependencyOverrideValidator(entrypoint);
-
-main() {
- initConfig();
-
- integration('invalidates a package if it has dependency overrides', () {
- d.dir(appPath, [d.pubspec({
- "name": "myapp",
- "dependency_overrides": {
- "foo": "<3.0.0"
- }
- })]).create();
-
- expectValidationError(dependencyOverride);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/dependency_test.dart b/sdk/lib/_internal/pub_generated/test/validator/dependency_test.dart
deleted file mode 100644
index 689fc66..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/dependency_test.dart
+++ /dev/null
@@ -1,411 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:http/http.dart' as http;
-import 'package:http/testing.dart';
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/dependency.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator dependency(Entrypoint entrypoint) =>
- new DependencyValidator(entrypoint);
-
-expectDependencyValidationError(String error) {
- expect(
- schedulePackageValidation(dependency),
- completion(pairOf(anyElement(contains(error)), isEmpty)));
-}
-
-expectDependencyValidationWarning(String warning) {
- expect(
- schedulePackageValidation(dependency),
- completion(pairOf(isEmpty, anyElement(contains(warning)))));
-}
-
-/// Sets up a test package with dependency [dep] and mocks a server with
-/// [hostedVersions] of the package available.
-setUpDependency(Map dep, {List<String> hostedVersions}) {
- useMockClient(new MockClient((request) {
- expect(request.method, equals("GET"));
- expect(request.url.path, equals("/api/packages/foo"));
-
- if (hostedVersions == null) {
- return new Future.value(new http.Response("not found", 404));
- } else {
- return new Future.value(new http.Response(JSON.encode({
- "name": "foo",
- "uploaders": ["nweiz@google.com"],
- "versions": hostedVersions.map(
- (version) => packageVersionApiMap(packageMap('foo', version))).toList()
- }), 200));
- }
- }));
-
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": dep
- })]).create();
-}
-
-main() {
- initConfig();
-
- group('should consider a package valid if it', () {
- integration('looks normal', () {
- d.validPackage.create();
- expectNoValidationError(dependency);
- });
-
- integration('has a ^ constraint with an appropriate SDK constraint', () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "^1.2.3"
- }, sdk: ">=1.8.0 <2.0.0")]).create();
- expectNoValidationError(dependency);
- });
- });
-
- group('should consider a package invalid if it', () {
- setUp(d.validPackage.create);
-
- group('has a git dependency', () {
- group('where a hosted version exists', () {
- integration("and should suggest the hosted primary version", () {
- setUpDependency({
- 'git': 'git://github.com/dart-lang/foo'
- }, hostedVersions: ["3.0.0-pre", "2.0.0", "1.0.0"]);
- expectDependencyValidationWarning(' foo: ">=2.0.0 <3.0.0"');
- });
-
- integration(
- "and should suggest the hosted prerelease version if "
- "it's the only version available",
- () {
- setUpDependency({
- 'git': 'git://github.com/dart-lang/foo'
- }, hostedVersions: ["3.0.0-pre", "2.0.0-pre"]);
- expectDependencyValidationWarning(' foo: ">=3.0.0-pre <4.0.0"');
- });
-
- integration(
- "and should suggest a tighter constraint if primary is " "pre-1.0.0",
- () {
- setUpDependency({
- 'git': 'git://github.com/dart-lang/foo'
- }, hostedVersions: ["0.0.1", "0.0.2"]);
- expectDependencyValidationWarning(' foo: ">=0.0.2 <0.1.0"');
- });
- });
-
- group('where no hosted version exists', () {
- integration("and should use the other source's version", () {
- setUpDependency({
- 'git': 'git://github.com/dart-lang/foo',
- 'version': '>=1.0.0 <2.0.0'
- });
- expectDependencyValidationWarning(' foo: ">=1.0.0 <2.0.0"');
- });
-
- integration(
- "and should use the other source's unquoted version if " "concrete",
- () {
- setUpDependency({
- 'git': 'git://github.com/dart-lang/foo',
- 'version': '0.2.3'
- });
- expectDependencyValidationWarning(' foo: 0.2.3');
- });
- });
- });
-
- group('has a path dependency', () {
- group('where a hosted version exists', () {
- integration("and should suggest the hosted primary version", () {
- setUpDependency({
- 'path': path.join(sandboxDir, 'foo')
- }, hostedVersions: ["3.0.0-pre", "2.0.0", "1.0.0"]);
- expectDependencyValidationError(' foo: ">=2.0.0 <3.0.0"');
- });
-
- integration(
- "and should suggest the hosted prerelease version if "
- "it's the only version available",
- () {
- setUpDependency({
- 'path': path.join(sandboxDir, 'foo')
- }, hostedVersions: ["3.0.0-pre", "2.0.0-pre"]);
- expectDependencyValidationError(' foo: ">=3.0.0-pre <4.0.0"');
- });
-
- integration(
- "and should suggest a tighter constraint if primary is " "pre-1.0.0",
- () {
- setUpDependency({
- 'path': path.join(sandboxDir, 'foo')
- }, hostedVersions: ["0.0.1", "0.0.2"]);
- expectDependencyValidationError(' foo: ">=0.0.2 <0.1.0"');
- });
- });
-
- group('where no hosted version exists', () {
- integration("and should use the other source's version", () {
- setUpDependency({
- 'path': path.join(sandboxDir, 'foo'),
- 'version': '>=1.0.0 <2.0.0'
- });
- expectDependencyValidationError(' foo: ">=1.0.0 <2.0.0"');
- });
-
- integration(
- "and should use the other source's unquoted version if " "concrete",
- () {
- setUpDependency({
- 'path': path.join(sandboxDir, 'foo'),
- 'version': '0.2.3'
- });
- expectDependencyValidationError(' foo: 0.2.3');
- });
- });
- });
-
- group('has an unconstrained dependency', () {
- group('and it should not suggest a version', () {
- integration("if there's no lockfile", () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "any"
- })]).create();
-
- expect(
- schedulePackageValidation(dependency),
- completion(pairOf(isEmpty, everyElement(isNot(contains("\n foo:"))))));
- });
-
- integration(
- "if the lockfile doesn't have an entry for the " "dependency",
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "any"
- }), d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'bar': {
- 'version': '1.2.3',
- 'source': 'hosted',
- 'description': {
- 'name': 'bar',
- 'url': 'http://pub.dartlang.org'
- }
- }
- }
- }))]).create();
-
- expect(
- schedulePackageValidation(dependency),
- completion(pairOf(isEmpty, everyElement(isNot(contains("\n foo:"))))));
- });
- });
-
- group('with a lockfile', () {
- integration(
- 'and it should suggest a constraint based on the locked ' 'version',
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "any"
- }), d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'foo': {
- 'version': '1.2.3',
- 'source': 'hosted',
- 'description': {
- 'name': 'foo',
- 'url': 'http://pub.dartlang.org'
- }
- }
- }
- }))]).create();
-
- expectDependencyValidationWarning(' foo: ">=1.2.3 <2.0.0"');
- });
-
- integration(
- 'and it should suggest a concrete constraint if the locked '
- 'version is pre-1.0.0',
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "any"
- }), d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'foo': {
- 'version': '0.1.2',
- 'source': 'hosted',
- 'description': {
- 'name': 'foo',
- 'url': 'http://pub.dartlang.org'
- }
- }
- }
- }))]).create();
-
- expectDependencyValidationWarning(' foo: ">=0.1.2 <0.2.0"');
- });
- });
- });
-
- integration(
- 'with a single-version dependency and it should suggest a '
- 'constraint based on the version',
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "1.2.3"
- })]).create();
-
- expectDependencyValidationWarning(' foo: ">=1.2.3 <2.0.0"');
- });
-
- group('has a dependency without a lower bound', () {
- group('and it should not suggest a version', () {
- integration("if there's no lockfile", () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "<3.0.0"
- })]).create();
-
- expect(
- schedulePackageValidation(dependency),
- completion(pairOf(isEmpty, everyElement(isNot(contains("\n foo:"))))));
- });
-
- integration(
- "if the lockfile doesn't have an entry for the " "dependency",
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "<3.0.0"
- }), d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'bar': {
- 'version': '1.2.3',
- 'source': 'hosted',
- 'description': {
- 'name': 'bar',
- 'url': 'http://pub.dartlang.org'
- }
- }
- }
- }))]).create();
-
- expect(
- schedulePackageValidation(dependency),
- completion(pairOf(isEmpty, everyElement(isNot(contains("\n foo:"))))));
- });
- });
-
- group('with a lockfile', () {
- integration(
- 'and it should suggest a constraint based on the locked ' 'version',
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "<3.0.0"
- }), d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'foo': {
- 'version': '1.2.3',
- 'source': 'hosted',
- 'description': {
- 'name': 'foo',
- 'url': 'http://pub.dartlang.org'
- }
- }
- }
- }))]).create();
-
- expectDependencyValidationWarning(' foo: ">=1.2.3 <3.0.0"');
- });
-
- integration('and it should preserve the upper-bound operator', () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "<=3.0.0"
- }), d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'foo': {
- 'version': '1.2.3',
- 'source': 'hosted',
- 'description': {
- 'name': 'foo',
- 'url': 'http://pub.dartlang.org'
- }
- }
- }
- }))]).create();
-
- expectDependencyValidationWarning(' foo: ">=1.2.3 <=3.0.0"');
- });
-
- integration(
- 'and it should expand the suggested constraint if the '
- 'locked version matches the upper bound',
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "<=1.2.3"
- }), d.file("pubspec.lock", JSON.encode({
- 'packages': {
- 'foo': {
- 'version': '1.2.3',
- 'source': 'hosted',
- 'description': {
- 'name': 'foo',
- 'url': 'http://pub.dartlang.org'
- }
- }
- }
- }))]).create();
-
- expectDependencyValidationWarning(' foo: ">=1.2.3 <2.0.0"');
- });
- });
- });
-
- group('with a dependency without an upper bound', () {
- integration(
- 'and it should suggest a constraint based on the lower bound',
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": ">=1.2.3"
- })]).create();
-
- expectDependencyValidationWarning(' foo: ">=1.2.3 <2.0.0"');
- });
-
- integration('and it should preserve the lower-bound operator', () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": ">1.2.3"
- })]).create();
-
- expectDependencyValidationWarning(' foo: ">1.2.3 <2.0.0"');
- });
- });
-
- group('has a ^ dependency', () {
- integration("without an SDK constraint", () {
- d.dir(appPath, [d.libPubspec("integration_pkg", "1.0.0", deps: {
- "foo": "^1.2.3"
- })]).create();
-
- expectDependencyValidationError(' foo: ">=1.2.3 <2.0.0"');
- });
-
- integration("with a too-broad SDK constraint", () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: {
- "foo": "^1.2.3"
- }, sdk: ">=1.5.0 <2.0.0")]).create();
-
- expectDependencyValidationError(' foo: ">=1.2.3 <2.0.0"');
- });
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/directory_test.dart b/sdk/lib/_internal/pub_generated/test/validator/directory_test.dart
deleted file mode 100644
index fcfdb11..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/directory_test.dart
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/directory.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator directory(Entrypoint entrypoint) =>
- new DirectoryValidator(entrypoint);
-
-main() {
- initConfig();
-
- group('should consider a package valid if it', () {
- setUp(d.validPackage.create);
-
- integration('looks normal', () => expectNoValidationError(directory));
-
- integration('has a nested directory named "tools"', () {
- d.dir(appPath, [d.dir("foo", [d.dir("tools")])]).create();
- expectNoValidationError(directory);
- });
- });
-
- group(
- 'should consider a package invalid if it has a top-level directory ' 'named',
- () {
- setUp(d.validPackage.create);
-
- var names = [
- "benchmarks",
- "docs",
- "examples",
- "sample",
- "samples",
- "tests",
- "tools"];
-
- for (var name in names) {
- integration('"$name"', () {
- d.dir(appPath, [d.dir(name)]).create();
- expectValidationWarning(directory);
- });
- }
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/executable_test.dart b/sdk/lib/_internal/pub_generated/test/validator/executable_test.dart
deleted file mode 100644
index 995fef9..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/executable_test.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/executable.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator executable(Entrypoint entrypoint) =>
- new ExecutableValidator(entrypoint);
-
-main() {
- initConfig();
-
- setUp(d.validPackage.create);
-
- group('should consider a package valid if it', () {
- integration('has executables that are present', () {
- d.dir(appPath, [d.pubspec({
- "name": "test_pkg",
- "version": "1.0.0",
- "executables": {
- "one": "one_script",
- "two": null
- }
- }),
- d.dir(
- "bin",
- [
- d.file("one_script.dart", "main() => print('ok');"),
- d.file("two.dart", "main() => print('ok');")])]).create();
- expectNoValidationError(executable);
- });
- });
-
- group("should consider a package invalid if it", () {
- integration('is missing one or more listed executables', () {
- d.dir(appPath, [d.pubspec({
- "name": "test_pkg",
- "version": "1.0.0",
- "executables": {
- "nope": "not_there",
- "nada": null
- }
- })]).create();
- expectValidationWarning(executable);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/license_test.dart b/sdk/lib/_internal/pub_generated/test/validator/license_test.dart
deleted file mode 100644
index 7cd2039..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/license_test.dart
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright (c) 2013, 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:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/io.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/license.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator license(Entrypoint entrypoint) => new LicenseValidator(entrypoint);
-
-main() {
- initConfig();
-
- group('should consider a package valid if it', () {
- setUp(d.validPackage.create);
-
- integration('looks normal', () => expectNoValidationError(license));
-
- integration('has a COPYING file', () {
- schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'LICENSE')));
- d.file(path.join(appPath, 'COPYING'), '').create();
- expectNoValidationError(license);
- });
-
- integration('has a prefixed LICENSE file', () {
- schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'LICENSE')));
- d.file(path.join(appPath, 'MIT_LICENSE'), '').create();
- expectNoValidationError(license);
- });
-
- integration('has a suffixed LICENSE file', () {
- schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'LICENSE')));
- d.file(path.join(appPath, 'LICENSE.md'), '').create();
- expectNoValidationError(license);
- });
- });
-
- integration(
- 'should consider a package invalid if it has no LICENSE file',
- () {
- d.validPackage.create();
- schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'LICENSE')));
- expectValidationError(license);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/name_test.dart b/sdk/lib/_internal/pub_generated/test/validator/name_test.dart
deleted file mode 100644
index 6e91bf4..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/name_test.dart
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright (c) 2013, 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:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/io.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/name.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator name(Entrypoint entrypoint) => new NameValidator(entrypoint);
-
-main() {
- initConfig();
-
- group('should consider a package valid if it', () {
- setUp(d.validPackage.create);
-
- integration('looks normal', () => expectNoValidationError(name));
-
- integration('has a badly-named library in lib/src', () {
- d.dir(
- appPath,
- [
- d.libPubspec("test_pkg", "1.0.0"),
- d.dir(
- "lib",
- [
- d.file("test_pkg.dart", "int i = 1;"),
- d.dir("src", [d.file("8ball.dart", "int j = 2;")])])]).create();
- expectNoValidationError(name);
- });
-
- integration('has a name that starts with an underscore', () {
- d.dir(
- appPath,
- [
- d.libPubspec("_test_pkg", "1.0.0"),
- d.dir("lib", [d.file("_test_pkg.dart", "int i = 1;")])]).create();
- expectNoValidationError(name);
- });
- });
-
- group('should consider a package invalid if it', () {
- setUp(d.validPackage.create);
-
- integration('has an empty package name', () {
- d.dir(appPath, [d.libPubspec("", "1.0.0")]).create();
- expectValidationError(name);
- });
-
- integration('has a package name with an invalid character', () {
- d.dir(appPath, [d.libPubspec("test-pkg", "1.0.0")]).create();
- expectValidationError(name);
- });
-
- integration('has a package name that begins with a number', () {
- d.dir(appPath, [d.libPubspec("8ball", "1.0.0")]).create();
- expectValidationError(name);
- });
-
- integration('has a package name that contains upper-case letters', () {
- d.dir(appPath, [d.libPubspec("TestPkg", "1.0.0")]).create();
- expectValidationWarning(name);
- });
-
- integration('has a package name that is a Dart reserved word', () {
- d.dir(appPath, [d.libPubspec("final", "1.0.0")]).create();
- expectValidationError(name);
- });
-
- integration('has a library name with an invalid character', () {
- d.dir(
- appPath,
- [
- d.libPubspec("test_pkg", "1.0.0"),
- d.dir("lib", [d.file("test-pkg.dart", "int i = 0;")])]).create();
- expectValidationWarning(name);
- });
-
- integration('has a library name that begins with a number', () {
- d.dir(
- appPath,
- [
- d.libPubspec("test_pkg", "1.0.0"),
- d.dir("lib", [d.file("8ball.dart", "int i = 0;")])]).create();
- expectValidationWarning(name);
- });
-
- integration('has a library name that contains upper-case letters', () {
- d.dir(
- appPath,
- [
- d.libPubspec("test_pkg", "1.0.0"),
- d.dir("lib", [d.file("TestPkg.dart", "int i = 0;")])]).create();
- expectValidationWarning(name);
- });
-
- integration('has a library name that is a Dart reserved word', () {
- d.dir(
- appPath,
- [
- d.libPubspec("test_pkg", "1.0.0"),
- d.dir("lib", [d.file("for.dart", "int i = 0;")])]).create();
- expectValidationWarning(name);
- });
-
- integration('has a single library named differently than the package', () {
- schedule(
- () => deleteEntry(path.join(sandboxDir, appPath, "lib", "test_pkg.dart")));
- d.dir(
- appPath,
- [d.dir("lib", [d.file("best_pkg.dart", "int i = 0;")])]).create();
- expectValidationWarning(name);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/pubspec_field_test.dart b/sdk/lib/_internal/pub_generated/test/validator/pubspec_field_test.dart
deleted file mode 100644
index 0d0c8b9..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/pubspec_field_test.dart
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/pubspec_field.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator pubspecField(Entrypoint entrypoint) =>
- new PubspecFieldValidator(entrypoint);
-
-main() {
- initConfig();
-
- group('should consider a package valid if it', () {
- setUp(d.validPackage.create);
-
- integration('looks normal', () => expectNoValidationError(pubspecField));
-
- integration('has "authors" instead of "author"', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["authors"] = [pkg.remove("author")];
- d.dir(appPath, [d.pubspec(pkg)]).create();
- expectNoValidationError(pubspecField);
- });
-
- integration('has an HTTPS homepage URL', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["homepage"] = "https://pub.dartlang.org";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectNoValidationError(pubspecField);
- });
-
- integration('has an HTTPS documentation URL', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["documentation"] = "https://pub.dartlang.org";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectNoValidationError(pubspecField);
- });
- });
-
- group('should consider a package invalid if it', () {
- setUp(d.validPackage.create);
-
- integration('is missing the "homepage" field', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg.remove("homepage");
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('is missing the "description" field', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg.remove("description");
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('is missing the "author" field', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg.remove("author");
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('has a non-string "homepage" field', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["homepage"] = 12;
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('has a non-string "description" field', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["description"] = 12;
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('has a non-string "author" field', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["author"] = 12;
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('has a non-list "authors" field', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["authors"] = 12;
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('has a non-string member of the "authors" field', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["authors"] = [12];
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('has a single author without an email', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["author"] = "Natalie Weizenbaum";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationWarning(pubspecField);
- });
-
- integration('has one of several authors without an email', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg.remove("author");
- pkg["authors"] = [
- "Bob Nystrom <rnystrom@google.com>",
- "Natalie Weizenbaum",
- "John Messerly <jmesserly@google.com>"];
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationWarning(pubspecField);
- });
-
- integration('has a single author without a name', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["author"] = "<nweiz@google.com>";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationWarning(pubspecField);
- });
-
- integration('has one of several authors without a name', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg.remove("author");
- pkg["authors"] = [
- "Bob Nystrom <rnystrom@google.com>",
- "<nweiz@google.com>",
- "John Messerly <jmesserly@google.com>"];
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationWarning(pubspecField);
- });
-
- integration('has a non-HTTP homepage URL', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["homepage"] = "file:///foo/bar";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
-
- integration('has a non-HTTP documentation URL', () {
- var pkg = packageMap("test_pkg", "1.0.0");
- pkg["documentation"] = "file:///foo/bar";
- d.dir(appPath, [d.pubspec(pkg)]).create();
-
- expectValidationError(pubspecField);
- });
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/sdk_constraint_test.dart b/sdk/lib/_internal/pub_generated/test/validator/sdk_constraint_test.dart
deleted file mode 100644
index 27c568a..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/sdk_constraint_test.dart
+++ /dev/null
@@ -1,48 +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 'dart:async';
-import 'dart:convert';
-
-import 'package:http/http.dart' as http;
-import 'package:http/testing.dart';
-import 'package:path/path.dart' as path;
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/sdk_constraint.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator sdkConstraint(Entrypoint entrypoint) =>
- new SdkConstraintValidator(entrypoint);
-
-main() {
- initConfig();
-
- group('should consider a package valid if it', () {
- integration('has no SDK constraint', () {
- d.validPackage.create();
- expectNoValidationError(sdkConstraint);
- });
-
- integration('has an SDK constraint without ^', () {
- d.dir(
- appPath,
- [d.libPubspec("test_pkg", "1.0.0", sdk: ">=1.8.0 <2.0.0")]).create();
- expectNoValidationError(sdkConstraint);
- });
- });
-
- test(
- "should consider a package invalid if it has an SDK constraint with " "^",
- () {
- d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", sdk: "^1.8.0")]).create();
- expect(
- schedulePackageValidation(sdkConstraint),
- completion(pairOf(anyElement(contains('">=1.8.0 <2.0.0"')), isEmpty)));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/size_test.dart b/sdk/lib/_internal/pub_generated/test/validator/size_test.dart
deleted file mode 100644
index 15a4b06..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/size_test.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async';
-import 'dart:math' as math;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/validator/size.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Function size(int size) {
- return (entrypoint) => new SizeValidator(entrypoint, new Future.value(size));
-}
-
-main() {
- initConfig();
-
- setUp(d.validPackage.create);
-
- integration('should consider a package valid if it is <= 10 MB', () {
- expectNoValidationError(size(100));
- expectNoValidationError(size(10 * math.pow(2, 20)));
- });
-
- integration('should consider a package invalid if it is more than 10 MB', () {
- expectValidationError(size(10 * math.pow(2, 20) + 1));
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/utf8_readme_test.dart b/sdk/lib/_internal/pub_generated/test/validator/utf8_readme_test.dart
deleted file mode 100644
index a2e3cf1..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/utf8_readme_test.dart
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2013, 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:scheduled_test/scheduled_test.dart';
-
-import '../../lib/src/entrypoint.dart';
-import '../../lib/src/validator.dart';
-import '../../lib/src/validator/utf8_readme.dart';
-import '../descriptor.dart' as d;
-import '../test_pub.dart';
-import 'utils.dart';
-
-Validator utf8Readme(Entrypoint entrypoint) =>
- new Utf8ReadmeValidator(entrypoint);
-
-main() {
- initConfig();
-
- group('should consider a package valid if it', () {
- setUp(d.validPackage.create);
-
- integration('looks normal', () => expectNoValidationError(utf8Readme));
-
- integration('has a non-primary readme with invalid utf-8', () {
- d.dir(
- appPath,
- [
- d.file("README", "Valid utf-8"),
- d.binaryFile("README.invalid", [192])]).create();
- expectNoValidationError(utf8Readme);
- });
- });
-
- integration(
- 'should consider a package invalid if it has a README with ' 'invalid utf-8',
- () {
- d.validPackage.create();
-
- d.dir(appPath, [d.binaryFile("README", [192])]).create();
- expectValidationWarning(utf8Readme);
- });
-}
diff --git a/sdk/lib/_internal/pub_generated/test/validator/utils.dart b/sdk/lib/_internal/pub_generated/test/validator/utils.dart
deleted file mode 100644
index def5bb9..0000000
--- a/sdk/lib/_internal/pub_generated/test/validator/utils.dart
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) 2013, 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 validator.utils;
-
-import 'package:scheduled_test/scheduled_test.dart';
-
-import '../test_pub.dart';
-
-void expectNoValidationError(ValidatorCreator fn) {
- expect(schedulePackageValidation(fn), completion(pairOf(isEmpty, isEmpty)));
-}
-
-void expectValidationError(ValidatorCreator fn) {
- expect(
- schedulePackageValidation(fn),
- completion(pairOf(isNot(isEmpty), anything)));
-}
-
-void expectValidationWarning(ValidatorCreator fn) {
- expect(
- schedulePackageValidation(fn),
- completion(pairOf(isEmpty, isNot(isEmpty))));
-}
diff --git a/sdk/lib/_internal/pub_generated/test/version_solver_test.dart b/sdk/lib/_internal/pub_generated/test/version_solver_test.dart
deleted file mode 100644
index f013a88..0000000
--- a/sdk/lib/_internal/pub_generated/test/version_solver_test.dart
+++ /dev/null
@@ -1,1720 +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 pub_upgrade_test;
-
-import 'dart:async';
-
-import 'package:pub_semver/pub_semver.dart';
-import 'package:unittest/unittest.dart';
-
-import '../lib/src/lock_file.dart';
-import '../lib/src/log.dart' as log;
-import '../lib/src/package.dart';
-import '../lib/src/pubspec.dart';
-import '../lib/src/sdk.dart' as sdk;
-import '../lib/src/source/cached.dart';
-import '../lib/src/system_cache.dart';
-import '../lib/src/utils.dart';
-import '../lib/src/solver/version_solver.dart';
-import 'test_pub.dart';
-
-MockSource source1;
-MockSource source2;
-
-main() {
- initConfig();
-
- // Uncomment this to debug failing tests.
- // log.verbosity = log.Verbosity.SOLVER;
-
- // Since this test isn't run from the SDK, it can't find the "version" file
- // to load. Instead, just manually inject a version.
- sdk.version = new Version(1, 2, 3);
-
- group('basic graph', basicGraph);
- group('with lockfile', withLockFile);
- group('root dependency', rootDependency);
- group('dev dependency', devDependency);
- group('unsolvable', unsolvable);
- group('bad source', badSource);
- group('backtracking', backtracking);
- group('SDK constraint', sdkConstraint);
- group('pre-release', prerelease);
- group('override', override);
- group('downgrade', downgrade);
-}
-
-void basicGraph() {
- testResolve('no dependencies', {
- 'myapp 0.0.0': {}
- }, result: {
- 'myapp from root': '0.0.0'
- });
-
- testResolve('simple dependency tree', {
- 'myapp 0.0.0': {
- 'a': '1.0.0',
- 'b': '1.0.0'
- },
- 'a 1.0.0': {
- 'aa': '1.0.0',
- 'ab': '1.0.0'
- },
- 'aa 1.0.0': {},
- 'ab 1.0.0': {},
- 'b 1.0.0': {
- 'ba': '1.0.0',
- 'bb': '1.0.0'
- },
- 'ba 1.0.0': {},
- 'bb 1.0.0': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0',
- 'aa': '1.0.0',
- 'ab': '1.0.0',
- 'b': '1.0.0',
- 'ba': '1.0.0',
- 'bb': '1.0.0'
- });
-
- testResolve('shared dependency with overlapping constraints', {
- 'myapp 0.0.0': {
- 'a': '1.0.0',
- 'b': '1.0.0'
- },
- 'a 1.0.0': {
- 'shared': '>=2.0.0 <4.0.0'
- },
- 'b 1.0.0': {
- 'shared': '>=3.0.0 <5.0.0'
- },
- 'shared 2.0.0': {},
- 'shared 3.0.0': {},
- 'shared 3.6.9': {},
- 'shared 4.0.0': {},
- 'shared 5.0.0': {},
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0',
- 'b': '1.0.0',
- 'shared': '3.6.9'
- });
-
- testResolve(
- 'shared dependency where dependent version in turn affects '
- 'other dependencies',
- {
- 'myapp 0.0.0': {
- 'foo': '<=1.0.2',
- 'bar': '1.0.0'
- },
- 'foo 1.0.0': {},
- 'foo 1.0.1': {
- 'bang': '1.0.0'
- },
- 'foo 1.0.2': {
- 'whoop': '1.0.0'
- },
- 'foo 1.0.3': {
- 'zoop': '1.0.0'
- },
- 'bar 1.0.0': {
- 'foo': '<=1.0.1'
- },
- 'bang 1.0.0': {},
- 'whoop 1.0.0': {},
- 'zoop 1.0.0': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '1.0.1',
- 'bar': '1.0.0',
- 'bang': '1.0.0'
- }, maxTries: 2);
-
- testResolve('circular dependency', {
- 'myapp 1.0.0': {
- 'foo': '1.0.0'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'bar 1.0.0': {
- 'foo': '1.0.0'
- }
- }, result: {
- 'myapp from root': '1.0.0',
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- });
-}
-
-withLockFile() {
- testResolve('with compatible locked dependency', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'foo 1.0.1': {
- 'bar': '1.0.1'
- },
- 'foo 1.0.2': {
- 'bar': '1.0.2'
- },
- 'bar 1.0.0': {},
- 'bar 1.0.1': {},
- 'bar 1.0.2': {}
- }, lockfile: {
- 'foo': '1.0.1'
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '1.0.1',
- 'bar': '1.0.1'
- });
-
- testResolve('with incompatible locked dependency', {
- 'myapp 0.0.0': {
- 'foo': '>1.0.1'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'foo 1.0.1': {
- 'bar': '1.0.1'
- },
- 'foo 1.0.2': {
- 'bar': '1.0.2'
- },
- 'bar 1.0.0': {},
- 'bar 1.0.1': {},
- 'bar 1.0.2': {}
- }, lockfile: {
- 'foo': '1.0.1'
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '1.0.2',
- 'bar': '1.0.2'
- });
-
- testResolve('with unrelated locked dependency', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'foo 1.0.1': {
- 'bar': '1.0.1'
- },
- 'foo 1.0.2': {
- 'bar': '1.0.2'
- },
- 'bar 1.0.0': {},
- 'bar 1.0.1': {},
- 'bar 1.0.2': {},
- 'baz 1.0.0': {}
- }, lockfile: {
- 'baz': '1.0.0'
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '1.0.2',
- 'bar': '1.0.2'
- });
-
- testResolve(
- 'unlocks dependencies if necessary to ensure that a new '
- 'dependency is satisfied',
- {
- 'myapp 0.0.0': {
- 'foo': 'any',
- 'newdep': 'any'
- },
- 'foo 1.0.0': {
- 'bar': '<2.0.0'
- },
- 'bar 1.0.0': {
- 'baz': '<2.0.0'
- },
- 'baz 1.0.0': {
- 'qux': '<2.0.0'
- },
- 'qux 1.0.0': {},
- 'foo 2.0.0': {
- 'bar': '<3.0.0'
- },
- 'bar 2.0.0': {
- 'baz': '<3.0.0'
- },
- 'baz 2.0.0': {
- 'qux': '<3.0.0'
- },
- 'qux 2.0.0': {},
- 'newdep 2.0.0': {
- 'baz': '>=1.5.0'
- }
- }, lockfile: {
- 'foo': '1.0.0',
- 'bar': '1.0.0',
- 'baz': '1.0.0',
- 'qux': '1.0.0'
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '2.0.0',
- 'bar': '2.0.0',
- 'baz': '2.0.0',
- 'qux': '1.0.0',
- 'newdep': '2.0.0'
- }, maxTries: 3);
-}
-
-rootDependency() {
- testResolve('with root source', {
- 'myapp 1.0.0': {
- 'foo': '1.0.0'
- },
- 'foo 1.0.0': {
- 'myapp from root': '>=1.0.0'
- }
- }, result: {
- 'myapp from root': '1.0.0',
- 'foo': '1.0.0'
- });
-
- testResolve('with different source', {
- 'myapp 1.0.0': {
- 'foo': '1.0.0'
- },
- 'foo 1.0.0': {
- 'myapp': '>=1.0.0'
- }
- }, result: {
- 'myapp from root': '1.0.0',
- 'foo': '1.0.0'
- });
-
- testResolve('with mismatched sources', {
- 'myapp 1.0.0': {
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- },
- 'foo 1.0.0': {
- 'myapp': '>=1.0.0'
- },
- 'bar 1.0.0': {
- 'myapp from mock2': '>=1.0.0'
- }
- }, error: sourceMismatch('myapp', 'foo', 'bar'));
-
- testResolve('with wrong version', {
- 'myapp 1.0.0': {
- 'foo': '1.0.0'
- },
- 'foo 1.0.0': {
- 'myapp': '<1.0.0'
- }
- }, error: couldNotSolve);
-}
-
-devDependency() {
- testResolve("includes root package's dev dependencies", {
- 'myapp 1.0.0': {
- '(dev) foo': '1.0.0',
- '(dev) bar': '1.0.0'
- },
- 'foo 1.0.0': {},
- 'bar 1.0.0': {}
- }, result: {
- 'myapp from root': '1.0.0',
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- });
-
- testResolve("includes dev dependency's transitive dependencies", {
- 'myapp 1.0.0': {
- '(dev) foo': '1.0.0'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'bar 1.0.0': {}
- }, result: {
- 'myapp from root': '1.0.0',
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- });
-
- testResolve("ignores transitive dependency's dev dependencies", {
- 'myapp 1.0.0': {
- 'foo': '1.0.0'
- },
- 'foo 1.0.0': {
- '(dev) bar': '1.0.0'
- },
- 'bar 1.0.0': {}
- }, result: {
- 'myapp from root': '1.0.0',
- 'foo': '1.0.0'
- });
-}
-
-unsolvable() {
- testResolve('no version that matches requirement', {
- 'myapp 0.0.0': {
- 'foo': '>=1.0.0 <2.0.0'
- },
- 'foo 2.0.0': {},
- 'foo 2.1.3': {}
- }, error: noVersion(['myapp', 'foo']));
-
- testResolve('no version that matches combined constraint', {
- 'myapp 0.0.0': {
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- },
- 'foo 1.0.0': {
- 'shared': '>=2.0.0 <3.0.0'
- },
- 'bar 1.0.0': {
- 'shared': '>=2.9.0 <4.0.0'
- },
- 'shared 2.5.0': {},
- 'shared 3.5.0': {}
- }, error: noVersion(['shared', 'foo', 'bar']));
-
- testResolve('disjoint constraints', {
- 'myapp 0.0.0': {
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- },
- 'foo 1.0.0': {
- 'shared': '<=2.0.0'
- },
- 'bar 1.0.0': {
- 'shared': '>3.0.0'
- },
- 'shared 2.0.0': {},
- 'shared 4.0.0': {}
- }, error: disjointConstraint(['shared', 'foo', 'bar']));
-
- testResolve('mismatched descriptions', {
- 'myapp 0.0.0': {
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- },
- 'foo 1.0.0': {
- 'shared-x': '1.0.0'
- },
- 'bar 1.0.0': {
- 'shared-y': '1.0.0'
- },
- 'shared-x 1.0.0': {},
- 'shared-y 1.0.0': {}
- }, error: descriptionMismatch('shared', 'foo', 'bar'));
-
- testResolve('mismatched sources', {
- 'myapp 0.0.0': {
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- },
- 'foo 1.0.0': {
- 'shared': '1.0.0'
- },
- 'bar 1.0.0': {
- 'shared from mock2': '1.0.0'
- },
- 'shared 1.0.0': {},
- 'shared 1.0.0 from mock2': {}
- }, error: sourceMismatch('shared', 'foo', 'bar'));
-
- testResolve('no valid solution', {
- 'myapp 0.0.0': {
- 'a': 'any',
- 'b': 'any'
- },
- 'a 1.0.0': {
- 'b': '1.0.0'
- },
- 'a 2.0.0': {
- 'b': '2.0.0'
- },
- 'b 1.0.0': {
- 'a': '2.0.0'
- },
- 'b 2.0.0': {
- 'a': '1.0.0'
- }
- }, error: couldNotSolve, maxTries: 4);
-
- // This is a regression test for #15550.
- testResolve('no version that matches while backtracking', {
- 'myapp 0.0.0': {
- 'a': 'any',
- 'b': '>1.0.0'
- },
- 'a 1.0.0': {},
- 'b 1.0.0': {}
- }, error: noVersion(['myapp', 'b']), maxTries: 1);
-
-
- // This is a regression test for #18300.
- testResolve('...', {
- "myapp 0.0.0": {
- "angular": "any",
- "collection": "any"
- },
- "analyzer 0.12.2": {},
- "angular 0.10.0": {
- "di": ">=0.0.32 <0.1.0",
- "collection": ">=0.9.1 <1.0.0"
- },
- "angular 0.9.11": {
- "di": ">=0.0.32 <0.1.0",
- "collection": ">=0.9.1 <1.0.0"
- },
- "angular 0.9.10": {
- "di": ">=0.0.32 <0.1.0",
- "collection": ">=0.9.1 <1.0.0"
- },
- "collection 0.9.0": {},
- "collection 0.9.1": {},
- "di 0.0.37": {
- "analyzer": ">=0.13.0 <0.14.0"
- },
- "di 0.0.36": {
- "analyzer": ">=0.13.0 <0.14.0"
- }
- }, error: noVersion(['myapp', 'angular', 'collection']), maxTries: 9);
-}
-
-badSource() {
- testResolve('fail if the root package has a bad source in dep', {
- 'myapp 0.0.0': {
- 'foo from bad': 'any'
- },
- }, error: unknownSource('myapp', 'foo', 'bad'));
-
- testResolve('fail if the root package has a bad source in dev dep', {
- 'myapp 0.0.0': {
- '(dev) foo from bad': 'any'
- },
- }, error: unknownSource('myapp', 'foo', 'bad'));
-
- testResolve('fail if all versions have bad source in dep', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar from bad': 'any'
- },
- 'foo 1.0.1': {
- 'baz from bad': 'any'
- },
- 'foo 1.0.3': {
- 'bang from bad': 'any'
- },
- }, error: unknownSource('foo', 'bar', 'bad'), maxTries: 3);
-
- testResolve('ignore versions with bad source in dep', {
- 'myapp 1.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar': 'any'
- },
- 'foo 1.0.1': {
- 'bar from bad': 'any'
- },
- 'foo 1.0.3': {
- 'bar from bad': 'any'
- },
- 'bar 1.0.0': {}
- }, result: {
- 'myapp from root': '1.0.0',
- 'foo': '1.0.0',
- 'bar': '1.0.0'
- }, maxTries: 3);
-}
-
-backtracking() {
- testResolve('circular dependency on older version', {
- 'myapp 0.0.0': {
- 'a': '>=1.0.0'
- },
- 'a 1.0.0': {},
- 'a 2.0.0': {
- 'b': '1.0.0'
- },
- 'b 1.0.0': {
- 'a': '1.0.0'
- }
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0'
- }, maxTries: 2);
-
- // The latest versions of a and b disagree on c. An older version of either
- // will resolve the problem. This test validates that b, which is farther
- // in the dependency graph from myapp is downgraded first.
- testResolve('rolls back leaf versions first', {
- 'myapp 0.0.0': {
- 'a': 'any'
- },
- 'a 1.0.0': {
- 'b': 'any'
- },
- 'a 2.0.0': {
- 'b': 'any',
- 'c': '2.0.0'
- },
- 'b 1.0.0': {},
- 'b 2.0.0': {
- 'c': '1.0.0'
- },
- 'c 1.0.0': {},
- 'c 2.0.0': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '2.0.0',
- 'b': '1.0.0',
- 'c': '2.0.0'
- }, maxTries: 2);
-
- // Only one version of baz, so foo and bar will have to downgrade until they
- // reach it.
- testResolve('simple transitive', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'foo 2.0.0': {
- 'bar': '2.0.0'
- },
- 'foo 3.0.0': {
- 'bar': '3.0.0'
- },
- 'bar 1.0.0': {
- 'baz': 'any'
- },
- 'bar 2.0.0': {
- 'baz': '2.0.0'
- },
- 'bar 3.0.0': {
- 'baz': '3.0.0'
- },
- 'baz 1.0.0': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '1.0.0',
- 'bar': '1.0.0',
- 'baz': '1.0.0'
- }, maxTries: 3);
-
- // This ensures it doesn't exhaustively search all versions of b when it's
- // a-2.0.0 whose dependency on c-2.0.0-nonexistent led to the problem. We
- // make sure b has more versions than a so that the solver tries a first
- // since it sorts sibling dependencies by number of versions.
- testResolve('backjump to nearer unsatisfied package', {
- 'myapp 0.0.0': {
- 'a': 'any',
- 'b': 'any'
- },
- 'a 1.0.0': {
- 'c': '1.0.0'
- },
- 'a 2.0.0': {
- 'c': '2.0.0-nonexistent'
- },
- 'b 1.0.0': {},
- 'b 2.0.0': {},
- 'b 3.0.0': {},
- 'c 1.0.0': {},
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0',
- 'b': '3.0.0',
- 'c': '1.0.0'
- }, maxTries: 2);
-
- // Tests that the backjumper will jump past unrelated selections when a
- // source conflict occurs. This test selects, in order:
- // - myapp -> a
- // - myapp -> b
- // - myapp -> c (1 of 5)
- // - b -> a
- // It selects a and b first because they have fewer versions than c. It
- // traverses b's dependency on a after selecting a version of c because
- // dependencies are traversed breadth-first (all of myapps's immediate deps
- // before any other their deps).
- //
- // This means it doesn't discover the source conflict until after selecting
- // c. When that happens, it should backjump past c instead of trying older
- // versions of it since they aren't related to the conflict.
- testResolve('backjump to conflicting source', {
- 'myapp 0.0.0': {
- 'a': 'any',
- 'b': 'any',
- 'c': 'any'
- },
- 'a 1.0.0': {},
- 'a 1.0.0 from mock2': {},
- 'b 1.0.0': {
- 'a': 'any'
- },
- 'b 2.0.0': {
- 'a from mock2': 'any'
- },
- 'c 1.0.0': {},
- 'c 2.0.0': {},
- 'c 3.0.0': {},
- 'c 4.0.0': {},
- 'c 5.0.0': {},
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0',
- 'b': '1.0.0',
- 'c': '5.0.0'
- }, maxTries: 2);
-
- // Like the above test, but for a conflicting description.
- testResolve('backjump to conflicting description', {
- 'myapp 0.0.0': {
- 'a-x': 'any',
- 'b': 'any',
- 'c': 'any'
- },
- 'a-x 1.0.0': {},
- 'a-y 1.0.0': {},
- 'b 1.0.0': {
- 'a-x': 'any'
- },
- 'b 2.0.0': {
- 'a-y': 'any'
- },
- 'c 1.0.0': {},
- 'c 2.0.0': {},
- 'c 3.0.0': {},
- 'c 4.0.0': {},
- 'c 5.0.0': {},
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0',
- 'b': '1.0.0',
- 'c': '5.0.0'
- }, maxTries: 2);
-
- // Similar to the above two tests but where there is no solution. It should
- // fail in this case with no backtracking.
- testResolve('backjump to conflicting source', {
- 'myapp 0.0.0': {
- 'a': 'any',
- 'b': 'any',
- 'c': 'any'
- },
- 'a 1.0.0': {},
- 'a 1.0.0 from mock2': {},
- 'b 1.0.0': {
- 'a from mock2': 'any'
- },
- 'c 1.0.0': {},
- 'c 2.0.0': {},
- 'c 3.0.0': {},
- 'c 4.0.0': {},
- 'c 5.0.0': {},
- }, error: sourceMismatch('a', 'myapp', 'b'), maxTries: 1);
-
- testResolve('backjump to conflicting description', {
- 'myapp 0.0.0': {
- 'a-x': 'any',
- 'b': 'any',
- 'c': 'any'
- },
- 'a-x 1.0.0': {},
- 'a-y 1.0.0': {},
- 'b 1.0.0': {
- 'a-y': 'any'
- },
- 'c 1.0.0': {},
- 'c 2.0.0': {},
- 'c 3.0.0': {},
- 'c 4.0.0': {},
- 'c 5.0.0': {},
- }, error: descriptionMismatch('a', 'myapp', 'b'), maxTries: 1);
-
- // Dependencies are ordered so that packages with fewer versions are tried
- // first. Here, there are two valid solutions (either a or b must be
- // downgraded once). The chosen one depends on which dep is traversed first.
- // Since b has fewer versions, it will be traversed first, which means a will
- // come later. Since later selections are revised first, a gets downgraded.
- testResolve('traverse into package with fewer versions first', {
- 'myapp 0.0.0': {
- 'a': 'any',
- 'b': 'any'
- },
- 'a 1.0.0': {
- 'c': 'any'
- },
- 'a 2.0.0': {
- 'c': 'any'
- },
- 'a 3.0.0': {
- 'c': 'any'
- },
- 'a 4.0.0': {
- 'c': 'any'
- },
- 'a 5.0.0': {
- 'c': '1.0.0'
- },
- 'b 1.0.0': {
- 'c': 'any'
- },
- 'b 2.0.0': {
- 'c': 'any'
- },
- 'b 3.0.0': {
- 'c': 'any'
- },
- 'b 4.0.0': {
- 'c': '2.0.0'
- },
- 'c 1.0.0': {},
- 'c 2.0.0': {},
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '4.0.0',
- 'b': '4.0.0',
- 'c': '2.0.0'
- }, maxTries: 2);
-
- // This is similar to the above test. When getting the number of versions of
- // a package to determine which to traverse first, versions that are
- // disallowed by the root package's constraints should not be considered.
- // Here, foo has more versions of bar in total (4), but fewer that meet
- // myapp's constraints (only 2). There is no solution, but we will do less
- // backtracking if foo is tested first.
- testResolve('take root package constraints into counting versions', {
- "myapp 0.0.0": {
- "foo": ">2.0.0",
- "bar": "any"
- },
- "foo 1.0.0": {
- "none": "2.0.0"
- },
- "foo 2.0.0": {
- "none": "2.0.0"
- },
- "foo 3.0.0": {
- "none": "2.0.0"
- },
- "foo 4.0.0": {
- "none": "2.0.0"
- },
- "bar 1.0.0": {},
- "bar 2.0.0": {},
- "bar 3.0.0": {},
- "none 1.0.0": {}
- }, error: noVersion(["foo", "none"]), maxTries: 2);
-
- // This sets up a hundred versions of foo and bar, 0.0.0 through 9.9.0. Each
- // version of foo depends on a baz with the same major version. Each version
- // of bar depends on a baz with the same minor version. There is only one
- // version of baz, 0.0.0, so only older versions of foo and bar will
- // satisfy it.
- var map = {
- 'myapp 0.0.0': {
- 'foo': 'any',
- 'bar': 'any'
- },
- 'baz 0.0.0': {}
- };
-
- for (var i = 0; i < 10; i++) {
- for (var j = 0; j < 10; j++) {
- map['foo $i.$j.0'] = {
- 'baz': '$i.0.0'
- };
- map['bar $i.$j.0'] = {
- 'baz': '0.$j.0'
- };
- }
- }
-
- testResolve('complex backtrack', map, result: {
- 'myapp from root': '0.0.0',
- 'foo': '0.9.0',
- 'bar': '9.0.0',
- 'baz': '0.0.0'
- }, maxTries: 100);
-
- // If there's a disjoint constraint on a package, then selecting other
- // versions of it is a waste of time: no possible versions can match. We need
- // to jump past it to the most recent package that affected the constraint.
- testResolve('backjump past failed package on disjoint constraint', {
- 'myapp 0.0.0': {
- 'a': 'any',
- 'foo': '>2.0.0'
- },
- 'a 1.0.0': {
- 'foo': 'any' // ok
- },
- 'a 2.0.0': {
- 'foo': '<1.0.0' // disjoint with myapp's constraint on foo
- },
- 'foo 2.0.0': {},
- 'foo 2.0.1': {},
- 'foo 2.0.2': {},
- 'foo 2.0.3': {},
- 'foo 2.0.4': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0',
- 'foo': '2.0.4'
- }, maxTries: 2);
-
- // This is a regression test for #18666. It was possible for the solver to
- // "forget" that a package had previously led to an error. In that case, it
- // would backtrack over the failed package instead of trying different
- // versions of it.
- testResolve("finds solution with less strict constraint", {
- "myapp 1.0.0": {
- "a": "any",
- "c": "any",
- "d": "any"
- },
- "a 2.0.0": {},
- "a 1.0.0": {},
- "b 1.0.0": {
- "a": "1.0.0"
- },
- "c 1.0.0": {
- "b": "any"
- },
- "d 2.0.0": {
- "myapp": "any"
- },
- "d 1.0.0": {
- "myapp": "<1.0.0"
- }
- }, result: {
- 'myapp from root': '1.0.0',
- 'a': '1.0.0',
- 'b': '1.0.0',
- 'c': '1.0.0',
- 'd': '2.0.0'
- }, maxTries: 3);
-}
-
-sdkConstraint() {
- var badVersion = '0.0.0-nope';
- var goodVersion = sdk.version.toString();
-
- testResolve('root matches SDK', {
- 'myapp 0.0.0': {
- 'sdk': goodVersion
- }
- }, result: {
- 'myapp from root': '0.0.0'
- });
-
- testResolve('root does not match SDK', {
- 'myapp 0.0.0': {
- 'sdk': badVersion
- }
- }, error: couldNotSolve);
-
- testResolve('dependency does not match SDK', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 0.0.0': {
- 'sdk': badVersion
- }
- }, error: couldNotSolve);
-
- testResolve('transitive dependency does not match SDK', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 0.0.0': {
- 'bar': 'any'
- },
- 'bar 0.0.0': {
- 'sdk': badVersion
- }
- }, error: couldNotSolve);
-
- testResolve('selects a dependency version that allows the SDK', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'sdk': goodVersion
- },
- 'foo 2.0.0': {
- 'sdk': goodVersion
- },
- 'foo 3.0.0': {
- 'sdk': badVersion
- },
- 'foo 4.0.0': {
- 'sdk': badVersion
- }
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '2.0.0'
- }, maxTries: 3);
-
- testResolve('selects a transitive dependency version that allows the SDK', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar': 'any'
- },
- 'bar 1.0.0': {
- 'sdk': goodVersion
- },
- 'bar 2.0.0': {
- 'sdk': goodVersion
- },
- 'bar 3.0.0': {
- 'sdk': badVersion
- },
- 'bar 4.0.0': {
- 'sdk': badVersion
- }
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '1.0.0',
- 'bar': '2.0.0'
- }, maxTries: 3);
-
- testResolve(
- 'selects a dependency version that allows a transitive '
- 'dependency that allows the SDK',
- {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'foo 2.0.0': {
- 'bar': '2.0.0'
- },
- 'foo 3.0.0': {
- 'bar': '3.0.0'
- },
- 'foo 4.0.0': {
- 'bar': '4.0.0'
- },
- 'bar 1.0.0': {
- 'sdk': goodVersion
- },
- 'bar 2.0.0': {
- 'sdk': goodVersion
- },
- 'bar 3.0.0': {
- 'sdk': badVersion
- },
- 'bar 4.0.0': {
- 'sdk': badVersion
- }
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '2.0.0',
- 'bar': '2.0.0'
- }, maxTries: 3);
-}
-
-void prerelease() {
- testResolve('prefer stable versions over unstable', {
- 'myapp 0.0.0': {
- 'a': 'any'
- },
- 'a 1.0.0': {},
- 'a 1.1.0-dev': {},
- 'a 2.0.0-dev': {},
- 'a 3.0.0-dev': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0'
- });
-
- testResolve('use latest allowed prerelease if no stable versions match', {
- 'myapp 0.0.0': {
- 'a': '<2.0.0'
- },
- 'a 1.0.0-dev': {},
- 'a 1.1.0-dev': {},
- 'a 1.9.0-dev': {},
- 'a 3.0.0': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.9.0-dev'
- });
-
- testResolve('use an earlier stable version on a < constraint', {
- 'myapp 0.0.0': {
- 'a': '<2.0.0'
- },
- 'a 1.0.0': {},
- 'a 1.1.0': {},
- 'a 2.0.0-dev': {},
- 'a 2.0.0': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.1.0'
- });
-
- testResolve('prefer a stable version even if constraint mentions unstable', {
- 'myapp 0.0.0': {
- 'a': '<=2.0.0-dev'
- },
- 'a 1.0.0': {},
- 'a 1.1.0': {},
- 'a 2.0.0-dev': {},
- 'a 2.0.0': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.1.0'
- });
-}
-
-void override() {
- testResolve('chooses best version matching override constraint', {
- 'myapp 0.0.0': {
- 'a': 'any'
- },
- 'a 1.0.0': {},
- 'a 2.0.0': {},
- 'a 3.0.0': {}
- }, overrides: {
- 'a': '<3.0.0'
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '2.0.0'
- });
-
- testResolve('uses override as dependency', {
- 'myapp 0.0.0': {},
- 'a 1.0.0': {},
- 'a 2.0.0': {},
- 'a 3.0.0': {}
- }, overrides: {
- 'a': '<3.0.0'
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '2.0.0'
- });
-
- testResolve('ignores other constraints on overridden package', {
- 'myapp 0.0.0': {
- 'b': 'any',
- 'c': 'any'
- },
- 'a 1.0.0': {},
- 'a 2.0.0': {},
- 'a 3.0.0': {},
- 'b 1.0.0': {
- 'a': '1.0.0'
- },
- 'c 1.0.0': {
- 'a': '3.0.0'
- }
- }, overrides: {
- 'a': '2.0.0'
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '2.0.0',
- 'b': '1.0.0',
- 'c': '1.0.0'
- });
-
- testResolve('backtracks on overidden package for its constraints', {
- 'myapp 0.0.0': {
- 'shared': '2.0.0'
- },
- 'a 1.0.0': {
- 'shared': 'any'
- },
- 'a 2.0.0': {
- 'shared': '1.0.0'
- },
- 'shared 1.0.0': {},
- 'shared 2.0.0': {}
- }, overrides: {
- 'a': '<3.0.0'
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '1.0.0',
- 'shared': '2.0.0'
- }, maxTries: 2);
-
- testResolve('override compatible with locked dependency', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'foo 1.0.1': {
- 'bar': '1.0.1'
- },
- 'foo 1.0.2': {
- 'bar': '1.0.2'
- },
- 'bar 1.0.0': {},
- 'bar 1.0.1': {},
- 'bar 1.0.2': {}
- }, lockfile: {
- 'foo': '1.0.1'
- }, overrides: {
- 'foo': '<1.0.2'
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '1.0.1',
- 'bar': '1.0.1'
- });
-
- testResolve('override incompatible with locked dependency', {
- 'myapp 0.0.0': {
- 'foo': 'any'
- },
- 'foo 1.0.0': {
- 'bar': '1.0.0'
- },
- 'foo 1.0.1': {
- 'bar': '1.0.1'
- },
- 'foo 1.0.2': {
- 'bar': '1.0.2'
- },
- 'bar 1.0.0': {},
- 'bar 1.0.1': {},
- 'bar 1.0.2': {}
- }, lockfile: {
- 'foo': '1.0.1'
- }, overrides: {
- 'foo': '>1.0.1'
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '1.0.2',
- 'bar': '1.0.2'
- });
-
- testResolve('no version that matches override', {
- 'myapp 0.0.0': {},
- 'foo 2.0.0': {},
- 'foo 2.1.3': {}
- }, overrides: {
- 'foo': '>=1.0.0 <2.0.0'
- }, error: noVersion(['myapp']));
-
- testResolve('override a bad source without error', {
- 'myapp 0.0.0': {
- 'foo from bad': 'any'
- },
- 'foo 0.0.0': {}
- }, overrides: {
- 'foo': 'any'
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '0.0.0'
- });
-}
-
-void downgrade() {
- testResolve("downgrades a dependency to the lowest matching version", {
- 'myapp 0.0.0': {
- 'foo': '>=2.0.0 <3.0.0'
- },
- 'foo 1.0.0': {},
- 'foo 2.0.0-dev': {},
- 'foo 2.0.0': {},
- 'foo 2.1.0': {}
- }, lockfile: {
- 'foo': '2.1.0'
- }, result: {
- 'myapp from root': '0.0.0',
- 'foo': '2.0.0'
- }, downgrade: true);
-
- testResolve(
- 'use earliest allowed prerelease if no stable versions match '
- 'while downgrading',
- {
- 'myapp 0.0.0': {
- 'a': '>=2.0.0-dev.1 <3.0.0'
- },
- 'a 1.0.0': {},
- 'a 2.0.0-dev.1': {},
- 'a 2.0.0-dev.2': {},
- 'a 2.0.0-dev.3': {}
- }, result: {
- 'myapp from root': '0.0.0',
- 'a': '2.0.0-dev.1'
- }, downgrade: true);
-}
-
-testResolve(String description, Map packages, {Map lockfile, Map overrides,
- Map result, FailMatcherBuilder error, int maxTries, bool downgrade: false}) {
- _testResolve(
- test,
- description,
- packages,
- lockfile: lockfile,
- overrides: overrides,
- result: result,
- error: error,
- maxTries: maxTries,
- downgrade: downgrade);
-}
-
-solo_testResolve(String description, Map packages, {Map lockfile, Map overrides,
- Map result, FailMatcherBuilder error, int maxTries, bool downgrade: false}) {
- log.verbosity = log.Verbosity.SOLVER;
- _testResolve(
- solo_test,
- description,
- packages,
- lockfile: lockfile,
- overrides: overrides,
- result: result,
- error: error,
- maxTries: maxTries,
- downgrade: downgrade);
-}
-
-_testResolve(void testFn(String description, Function body), String description,
- Map packages, {Map lockfile, Map overrides, Map result,
- FailMatcherBuilder error, int maxTries, bool downgrade: false}) {
- if (maxTries == null) maxTries = 1;
-
- testFn(description, () {
- var cache = new SystemCache('.');
- source1 = new MockSource('mock1');
- source2 = new MockSource('mock2');
- cache.register(source1);
- cache.register(source2);
- cache.sources.setDefault(source1.name);
-
- // Build the test package graph.
- var root;
- packages.forEach((description, dependencies) {
- var id = parseSpec(description);
- var package =
- mockPackage(id, dependencies, id.name == 'myapp' ? overrides : null);
- if (id.name == 'myapp') {
- // Don't add the root package to the server, so we can verify that Pub
- // doesn't try to look up information about the local package on the
- // remote server.
- root = package;
- } else {
- (cache.sources[id.source] as MockSource).addPackage(
- id.description,
- package);
- }
- });
-
- // Clean up the expectation.
- if (result != null) {
- var newResult = {};
- result.forEach((description, version) {
- var id = parseSpec(description, version);
- newResult[id.name] = id;
- });
- result = newResult;
- }
-
- // Parse the lockfile.
- var realLockFile = new LockFile.empty();
- if (lockfile != null) {
- lockfile.forEach((name, version) {
- version = new Version.parse(version);
- realLockFile.packages[name] =
- new PackageId(name, source1.name, version, name);
- });
- }
-
- // Resolve the versions.
- var future = resolveVersions(
- downgrade ? SolveType.DOWNGRADE : SolveType.GET,
- cache.sources,
- root,
- lockFile: realLockFile);
-
- var matcher;
- if (result != null) {
- matcher = new SolveSuccessMatcher(result, maxTries);
- } else if (error != null) {
- matcher = error(maxTries);
- }
-
- expect(future, completion(matcher));
- });
-}
-
-typedef SolveFailMatcher FailMatcherBuilder(int maxTries);
-
-FailMatcherBuilder noVersion(List<String> packages) {
- return (maxTries) =>
- new SolveFailMatcher(packages, maxTries, NoVersionException);
-}
-
-FailMatcherBuilder disjointConstraint(List<String> packages) {
- return (maxTries) =>
- new SolveFailMatcher(packages, maxTries, DisjointConstraintException);
-}
-
-FailMatcherBuilder descriptionMismatch(String package, String depender1,
- String depender2) {
- return (maxTries) =>
- new SolveFailMatcher(
- [package, depender1, depender2],
- maxTries,
- DescriptionMismatchException);
-}
-
-// If no solution can be found, the solver just reports the last failure that
-// happened during propagation. Since we don't specify the order that solutions
-// are tried, this just validates that *some* failure occurred, but not which.
-SolveFailMatcher couldNotSolve(maxTries) =>
- new SolveFailMatcher([], maxTries, null);
-
-FailMatcherBuilder sourceMismatch(String package, String depender1,
- String depender2) {
- return (maxTries) =>
- new SolveFailMatcher(
- [package, depender1, depender2],
- maxTries,
- SourceMismatchException);
-}
-
-unknownSource(String depender, String dependency, String source) {
- return (maxTries) =>
- new SolveFailMatcher(
- [depender, dependency, source],
- maxTries,
- UnknownSourceException);
-}
-
-class SolveSuccessMatcher implements Matcher {
- /// The expected concrete package selections.
- final Map<String, PackageId> _expected;
-
- /// The maximum number of attempts that should have been tried before finding
- /// the solution.
- final int _maxTries;
-
- SolveSuccessMatcher(this._expected, this._maxTries);
-
- Description describe(Description description) {
- return description.add(
- 'Solver to use at most $_maxTries attempts to find:\n'
- '${_listPackages(_expected.values)}');
- }
-
- Description describeMismatch(SolveResult result, Description description,
- Map state, bool verbose) {
- if (!result.succeeded) {
- description.add('Solver failed with:\n${result.error}');
- return null;
- }
-
- description.add('Resolved:\n${_listPackages(result.packages)}\n');
- description.add(state['failures']);
- return description;
- }
-
- bool matches(SolveResult result, Map state) {
- if (!result.succeeded) return false;
-
- var expected = new Map.from(_expected);
- var failures = new StringBuffer();
-
- for (var id in result.packages) {
- if (!expected.containsKey(id.name)) {
- failures.writeln('Should not have selected $id');
- } else {
- var expectedId = expected.remove(id.name);
- if (id != expectedId) {
- failures.writeln('Expected $expectedId, not $id');
- }
- }
- }
-
- if (!expected.isEmpty) {
- failures.writeln('Missing:\n${_listPackages(expected.values)}');
- }
-
- // Allow 1 here because the greedy solver will only make one attempt.
- if (result.attemptedSolutions != 1 &&
- result.attemptedSolutions != _maxTries) {
- failures.writeln('Took ${result.attemptedSolutions} attempts');
- }
-
- if (!failures.isEmpty) {
- state['failures'] = failures.toString();
- return false;
- }
-
- return true;
- }
-
- String _listPackages(Iterable<PackageId> packages) {
- return '- ${packages.join('\n- ')}';
- }
-}
-
-class SolveFailMatcher implements Matcher {
- /// The strings that should appear in the resulting error message.
- // TODO(rnystrom): This seems to always be package names. Make that explicit.
- final Iterable<String> _expected;
-
- /// The maximum number of attempts that should be tried before failing.
- final int _maxTries;
-
- /// The concrete error type that should be found, or `null` if any
- /// [SolveFailure] is allowed.
- final Type _expectedType;
-
- SolveFailMatcher(this._expected, this._maxTries, this._expectedType);
-
- Description describe(Description description) {
- description.add('Solver should fail after at most $_maxTries attempts.');
- if (!_expected.isEmpty) {
- var textList = _expected.map((s) => '"$s"').join(", ");
- description.add(' The error should contain $textList.');
- }
- return description;
- }
-
- Description describeMismatch(SolveResult result, Description description,
- Map state, bool verbose) {
- description.add(state['failures']);
- return description;
- }
-
- bool matches(SolveResult result, Map state) {
- var failures = new StringBuffer();
-
- if (result.succeeded) {
- failures.writeln('Solver succeeded');
- } else {
- if (_expectedType != null && result.error.runtimeType != _expectedType) {
- failures.writeln(
- 'Should have error type $_expectedType, got ' '${result.error.runtimeType}');
- }
-
- var message = result.error.toString();
- for (var expected in _expected) {
- if (!message.contains(expected)) {
- failures.writeln(
- 'Expected error to contain "$expected", got:\n$message');
- }
- }
-
- // Allow 1 here because the greedy solver will only make one attempt.
- if (result.attemptedSolutions != 1 &&
- result.attemptedSolutions != _maxTries) {
- failures.writeln('Took ${result.attemptedSolutions} attempts');
- }
- }
-
- if (!failures.isEmpty) {
- state['failures'] = failures.toString();
- return false;
- }
-
- return true;
- }
-}
-
-/// A source used for testing. This both creates mock package objects and acts
-/// as a source for them.
-///
-/// In order to support testing packages that have the same name but different
-/// descriptions, a package's name is calculated by taking the description
-/// string and stripping off any trailing hyphen followed by non-hyphen
-/// characters.
-class MockSource extends CachedSource {
- final _packages = <String, Map<Version, Package>>{};
-
- /// Keeps track of which package version lists have been requested. Ensures
- /// that a source is only hit once for a given package and that pub
- /// internally caches the results.
- final _requestedVersions = new Set<String>();
-
- /// Keeps track of which package pubspecs have been requested. Ensures that a
- /// source is only hit once for a given package and that pub internally
- /// caches the results.
- final _requestedPubspecs = new Map<String, Set<Version>>();
-
- final String name;
- final hasMultipleVersions = true;
-
- MockSource(this.name);
-
- dynamic parseDescription(String containingPath, description,
- {bool fromLockFile: false}) =>
- description;
-
- bool descriptionsEqual(description1, description2) =>
- description1 == description2;
-
- Future<String> getDirectory(PackageId id) {
- return new Future.value('${id.name}-${id.version}');
- }
-
- Future<List<Version>> getVersions(String name, String description) {
- return new Future.sync(() {
- // Make sure the solver doesn't request the same thing twice.
- if (_requestedVersions.contains(description)) {
- throw new Exception(
- 'Version list for $description was already ' 'requested.');
- }
-
- _requestedVersions.add(description);
-
- if (!_packages.containsKey(description)) {
- throw new Exception(
- 'MockSource does not have a package matching ' '"$description".');
- }
-
- return _packages[description].keys.toList();
- });
- }
-
- Future<Pubspec> describeUncached(PackageId id) {
- return new Future.sync(() {
- // Make sure the solver doesn't request the same thing twice.
- if (_requestedPubspecs.containsKey(id.description) &&
- _requestedPubspecs[id.description].contains(id.version)) {
- throw new Exception('Pubspec for $id was already requested.');
- }
-
- _requestedPubspecs.putIfAbsent(id.description, () => new Set<Version>());
- _requestedPubspecs[id.description].add(id.version);
-
- return _packages[id.description][id.version].pubspec;
- });
- }
-
- Future<Package> downloadToSystemCache(PackageId id) =>
- throw new UnsupportedError('Cannot download mock packages');
-
- List<Package> getCachedPackages() =>
- throw new UnsupportedError('Cannot get mock packages');
-
- Future<Pair<int, int>> repairCachedPackages() =>
- throw new UnsupportedError('Cannot repair mock packages');
-
- void addPackage(String description, Package package) {
- _packages.putIfAbsent(description, () => new Map<Version, Package>());
- _packages[description][package.version] = package;
- }
-}
-
-Package mockPackage(PackageId id, Map dependencyStrings, Map overrides) {
- var sdkConstraint = null;
-
- // Build the pubspec dependencies.
- var dependencies = <PackageDep>[];
- var devDependencies = <PackageDep>[];
-
- dependencyStrings.forEach((spec, constraint) {
- var isDev = spec.startsWith("(dev) ");
- if (isDev) {
- spec = spec.substring("(dev) ".length);
- }
-
- var dep =
- parseSpec(spec).withConstraint(new VersionConstraint.parse(constraint));
-
- if (dep.name == 'sdk') {
- sdkConstraint = dep.constraint;
- return;
- }
-
- if (isDev) {
- devDependencies.add(dep);
- } else {
- dependencies.add(dep);
- }
- });
-
- var dependencyOverrides = <PackageDep>[];
- if (overrides != null) {
- overrides.forEach((spec, constraint) {
- dependencyOverrides.add(
- parseSpec(spec).withConstraint(new VersionConstraint.parse(constraint)));
- });
- }
-
- return new Package.inMemory(
- new Pubspec(
- id.name,
- version: id.version,
- dependencies: dependencies,
- devDependencies: devDependencies,
- dependencyOverrides: dependencyOverrides,
- sdkConstraint: sdkConstraint));
-}
-
-/// Creates a new [PackageId] parsed from [text], which looks something like
-/// this:
-///
-/// foo-xyz 1.0.0 from mock
-///
-/// The package name is "foo". A hyphenated suffix like "-xyz" here is part
-/// of the package description, but not its name, so the description here is
-/// "foo-xyz".
-///
-/// This is followed by an optional [Version]. If [version] is provided, then
-/// it is parsed to a [Version], and [text] should *not* also contain a
-/// version string.
-///
-/// The "from mock" optional suffix is the name of a source for the package.
-/// If omitted, it defaults to "mock1".
-PackageId parseSpec(String text, [String version]) {
- var pattern = new RegExp(r"(([a-z_]*)(-[a-z_]+)?)( ([^ ]+))?( from (.*))?$");
- var match = pattern.firstMatch(text);
- if (match == null) {
- throw new FormatException("Could not parse spec '$text'.");
- }
-
- var description = match[1];
- var name = match[2];
-
- var parsedVersion;
- if (version != null) {
- // Spec string shouldn't also contain a version.
- if (match[5] != null) {
- throw new ArgumentError(
- "Spec '$text' should not contain a version "
- "since '$version' was passed in explicitly.");
- }
- parsedVersion = new Version.parse(version);
- } else {
- if (match[5] != null) {
- parsedVersion = new Version.parse(match[5]);
- } else {
- parsedVersion = Version.none;
- }
- }
-
- var source = "mock1";
- if (match[7] != null) {
- source = match[7];
- if (source == "root") source = null;
- }
-
- return new PackageId(name, source, parsedVersion, description);
-}
diff --git a/sdk/lib/async/broadcast_stream_controller.dart b/sdk/lib/async/broadcast_stream_controller.dart
index c2cd4ab..93c0833 100644
--- a/sdk/lib/async/broadcast_stream_controller.dart
+++ b/sdk/lib/async/broadcast_stream_controller.dart
@@ -337,12 +337,23 @@
}
}
-class _SyncBroadcastStreamController<T> extends _BroadcastStreamController<T> {
+class _SyncBroadcastStreamController<T> extends _BroadcastStreamController<T>
+ implements SynchronousStreamController<T> {
_SyncBroadcastStreamController(void onListen(), void onCancel())
: super(onListen, onCancel);
// EventDispatch interface.
+ bool get _mayAddEvent => super._mayAddEvent && !_isFiring;
+
+ _addEventError() {
+ if (_isFiring) {
+ return new StateError(
+ "Cannot fire new event. Controller is already firing an event");
+ }
+ return super._addEventError();
+ }
+
void _sendData(T data) {
if (_isEmpty) return;
if (_hasOneListener) {
diff --git a/sdk/lib/async/stream_controller.dart b/sdk/lib/async/stream_controller.dart
index 0b470b8..a4116cd 100644
--- a/sdk/lib/async/stream_controller.dart
+++ b/sdk/lib/async/stream_controller.dart
@@ -53,10 +53,9 @@
/**
* A controller with a [stream] that supports only one single subscriber.
*
- * If [sync] is true, events may be passed directly to the stream's listener
- * during an [add], [addError] or [close] call. If [sync] is false, the event
- * will be passed to the listener at a later time, after the code creating
- * the event has returned.
+ * If [sync] is true, the returned stream controller is a
+ * [SynchronousStreamController], and must be used with the care
+ * and attention necessary to not break the [Stream] contract.
*
* The controller will buffer all incoming events until the subscriber is
* registered.
@@ -108,10 +107,13 @@
*
* If [sync] is true, events may be fired directly by the stream's
* subscriptions during an [add], [addError] or [close] call.
- * If [sync] is false, the event will be fired at a later time,
- * after the code adding the event has completed.
+ * The returned stream controller is a [SynchronousStreamController],
+ * and must be used with the care and attention necessary to not break
+ * the [Stream] contract.
*
- * When [sync] is false, no guarantees are given with regard to when
+ * If [sync] is false, the event will always be fired at a later time,
+ * after the code adding the event has completed.
+ * In that case, no guarantees are given with regard to when
* multiple listeners get the events, except that each listener will get
* all events in the correct order. Each subscription handles the events
* individually.
@@ -202,6 +204,103 @@
}
+/**
+ * A stream controller that delivers its events synchronously.
+ *
+ * A synchronous stream controller is intended for cases where
+ * an already asynchronous event triggers an event on a stream.
+ *
+ * Instead of adding the event to the stream in a later microtask,
+ * causing extra latency, the event is instead fired immediately by the
+ * synchronous stream controller, as if the stream event was
+ * the current event or microtask.
+ *
+ * The synchronous stream controller can be used to break the contract
+ * on [Stream], and it must be used carefully to avoid doing so.
+ *
+ * The only advantage to using a [SynchronousStreamController] over a
+ * normal [StreamController] is the improved latency.
+ * Only use the synchronous version if the improvement is significant,
+ * and if its use is safe. Otherwise just use a normal stream controller,
+ * which will always have the correct behavior for a [Stream], and won't
+ * accidentally break other code.
+ *
+ * Adding events to a synchronous controller should only happen as the
+ * very last part of a the handling of the original event.
+ * At that point, adding an event to the stream is equivalent to
+ * returning to the event loop and adding the event in the next microtask.
+ *
+ * Each listener callback will be run as if it was a top-level event
+ * or microtask. This means that if it throws, the error will be reported as
+ * uncaught as soon as possible.
+ * This is one reason to add the event as the last thing in the original event
+ * handler - any action done after adding the event will delay the report of
+ * errors in the event listener callbacks.
+ *
+ * If an event is added in a setting that isn't known to be another event,
+ * it may cause the stream's listener to get that event before the listener
+ * is ready to handle it. We promise that after calling [Stream.listen],
+ * you won't get any events until the code doing the listen has completed.
+ * Calling [add] in response to a function call of unknown origin may break
+ * that promise.
+ *
+ * An [onListen] callback from the controller is *not* an asynchronous event,
+ * and adding events to the controller in the `onListen` callback is always
+ * wrong. The events will be delivered before the listener has even received
+ * the subscription yet.
+ *
+ * The synchronous broadcast stream controller also has a restrictions that a
+ * normal stream controller does not:
+ * The [add], [addError], [close] and [addStream] methods *must not* be
+ * called while an event is being delivered.
+ * That is, if a callback on a subscription on the controller's stream causes
+ * a call to any of the functions above, the call will fail.
+ * A broadcast stream may have more than one listener, and if an
+ * event is added synchronously while another is being also in the process
+ * of being added, the latter event might reach some listeners before
+ * the former. To prevent that, an event cannot be added while a previous
+ * event is being fired.
+ * This guarantees that an event is fully delivered when the
+ * first [add], [addError] or [close] returns,
+ * and further events will be delivered in the correct order.
+ *
+ * This still only guarantees that the event is delivered to the subscription.
+ * If the subscription is paused, the actual callback may still happen later,
+ * and the event will instead be buffered by the subscription.
+ * Barring pausing, and the following buffered events that haven't been
+ * delivered yet, callbacks will be called synchronously when an event is added.
+ *
+ * Adding an event to a synchronous non-broadcast stream controller while
+ * another event is in progress may cause the second event to be delayed
+ * and not be delivered synchronously, and until that event is delivered,
+ * the controller will not act synchronously.
+ */
+abstract class SynchronousStreamController<T> implements StreamController<T> {
+ /**
+ * Adds event to the controller's stream.
+ *
+ * As [StreamController.add], but must not be called while an event is
+ * being added by [add], [addError] or [close].
+ */
+ void add(T data);
+
+ /**
+ * Adds error to the controller's stream.
+ *
+ * As [StreamController.addError], but must not be called while an event is
+ * being added by [add], [addError] or [close].
+ */
+ void addError(Object error, [StackTrace stackTrace]);
+
+ /**
+ * Closes the controller's stream.
+ *
+ * As [StreamController.close], but must not be called while an event is
+ * being added by [add], [addError] or [close].
+ */
+ Future close();
+}
+
abstract class _StreamControllerLifecycle<T> {
StreamSubscription<T> _subscribe(
void onData(T data),
@@ -421,8 +520,8 @@
* Send or enqueue an error event.
*/
void addError(Object error, [StackTrace stackTrace]) {
- error = _nonNullError(error);
if (!_mayAddEvent) throw _badEventState();
+ error = _nonNullError(error);
AsyncError replacement = Zone.current.errorCallback(error, stackTrace);
if (replacement != null) {
error = _nonNullError(replacement.error);
@@ -440,7 +539,8 @@
* You are allowed to close the controller more than once, but only the first
* call has any effect.
*
- * After closing, no further events may be added using [add] or [addError].
+ * After closing, no further events may be added using [add], [addError]
+ * or [addStream].
*
* The returned future is completed when the done event has been delivered.
*/
@@ -590,7 +690,10 @@
}
abstract class _SyncStreamControllerDispatch<T>
- implements _StreamController<T> {
+ implements _StreamController<T>, SynchronousStreamController<T> {
+ int get _state;
+ void set _state(int state);
+
void _sendData(T data) {
_subscription._add(data);
}
diff --git a/sdk/lib/async/stream_pipe.dart b/sdk/lib/async/stream_pipe.dart
index ca1164d..a2fc15d 100644
--- a/sdk/lib/async/stream_pipe.dart
+++ b/sdk/lib/async/stream_pipe.dart
@@ -308,20 +308,32 @@
class _TakeStream<T> extends _ForwardingStream<T, T> {
- int _remaining;
+ final int _count;
_TakeStream(Stream<T> source, int count)
- : this._remaining = count, super(source) {
+ : this._count = count, super(source) {
// This test is done early to avoid handling an async error
// in the _handleData method.
if (count is! int) throw new ArgumentError(count);
}
+ StreamSubscription<T> _createSubscription(
+ void onData(T data),
+ Function onError,
+ void onDone(),
+ bool cancelOnError) {
+ return new _StateStreamSubscription<T>(
+ this, onData, onError, onDone, cancelOnError, _count);
+ }
+
void _handleData(T inputEvent, _EventSink<T> sink) {
- if (_remaining > 0) {
+ _StateStreamSubscription subscription = sink;
+ int count = subscription._count;
+ if (count > 0) {
sink._add(inputEvent);
- _remaining -= 1;
- if (_remaining == 0) {
+ count -= 1;
+ subscription._count = count;
+ if (count == 0) {
// Closing also unsubscribes all subscribers, which unsubscribes
// this from source.
sink._close();
@@ -330,6 +342,26 @@
}
}
+/**
+ * A [_ForwardingStreamSubscription] with one extra state field.
+ *
+ * Use by several different classes, some storing an integer, others a bool.
+ */
+class _StateStreamSubscription<T> extends _ForwardingStreamSubscription<T, T> {
+ // Raw state field. Typed access provided by getters and setters below.
+ var _sharedState;
+
+ _StateStreamSubscription(_ForwardingStream stream, void onData(T data),
+ Function onError, void onDone(),
+ bool cancelOnError, this._sharedState)
+ : super(stream, onData, onError, onDone, cancelOnError);
+
+ bool get _flag => _sharedState;
+ void set _flag(bool flag) { _sharedState = flag; }
+ int get _count => _sharedState;
+ void set _count(int count) { _sharedState = count; }
+}
+
class _TakeWhileStream<T> extends _ForwardingStream<T, T> {
final _Predicate<T> _test;
@@ -356,18 +388,29 @@
}
class _SkipStream<T> extends _ForwardingStream<T, T> {
- int _remaining;
+ final int _count;
_SkipStream(Stream<T> source, int count)
- : this._remaining = count, super(source) {
+ : this._count = count, super(source) {
// This test is done early to avoid handling an async error
// in the _handleData method.
if (count is! int || count < 0) throw new ArgumentError(count);
}
+ StreamSubscription<T> _createSubscription(
+ void onData(T data),
+ Function onError,
+ void onDone(),
+ bool cancelOnError) {
+ return new _StateStreamSubscription<T>(
+ this, onData, onError, onDone, cancelOnError, _count);
+ }
+
void _handleData(T inputEvent, _EventSink<T> sink) {
- if (_remaining > 0) {
- _remaining--;
+ _StateStreamSubscription subscription = sink;
+ int count = subscription._count;
+ if (count > 0) {
+ subscription._count = count - 1;
return;
}
sink._add(inputEvent);
@@ -376,13 +419,23 @@
class _SkipWhileStream<T> extends _ForwardingStream<T, T> {
final _Predicate<T> _test;
- bool _hasFailed = false;
_SkipWhileStream(Stream<T> source, bool test(T value))
: this._test = test, super(source);
+ StreamSubscription<T> _createSubscription(
+ void onData(T data),
+ Function onError,
+ void onDone(),
+ bool cancelOnError) {
+ return new _StateStreamSubscription<T>(
+ this, onData, onError, onDone, cancelOnError, false);
+ }
+
void _handleData(T inputEvent, _EventSink<T> sink) {
- if (_hasFailed) {
+ _StateStreamSubscription subscription = sink;
+ bool hasFailed = subscription._flag;
+ if (hasFailed) {
sink._add(inputEvent);
return;
}
@@ -392,11 +445,11 @@
} catch (e, s) {
_addErrorWithReplacement(sink, e, s);
// A failure to return a boolean is considered "not matching".
- _hasFailed = true;
+ subscription._flag = true;
return;
}
if (!satisfies) {
- _hasFailed = true;
+ subscription._flag = true;
sink._add(inputEvent);
}
}
diff --git a/sdk/lib/core/errors.dart b/sdk/lib/core/errors.dart
index a673406..3d36b39 100644
--- a/sdk/lib/core/errors.dart
+++ b/sdk/lib/core/errors.dart
@@ -171,7 +171,7 @@
: this.value(null, name, "Must not be null");
// Helper functions for toString overridden in subclasses.
- String get _errorName => "Invalid argument${name == null ? "(s)" : ""}";
+ String get _errorName => "Invalid argument${!_hasValue ? "(s)" : ""}";
String get _errorExplanation => "";
String toString() {
@@ -179,9 +179,9 @@
if (name != null) {
nameString = " ($name)";
}
- var message = this.message == null ? "" : ": ${this.message}";
+ var message = (this.message == null) ? "" : ": ${this.message}";
String prefix = "$_errorName$nameString$message";
- if (invalidValue == null) return prefix;
+ if (!_hasValue) return prefix;
// If we know the invalid value, we can try to describe the problem.
String explanation = _errorExplanation;
String errorValue = Error.safeToString(invalidValue);
diff --git a/sdk/lib/core/list.dart b/sdk/lib/core/list.dart
index d4f6cfa..05c4c2e 100644
--- a/sdk/lib/core/list.dart
+++ b/sdk/lib/core/list.dart
@@ -441,6 +441,10 @@
* list.join(', '); // '1, 6, 7, 5'
*
* An error occurs if [start]..[end] is not a valid range for `this`.
+ *
+ * This method does not work on fixed-length lists, even when [replacement]
+ * has the same number of elements as the replaced range. In that case use
+ * [setRange] instead.
*/
void replaceRange(int start, int end, Iterable<E> replacement);
diff --git a/sdk/lib/core/string.dart b/sdk/lib/core/string.dart
index e4a1c1d..625446f 100644
--- a/sdk/lib/core/string.dart
+++ b/sdk/lib/core/string.dart
@@ -414,7 +414,7 @@
bool contains(Pattern other, [int startIndex = 0]);
/**
- * Returns a new string in which the first occurence of [from] in this string
+ * Returns a new string in which the first occurence of [from] in this string
* is replaced with [to], starting from [startIndex]:
*
* '0.0001'.replaceFirst(new RegExp(r'0'), ''); // '.0001'
@@ -423,6 +423,20 @@
String replaceFirst(Pattern from, String to, [int startIndex = 0]);
/**
+ * Replace the first occurence of [from] in this string.
+ *
+ * Returns a new string, which is this string
+ * except that the first match of [pattern], starting from [startIndex],
+ * is replaced by the result of calling [replace] with the match object.
+ *
+ * If the value returned by calling `replace` is not a [String], it
+ * is converted to a `String` using its `toString` method, which must
+ * then return a string.
+ */
+ String replaceFirstMapped(Pattern from, String replace(Match match),
+ [int startIndex = 0]);
+
+ /**
* Replaces all substrings that match [from] with [replace].
*
* Returns a new string in which the non-overlapping substrings matching
diff --git a/sdk/lib/html/dartium/html_dartium.dart b/sdk/lib/html/dartium/html_dartium.dart
index 63d97d7..bf43c15 100644
--- a/sdk/lib/html/dartium/html_dartium.dart
+++ b/sdk/lib/html/dartium/html_dartium.dart
@@ -40487,6 +40487,11 @@
}
var className = MirrorSystem.getName(cls.simpleName);
+ if (cls.isAbstract) {
+ throw new UnsupportedError('Invalid custom element '
+ 'class $className is abstract.');
+ }
+
var createdConstructor = cls.declarations[new Symbol('$className.created')];
if (createdConstructor == null ||
createdConstructor is! MethodMirror ||
diff --git a/sdk/lib/internal/iterable.dart b/sdk/lib/internal/iterable.dart
index 87c5f14..bc80b88 100644
--- a/sdk/lib/internal/iterable.dart
+++ b/sdk/lib/internal/iterable.dart
@@ -757,404 +757,6 @@
bool movePrevious();
}
-/**
- * This class provides default implementations for Iterables (including Lists).
- *
- * The uses of this class will be replaced by mixins.
- */
-class IterableMixinWorkaround<T> {
- static bool contains(Iterable iterable, var element) {
- for (final e in iterable) {
- if (e == element) return true;
- }
- return false;
- }
-
- static void forEach(Iterable iterable, void f(o)) {
- for (final e in iterable) {
- f(e);
- }
- }
-
- static bool any(Iterable iterable, bool f(o)) {
- for (final e in iterable) {
- if (f(e)) return true;
- }
- return false;
- }
-
- static bool every(Iterable iterable, bool f(o)) {
- for (final e in iterable) {
- if (!f(e)) return false;
- }
- return true;
- }
-
- static dynamic reduce(Iterable iterable,
- dynamic combine(previousValue, element)) {
- Iterator iterator = iterable.iterator;
- if (!iterator.moveNext()) throw IterableElementError.noElement();
- var value = iterator.current;
- while (iterator.moveNext()) {
- value = combine(value, iterator.current);
- }
- return value;
- }
-
- static dynamic fold(Iterable iterable,
- dynamic initialValue,
- dynamic combine(dynamic previousValue, element)) {
- for (final element in iterable) {
- initialValue = combine(initialValue, element);
- }
- return initialValue;
- }
-
- /**
- * Removes elements matching [test] from [list].
- *
- * This is performed in two steps, to avoid exposing an inconsistent state
- * to the [test] function. First the elements to retain are found, and then
- * the original list is updated to contain those elements.
- */
- static void removeWhereList(List list, bool test(var element)) {
- List retained = [];
- int length = list.length;
- for (int i = 0; i < length; i++) {
- var element = list[i];
- if (!test(element)) {
- retained.add(element);
- }
- if (length != list.length) {
- throw new ConcurrentModificationError(list);
- }
- }
- if (retained.length == length) return;
- list.length = retained.length;
- for (int i = 0; i < retained.length; i++) {
- list[i] = retained[i];
- }
- }
-
- static bool isEmpty(Iterable iterable) {
- return !iterable.iterator.moveNext();
- }
-
- static dynamic first(Iterable iterable) {
- Iterator it = iterable.iterator;
- if (!it.moveNext()) {
- throw IterableElementError.noElement();
- }
- return it.current;
- }
-
- static dynamic last(Iterable iterable) {
- Iterator it = iterable.iterator;
- if (!it.moveNext()) {
- throw IterableElementError.noElement();
- }
- dynamic result;
- do {
- result = it.current;
- } while(it.moveNext());
- return result;
- }
-
- static dynamic single(Iterable iterable) {
- Iterator it = iterable.iterator;
- if (!it.moveNext()) throw IterableElementError.noElement();
- dynamic result = it.current;
- if (it.moveNext()) throw IterableElementError.tooMany();
- return result;
- }
-
- static dynamic firstWhere(Iterable iterable,
- bool test(dynamic value),
- dynamic orElse()) {
- for (dynamic element in iterable) {
- if (test(element)) return element;
- }
- if (orElse != null) return orElse();
- throw IterableElementError.noElement();
- }
-
- static dynamic lastWhere(Iterable iterable,
- bool test(dynamic value),
- dynamic orElse()) {
- dynamic result = null;
- bool foundMatching = false;
- for (dynamic element in iterable) {
- if (test(element)) {
- result = element;
- foundMatching = true;
- }
- }
- if (foundMatching) return result;
- if (orElse != null) return orElse();
- throw IterableElementError.noElement();
- }
-
- static dynamic lastWhereList(List list,
- bool test(dynamic value),
- dynamic orElse()) {
- // TODO(floitsch): check that arguments are of correct type?
- for (int i = list.length - 1; i >= 0; i--) {
- dynamic element = list[i];
- if (test(element)) return element;
- }
- if (orElse != null) return orElse();
- throw IterableElementError.noElement();
- }
-
- static dynamic singleWhere(Iterable iterable, bool test(dynamic value)) {
- dynamic result = null;
- bool foundMatching = false;
- for (dynamic element in iterable) {
- if (test(element)) {
- if (foundMatching) {
- throw IterableElementError.tooMany();
- }
- result = element;
- foundMatching = true;
- }
- }
- if (foundMatching) return result;
- throw IterableElementError.noElement();
- }
-
- static elementAt(Iterable iterable, int index) {
- if (index is! int) throw new ArgumentError.notNull("index");
- RangeError.checkNotNegative(index, "index");
- int elementIndex = 0;
- for (var element in iterable) {
- if (index == elementIndex) return element;
- elementIndex++;
- }
- throw new RangeError.index(index, iterable, "index", null, elementIndex);
- }
-
- static String join(Iterable iterable, [String separator]) {
- StringBuffer buffer = new StringBuffer();
- buffer.writeAll(iterable, separator);
- return buffer.toString();
- }
-
- static String joinList(List list, [String separator]) {
- if (list.isEmpty) return "";
- if (list.length == 1) return "${list[0]}";
- StringBuffer buffer = new StringBuffer();
- if (separator.isEmpty) {
- for (int i = 0; i < list.length; i++) {
- buffer.write(list[i]);
- }
- } else {
- buffer.write(list[0]);
- for (int i = 1; i < list.length; i++) {
- buffer.write(separator);
- buffer.write(list[i]);
- }
- }
- return buffer.toString();
- }
-
- Iterable<T> where(Iterable iterable, bool f(var element)) {
- return new WhereIterable<T>(iterable, f);
- }
-
- static Iterable map(Iterable iterable, f(var element)) {
- return new MappedIterable(iterable, f);
- }
-
- static Iterable mapList(List list, f(var element)) {
- return new MappedListIterable(list, f);
- }
-
- static Iterable expand(Iterable iterable, Iterable f(var element)) {
- return new ExpandIterable(iterable, f);
- }
-
- Iterable<T> takeList(List list, int n) {
- // The generic type is currently lost. It will be fixed with mixins.
- return new SubListIterable<T>(list, 0, n);
- }
-
- Iterable<T> takeWhile(Iterable iterable, bool test(var value)) {
- // The generic type is currently lost. It will be fixed with mixins.
- return new TakeWhileIterable<T>(iterable, test);
- }
-
- Iterable<T> skipList(List list, int n) {
- // The generic type is currently lost. It will be fixed with mixins.
- return new SubListIterable<T>(list, n, null);
- }
-
- Iterable<T> skipWhile(Iterable iterable, bool test(var value)) {
- // The generic type is currently lost. It will be fixed with mixins.
- return new SkipWhileIterable<T>(iterable, test);
- }
-
- Iterable<T> reversedList(List list) {
- return new ReversedListIterable<T>(list);
- }
-
- static void sortList(List list, int compare(a, b)) {
- if (compare == null) compare = Comparable.compare;
- Sort.sort(list, compare);
- }
-
- static void shuffleList(List list, Random random) {
- if (random == null) random = new Random();
- int length = list.length;
- while (length > 1) {
- int pos = random.nextInt(length);
- length -= 1;
- var tmp = list[length];
- list[length] = list[pos];
- list[pos] = tmp;
- }
- }
-
- static int indexOfList(List list, var element, int start) {
- return Lists.indexOf(list, element, start, list.length);
- }
-
- static int lastIndexOfList(List list, var element, int start) {
- if (start == null) start = list.length - 1;
- return Lists.lastIndexOf(list, element, start);
- }
-
- static void _rangeCheck(List list, int start, int end) {
- RangeError.checkValidRange(start, end, list.length);
- }
-
- Iterable<T> getRangeList(List list, int start, int end) {
- _rangeCheck(list, start, end);
- // The generic type is currently lost. It will be fixed with mixins.
- return new SubListIterable<T>(list, start, end);
- }
-
- static void setRangeList(List list, int start, int end,
- Iterable from, int skipCount) {
- _rangeCheck(list, start, end);
- int length = end - start;
- if (length == 0) return;
-
- if (skipCount < 0) throw new ArgumentError(skipCount);
-
- // TODO(floitsch): Make this accept more.
- List otherList;
- int otherStart;
- if (from is List) {
- otherList = from;
- otherStart = skipCount;
- } else {
- otherList = from.skip(skipCount).toList(growable: false);
- otherStart = 0;
- }
- if (otherStart + length > otherList.length) {
- throw IterableElementError.tooFew();
- }
- Lists.copy(otherList, otherStart, list, start, length);
- }
-
- static void replaceRangeList(List list, int start, int end,
- Iterable iterable) {
- _rangeCheck(list, start, end);
- if (iterable is! EfficientLength) {
- iterable = iterable.toList();
- }
- int removeLength = end - start;
- int insertLength = iterable.length;
- if (removeLength >= insertLength) {
- int delta = removeLength - insertLength;
- int insertEnd = start + insertLength;
- int newEnd = list.length - delta;
- list.setRange(start, insertEnd, iterable);
- if (delta != 0) {
- list.setRange(insertEnd, newEnd, list, end);
- list.length = newEnd;
- }
- } else {
- int delta = insertLength - removeLength;
- int newLength = list.length + delta;
- int insertEnd = start + insertLength; // aka. end + delta.
- list.length = newLength;
- list.setRange(insertEnd, newLength, list, end);
- list.setRange(start, insertEnd, iterable);
- }
- }
-
- static void fillRangeList(List list, int start, int end, fillValue) {
- _rangeCheck(list, start, end);
- for (int i = start; i < end; i++) {
- list[i] = fillValue;
- }
- }
-
- static void insertAllList(List list, int index, Iterable iterable) {
- RangeError.checkValueInInterval(index, 0, list.length, "index");
- if (iterable is! EfficientLength) {
- iterable = iterable.toList(growable: false);
- }
- int insertionLength = iterable.length;
- list.length += insertionLength;
- list.setRange(index + insertionLength, list.length, list, index);
- for (var element in iterable) {
- list[index++] = element;
- }
- }
-
- static void setAllList(List list, int index, Iterable iterable) {
- RangeError.checkValueInInterval(index, 0, list.length, "index");
- for (var element in iterable) {
- list[index++] = element;
- }
- }
-
- Map<int, T> asMapList(List l) {
- return new ListMapView<T>(l);
- }
-
- static bool setContainsAll(Set set, Iterable other) {
- for (var element in other) {
- if (!set.contains(element)) return false;
- }
- return true;
- }
-
- static Set setIntersection(Set set, Set other, Set result) {
- Set smaller;
- Set larger;
- if (set.length < other.length) {
- smaller = set;
- larger = other;
- } else {
- smaller = other;
- larger = set;
- }
- for (var element in smaller) {
- if (larger.contains(element)) {
- result.add(element);
- }
- }
- return result;
- }
-
- static Set setUnion(Set set, Set other, Set result) {
- result.addAll(set);
- result.addAll(other);
- return result;
- }
-
- static Set setDifference(Set set, Set other, Set result) {
- for (var element in set) {
- if (!other.contains(element)) {
- result.add(element);
- }
- }
- return result;
- }
-}
/**
* Creates errors throw by [Iterable] when the element count is wrong.
diff --git a/sdk/lib/io/platform.dart b/sdk/lib/io/platform.dart
index 12e152c..134cd21 100644
--- a/sdk/lib/io/platform.dart
+++ b/sdk/lib/io/platform.dart
@@ -173,6 +173,11 @@
/**
* Returns the version of the current Dart runtime.
+ *
+ * The returned `String` is formatted as the
+ * [semver](http://semver.org) version string of the current dart
+ * runtime, possibly followed by whitespace and other version and
+ * build details.
*/
static String get version => _version;
}
diff --git a/sdk/lib/mirrors/mirrors.dart b/sdk/lib/mirrors/mirrors.dart
index d16e62e..1c30bdc 100644
--- a/sdk/lib/mirrors/mirrors.dart
+++ b/sdk/lib/mirrors/mirrors.dart
@@ -286,9 +286,35 @@
bool get isTopLevel;
/**
- * The source location of this Dart language entity.
+ * The source location of this Dart language entity, or [:null:] if the
+ * entity is synthetic.
*
- * This operation is optional and may return [:null:].
+ * If the reflectee is a variable, the returned location gives the position of * the variable name at its point of declaration.
+ *
+ * If the reflectee is a library, class, typedef, function or type variable
+ * with associated metadata, the returned location gives the position of the
+ * first metadata declaration associated with the reflectee.
+ *
+ * Otherwise:
+ * If the reflectee is a library, the returned location gives the position of
+ * the keyword 'library' at the reflectee's point of declaration, if the
+ * reflectee is a named library, or the first character of the first line in
+ * the compilation unit defining the reflectee if the reflectee is anonymous.
+ *
+ * If the reflectee is an abstract class, the returned location gives the
+ * position of the keyword 'abstract' at the reflectee's point of declaration. * Otherwise, if the reflectee is a class, the returned location gives the
+ * position of the keyword 'class' at the reflectee's point of declaration.
+ *
+ * If the reflectee is a typedef the returned location gives the position of
+ * the of the keyword 'typedef' at the reflectee's point of declaration.
+ *
+ * If the reflectee is a function with a declared return type, the returned
+ * location gives the position of the function's return type at the
+ * reflectee's point of declaration. Otherwise. the returned location gives
+ * the position of the function's name at the reflectee's point of
+ * declaration.
+ *
+ * This operation is optional and may throw an [UnsupportedError].
*/
SourceLocation get location;
@@ -578,6 +604,10 @@
/// Is `true` if this dependency is an export.
bool get isExport;
+ /// Returns true iff this dependency is a deferred import. Otherwise returns
+ /// false.
+ bool get isDeferred;
+
/// Returns the library mirror of the library that imports or exports the
/// [targetLibrary].
LibraryMirror get sourceLibrary;
diff --git a/site/try/src/interaction_manager.dart b/site/try/src/interaction_manager.dart
index 7df3923..6106df0 100644
--- a/site/try/src/interaction_manager.dart
+++ b/site/try/src/interaction_manager.dart
@@ -1106,7 +1106,7 @@
}
Token tokenize(String text) {
- var file = new StringSourceFile('', text);
+ var file = new StringSourceFile.fromName('', text);
return new StringScanner(file, includeComments: true).tokenize();
}
diff --git a/tests/co19/co19-dart2js.status b/tests/co19/co19-dart2js.status
index 49362dc..93373f4 100644
--- a/tests/co19/co19-dart2js.status
+++ b/tests/co19/co19-dart2js.status
@@ -1138,8 +1138,6 @@
WebPlatformTest/html-templates/innerhtml-on-templates/innerhtml_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-head-insertion-mode/generating-of-implied-end-tags_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-head-insertion-mode/template-end-tag-without-start-one_t01: RuntimeError # Please triage this failure
-WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-body-context_t01: RuntimeError # Please triage this failure
-WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/creating-an-element-for-the-token/template-owner-document_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/template-element/template-as-a-descendant_t01: RuntimeError # Please triage this failure
WebPlatformTest/html/browsers/browsing-the-web/read-media/pageload-image_t01: RuntimeError # Please triage this failure
@@ -2755,8 +2753,6 @@
WebPlatformTest/html-templates/additions-to-the-steps-to-clone-a-node/templates-copy-document-owner_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/innerhtml-on-templates/innerhtml_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-head-insertion-mode/generating-of-implied-end-tags_t01: RuntimeError # Please triage this failure
-WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-body-context_t01: RuntimeError # Please triage this failure
-WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/creating-an-element-for-the-token/template-owner-document_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/template-element/node-document-changes_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/template-element/template-as-a-descendant_t01: RuntimeError # Please triage this failure
@@ -3641,6 +3637,7 @@
LayoutTests/fast/loader/about-blank-hash-change_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/loader/about-blank-hash-kept_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/loader/hashchange-event-properties_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/loader/loadInProgress_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/loader/onhashchange-attribute-listeners_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/loader/scroll-position-restored-on-back_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/loader/scroll-position-restored-on-reload-at-load-event_t01: RuntimeError # Please triage this failure
@@ -3690,6 +3687,7 @@
LayoutTests/fast/replaced/container-width-zero_t01: RuntimeError # Please triage this failure
LayoutTests/fast/replaced/iframe-with-percentage-height-within-table-with-anonymous-table-cell_t01: RuntimeError # Please triage this failure
LayoutTests/fast/replaced/iframe-with-percentage-height-within-table-with-table-cell-ignore-height_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/replaced/preferred-widths_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/replaced/table-percent-height-text-controls_t01: RuntimeError # Please triage this failure
LayoutTests/fast/replaced/table-percent-height_t01: RuntimeError # Please triage this failure
LayoutTests/fast/replaced/table-percent-width_t01: RuntimeError # Please triage this failure
@@ -4009,8 +4007,6 @@
WebPlatformTest/html-templates/innerhtml-on-templates/innerhtml_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-head-insertion-mode/generating-of-implied-end-tags_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-head-insertion-mode/template-end-tag-without-start-one_t01: RuntimeError # Please triage this failure
-WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-body-context_t01: RuntimeError # Please triage this failure
-WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/creating-an-element-for-the-token/template-owner-document_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/template-element/node-document-changes_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/template-element/template-as-a-descendant_t01: RuntimeError # Please triage this failure
@@ -6466,7 +6462,7 @@
LayoutTests/fast/events/scroll-event-does-not-bubble_t01: RuntimeError # Please triage this failure
LayoutTests/fast/events/selectstart-prevent-selectall_t01: RuntimeError # Please triage this failure
LayoutTests/fast/events/submit-reset-nested-bubble_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/events/tabindex-removal-from-focused-element_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/events/tabindex-removal-from-focused-element_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/events/wheelevent-constructor_t01: RuntimeError # Please triage this failure
LayoutTests/fast/eventsource/eventsource-attribute-listeners_t01: RuntimeError # Please triage this failure
LayoutTests/fast/eventsource/eventsource-constructor_t01: RuntimeError # Please triage this failure
@@ -7337,9 +7333,9 @@
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-head-insertion-mode/generating-of-implied-end-tags_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-table-insertion-mode/end-tag-table_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/appending-to-a-template/template-child-nodes_t01: RuntimeError # Please triage this failure
+WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-row-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-body-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-context_t01: RuntimeError # Please triage this failure
-WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-row-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/creating-an-element-for-the-token/template-owner-document_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/serializing-html-templates/outerhtml_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/template-element/content-attribute_t01: RuntimeError # Please triage this failure
@@ -7939,7 +7935,7 @@
LayoutTests/fast/css/link-alternate-stylesheet-3_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/link-alternate-stylesheet-4_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/link-alternate-stylesheet-5_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/css/link-disabled-attr-parser_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/css/link-disabled-attr-parser_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/css/list-item-text-align_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/margin-start-end_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/max-device-aspect-ratio_t01: Pass, RuntimeError # Please triage this failure
@@ -9211,9 +9207,9 @@
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-head-insertion-mode/generating-of-implied-end-tags_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/additions-to-the-in-table-insertion-mode/end-tag-table_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/appending-to-a-template/template-child-nodes_t01: RuntimeError # Please triage this failure
+WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-row-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-body-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-context_t01: RuntimeError # Please triage this failure
-WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-row-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/creating-an-element-for-the-token/template-owner-document_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/serializing-html-templates/outerhtml_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/template-element/content-attribute_t01: RuntimeError # Please triage this failure
diff --git a/tests/co19/co19-dartium.status b/tests/co19/co19-dartium.status
index 758d027..77a5909 100644
--- a/tests/co19/co19-dartium.status
+++ b/tests/co19/co19-dartium.status
@@ -1013,54 +1013,54 @@
WebPlatformTest/html/semantics/forms/the-datalist-element/datalistoptions_t01: Skip # Issue 20540.
[ $compiler == none && $runtime == ContentShellOnAndroid ]
-LibTest/collection/ListBase/ListBase_class_A01_t02: Skip # Times out flakily. Issue 20956
-LibTest/core/List/List_class_A01_t02: Skip # Times out flakily. Issue 20956
-LibTest/html/Element/getBoundingClientRect_A01_t02: RuntimeError # Issue 19127.
-LibTest/html/Window/animationFrame_A01_t01: Skip # Times out. co19-roll r786: Please triage this failure.
-LibTest/math/log_A01_t01: Pass, Fail # co19 issue 44.
-LayoutTests/fast/canvas/canvas-composite-text-alpha_t01: RuntimeError # co19-roll r761: Please triage this failure.
-LayoutTests/fast/canvas/canvas-scale-drawImage-shadow_t01: RuntimeError, Pass # co19-roll r761: Please triage this failure.
-LayoutTests/fast/canvas/canvas-scale-fillPath-shadow_t01: RuntimeError, Pass # co19-roll r761: Please triage this failure.
-LayoutTests/fast/canvas/canvas-scale-fillRect-shadow_t01: Skip # Times out. co19-roll r761: Please triage this failure.
+LayoutTests/fast/canvas/canvas-composite-text-alpha_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/canvas/canvas-scale-drawImage-shadow_t01: RuntimeError, Pass # Please triage this failure.
+LayoutTests/fast/canvas/canvas-scale-fillPath-shadow_t01: RuntimeError, Pass # Please triage this failure.
+LayoutTests/fast/canvas/canvas-scale-fillRect-shadow_t01: Skip # Times out. Please triage this failure.
LayoutTests/fast/canvas/canvas-scale-shadowBlur_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/canvas-scale-strokePath-shadow_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/canvas-strokePath-alpha-shadow_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/canvas-strokePath-gradient-shadow_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/canvas-strokeRect-alpha-shadow_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/canvas-strokeRect-gradient-shadow_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/canvas/canvas-transforms-fillRect-shadow_t01: RuntimeError, Pass # co19-roll r761: Please triage this failure.
-LayoutTests/fast/canvas/webgl/canvas-test_t01: RuntimeError, Pass # co19-roll r761: Please triage this failure.
-LayoutTests/fast/canvas/webgl/webgl-large-texture_t01: Skip # Times out flakily. co19-roll r761: Please triage this failure.
-LayoutTests/fast/css/getComputedStyle/computed-style-select-overflow_t01: RuntimeError # co19-roll r761: Please triage this failure.
-LayoutTests/fast/css/vertical-align-length-copy-bug_t01: RuntimeError # co19-roll r761: Please triage this failure.
-LayoutTests/fast/css-generated-content/bug-106384_t01: Skip # Times out. co19-roll r786: Please triage this failure.
-LayoutTests/fast/css-generated-content/empty-first-letter-with-columns-crash_t01: Skip # Times out. co19-roll r786: Please triage this failure.
-LayoutTests/fast/css-generated-content/hit-test-generated-content_t01: RuntimeError # co19-roll r786: Please triage this failure.
-LayoutTests/fast/css-intrinsic-dimensions/css-tables_t01: RuntimeError # co19-roll r786: Please triage this failure.
-LayoutTests/fast/css-intrinsic-dimensions/tables_t01: RuntimeError # co19-roll r786: Please triage this failure.
-LayoutTests/fast/filesystem/file-writer-abort-continue_t01: Skip # Times out. co19-roll r786: Please triage this failure.
-LayoutTests/fast/text/international/listbox-width-rtl_t01: RuntimeError # co19-roll r786: Please triage this failure.
-LayoutTests/fast/text-autosizing/text-removal_t01: RuntimeError # co19-roll r786: Please triage this failure.
-LayoutTests/fast/transforms/scrollIntoView-transformed_t01: RuntimeError # co19-roll r786: Please triage this failure.
+LayoutTests/fast/canvas/canvas-transforms-fillRect-shadow_t01: RuntimeError, Pass # Please triage this failure.
+LayoutTests/fast/canvas/webgl/canvas-test_t01: RuntimeError, Pass # Please triage this failure.
+LayoutTests/fast/canvas/webgl/webgl-large-texture_t01: Skip # Times out flakily. Please triage this failure.
+LayoutTests/fast/css-generated-content/bug-106384_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/css-generated-content/empty-first-letter-with-columns-crash_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/css-generated-content/hit-test-generated-content_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/css-intrinsic-dimensions/css-tables_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/css-intrinsic-dimensions/tables_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/css/getComputedStyle/computed-style-select-overflow_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/css/vertical-align-length-copy-bug_t01: RuntimeError # Please triage this failure.
LayoutTests/fast/dom/HTMLElement/innerHTML-selection-crash_t01: Skip # Times out. Please triage this failure.
-LayoutTests/fast/dom/partial-layout-overlay-scrollbars_t01: Pass, RuntimeError # Please triage this failure.
-LayoutTests/fast/dom/partial-layout-non-overlay-scrollbars_t01: Pass, RuntimeError # Please triage this failure.
-LayoutTests/fast/dom/shadow/shadowdom-for-input-type-change_t01: RuntimeError # Please triage this failure.
-LayoutTests/fast/dom/jsDevicePixelRatio_t01: RuntimeError # Please triage this failure.
LayoutTests/fast/dom/HTMLLinkElement/prefetch-beforeload_t01: Pass, RuntimeError # Please triage this failure.
-LayoutTests/fast/forms/activate-and-disabled-elements_t01: Skip # Times out. co19-roll r801: Please triage this failure.
+LayoutTests/fast/dom/jsDevicePixelRatio_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/dom/partial-layout-non-overlay-scrollbars_t01: Pass, RuntimeError # Please triage this failure.
+LayoutTests/fast/dom/partial-layout-overlay-scrollbars_t01: Pass, RuntimeError # Please triage this failure.
+LayoutTests/fast/dom/shadow/shadowdom-for-input-type-change_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/filesystem/file-writer-abort-continue_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/forms/activate-and-disabled-elements_t01: Skip # Times out. Please triage this failure.
LayoutTests/fast/forms/text-set-value-crash_t01: Skip # Times out. Please triage this failure.
-LayoutTests/fast/inline/continuation-inlines-inserted-in-reverse-after-block_t01: Skip # Times out. co19-roll r801: Please triage this failure.
-LayoutTests/fast/inline/fixed-pos-moves-with-abspos-inline-parent_t01: Skip # Times out. co19-roll r801: Please triage this failure.
-LayoutTests/fast/inline/fixed-pos-moves-with-abspos-parent_t01: Skip # Times out. co19-roll r801: Please triage this failure.
-LayoutTests/fast/inline/fixed-pos-moves-with-abspos-parent-relative-ancestor_t01: Skip # Times out. co19-roll r801: Please triage this failure.
-LayoutTests/fast/inline/inline-relative-offset-boundingbox_t01: Skip # Times out. co19-roll r801: Please triage this failure.
-LayoutTests/fast/inline/out-of-flow-objects-and-whitespace-after-empty-inline_t01: Skip # Times out. co19-roll r801: Please triage this failure.
-LayoutTests/fast/inline/parent-inline-element-padding-contributes-width_t01: Skip # Times out. co19-roll r801: Please triage this failure.
-LayoutTests/fast/layers/negative-scroll-positions_t01: Skip # Times out. co19-roll r801: Please triage this failure.
-LayoutTests/fast/loader/loadInProgress_t01: Pass, RuntimeError # co19-roll r801: Please triage this failure.
+LayoutTests/fast/inline/continuation-inlines-inserted-in-reverse-after-block_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/inline/fixed-pos-moves-with-abspos-inline-parent_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/inline/fixed-pos-moves-with-abspos-parent-relative-ancestor_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/inline/fixed-pos-moves-with-abspos-parent_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/inline/inline-relative-offset-boundingbox_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/inline/out-of-flow-objects-and-whitespace-after-empty-inline_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/inline/parent-inline-element-padding-contributes-width_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/layers/negative-scroll-positions_t01: Skip # Times out. Please triage this failure.
+LayoutTests/fast/loader/loadInProgress_t01: Skip # Times out. Please triage this failure.
LayoutTests/fast/table/table-rowspan-height-distribution-in-rows_t02: Skip # Times out. Please triage this failure.
+LayoutTests/fast/text-autosizing/text-removal_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/text/international/listbox-width-rtl_t01: RuntimeError # Please triage this failure.
+LayoutTests/fast/transforms/scrollIntoView-transformed_t01: RuntimeError # Please triage this failure.
+LibTest/collection/ListBase/ListBase_class_A01_t02: Skip # Times out flakily. Issue 20956
LibTest/core/DateTime/parse_A01_t02: Skip # Times out. Please triage this failure.
+LibTest/core/List/List_class_A01_t02: Skip # Times out flakily. Issue 20956
+LibTest/html/Element/getBoundingClientRect_A01_t02: RuntimeError # Issue 19127.
+LibTest/html/Window/animationFrame_A01_t01: Skip # Times out. Please triage this failure.
+LibTest/math/log_A01_t01: Pass, Fail # co19 issue 44.
[ $compiler == none && $runtime == dartium ]
LayoutTests/fast/canvas/webgl/webgl-depth-texture_t01: RuntimeError # co19-roll r761: Please triage this failure.
diff --git a/tests/compiler/dart2js/analyze_unused_dart2js_test.dart b/tests/compiler/dart2js/analyze_unused_dart2js_test.dart
index 570b528..f12b8f1 100644
--- a/tests/compiler/dart2js/analyze_unused_dart2js_test.dart
+++ b/tests/compiler/dart2js/analyze_unused_dart2js_test.dart
@@ -23,10 +23,6 @@
// Some things in dart_printer are not yet used
"lib/src/dart_backend/backend_ast_nodes.dart": const [" is never "],
-
- // MethodElement
- // TODO(20377): Why is MethodElement unused?
- "lib/src/elements/elements.dart": const [" is never "]
};
void main() {
diff --git a/tests/compiler/dart2js/async_await_js_transform_test.dart b/tests/compiler/dart2js/async_await_js_transform_test.dart
index 98bcbe3..ce0cac1 100644
--- a/tests/compiler/dart2js/async_await_js_transform_test.dart
+++ b/tests/compiler/dart2js/async_await_js_transform_test.dart
@@ -36,169 +36,157 @@
function(a) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, __self = this;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- print(__self.x);
- __goto = 2;
- return thenHelper(foo(), __body, __completer);
- case 2:
- // returning from await.
- // implicit return
- return thenHelper(null, 0, __completer, null);
- case 1:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ switch (__goto) {
+ case 0:
+ // Function start
+ print(__self.x);
+ __goto = 2;
+ return thenHelper(foo(), __body, __completer);
+ case 2:
+ // returning from await.
+ // implicit return
+ return thenHelper(null, 0, __completer, null);
+ case 1:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
testTransform("""
-function(b) async {
- try {
- __outer: while (true) { // Overlapping label name.
- try {
- inner: while (true) {
- break __outer; // Break from untranslated loop to translated target.
- break; // break to untranslated target.
+ function(b) async {
+ try {
+ __outer: while (true) { // Overlapping label name.
+ try {
+ inner: while (true) {
+ break __outer; // Break from untranslated loop to translated target.
+ break; // break to untranslated target.
+ }
+ while (true) {
+ return; // Return via finallies.
+ }
+ var __helper = await foo(); // Overlapping variable name.
+ } finally {
+ foo();
+ continue; // Continue from finally with pending finally.
+ return 2; // Return from finally with pending finally.
}
- while (true) {
- return; // Return via finallies.
- }
- var __helper = await foo(); // Overlapping variable name.
- } finally {
- foo();
- continue; // Continue from finally with pending finally.
- return 2; // Return from finally with pending finally.
}
+ } finally {
+ return 3; // Return from finally with no pending finally.
}
- } finally {
- return 3; // Return from finally with no pending finally.
- }
- return 4;
-}""", """
+ return 4;
+ }""", """
function(b) {
var __goto = 0, __completer = new Completer(), __handler = 2, __currentError, __next, __returnValue, __helper;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- __outer1:
- switch (__goto) {
- case 0:
- // Function start
- __handler = 3;
- case 7:
- // continue __outer
- case 8:
- // while condition
- __handler = 10;
- inner: {
- while (true) {
- __next = [6];
- // goto finally
- __goto = 11;
- break __outer1;
- break;
- }
- }
+ __outer1:
+ switch (__goto) {
+ case 0:
+ // Function start
+ __handler = 3;
+ case 7:
+ // continue __outer
+ case 8:
+ // while condition
+ __handler = 10;
+ inner: {
while (true) {
- __next = [1, 4];
+ __next = [6];
// goto finally
__goto = 11;
break __outer1;
+ break;
}
- __goto = 13;
- return thenHelper(foo(), __body, __completer);
- case 13:
- // returning from await.
- __helper = __result;
- __next = [12];
+ }
+ while (true) {
+ __next = [1, 4];
// goto finally
__goto = 11;
- break;
- case 10:
- // uncaught
- __next = [3];
- case 11:
- // finally
- __handler = 3;
- foo();
- // goto while condition
- __goto = 8;
- break;
- __returnValue = 2;
- __next = [1];
- // goto finally
- __goto = 4;
- break;
- // goto the next finally handler
- __goto = __next.pop();
- break;
- case 12:
- // after finally
- // goto while condition
- __goto = 8;
- break;
- case 9:
- // after while
- case 6:
- // break __outer
- __next = [5];
- // goto finally
- __goto = 4;
- break;
- case 3:
- // uncaught
- __next = [2];
- case 4:
- // finally
- __handler = 2;
- __returnValue = 3;
- // goto return
- __goto = 1;
- break;
- // goto the next finally handler
- __goto = __next.pop();
- break;
- case 5:
- // after finally
- __returnValue = 4;
- // goto return
- __goto = 1;
- break;
- case 1:
- // return
- return thenHelper(__returnValue, 0, __completer, null);
- case 2:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
- }
-
+ break __outer1;
+ }
+ __goto = 13;
+ return thenHelper(foo(), __body, __completer);
+ case 13:
+ // returning from await.
+ __helper = __result;
+ __next = [12];
+ // goto finally
+ __goto = 11;
+ break;
+ case 10:
+ // uncaught
+ __next = [3];
+ case 11:
+ // finally
+ __handler = 3;
+ foo();
+ // goto while condition
+ __goto = 8;
+ break;
+ __returnValue = 2;
+ __next = [1];
+ // goto finally
+ __goto = 4;
+ break;
+ // goto the next finally handler
+ __goto = __next.pop();
+ break;
+ case 12:
+ // after finally
+ // goto while condition
+ __goto = 8;
+ break;
+ case 9:
+ // after while
+ case 6:
+ // break __outer
+ __next = [5];
+ // goto finally
+ __goto = 4;
+ break;
+ case 3:
+ // uncaught
+ __next = [2];
+ case 4:
+ // finally
+ __handler = 2;
+ __returnValue = 3;
+ // goto return
+ __goto = 1;
+ break;
+ // goto the next finally handler
+ __goto = __next.pop();
+ break;
+ case 5:
+ // after finally
+ __returnValue = 4;
+ // goto return
+ __goto = 1;
+ break;
+ case 1:
+ // return
+ return thenHelper(__returnValue, 0, __completer, null);
+ case 2:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
+ }
}
return thenHelper(null, __body, __completer, null);
}""");
- testTransform("""
+ testTransform("""
function(c) async {
var a, b, c, d, e, f;
a = b++; // post- and preincrements.
@@ -211,194 +199,182 @@
function(c) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, a, b, c, d, e, f, __temp1;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- a = b++;
- b = --b;
- __goto = 2;
- return thenHelper(foo(), __body, __completer);
- case 2:
- // returning from await.
- c = __result.a++;
- __goto = 3;
- return thenHelper(foo(), __body, __completer);
- case 3:
- // returning from await.
- d = ++__result.a;
- __temp1 = foo1();
- __goto = 4;
- return thenHelper(foo2(), __body, __completer);
- case 4:
- // returning from await.
- e = __temp1[__result]--;
- __temp1 = foo1();
- __goto = 5;
- return thenHelper(foo2(), __body, __completer);
- case 5:
- // returning from await.
- f = --__temp1[__result];
- // implicit return
- return thenHelper(null, 0, __completer, null);
- case 1:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ switch (__goto) {
+ case 0:
+ // Function start
+ a = b++;
+ b = --b;
+ __goto = 2;
+ return thenHelper(foo(), __body, __completer);
+ case 2:
+ // returning from await.
+ c = __result.a++;
+ __goto = 3;
+ return thenHelper(foo(), __body, __completer);
+ case 3:
+ // returning from await.
+ d = ++__result.a;
+ __temp1 = foo1();
+ __goto = 4;
+ return thenHelper(foo2(), __body, __completer);
+ case 4:
+ // returning from await.
+ e = __temp1[__result]--;
+ __temp1 = foo1();
+ __goto = 5;
+ return thenHelper(foo2(), __body, __completer);
+ case 5:
+ // returning from await.
+ f = --__temp1[__result];
+ // implicit return
+ return thenHelper(null, 0, __completer, null);
+ case 1:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
testTransform("""
-function(d2) async {
- var a, b, c, d, e, f, g, h; // empty initializer
- a = foo1() || await foo2(); // short circuiting operators
- b = await foo1() || foo2();
- c = await foo1() || foo3(await foo2());
- d = foo1() || foo2();
- e = foo1() && await foo2();
- f = await foo1() && foo2();
- g = await foo1() && await foo2();
- h = foo1() && foo2();
-}""", """
+ function(d2) async {
+ var a, b, c, d, e, f, g, h; // empty initializer
+ a = foo1() || await foo2(); // short circuiting operators
+ b = await foo1() || foo2();
+ c = await foo1() || foo3(await foo2());
+ d = foo1() || foo2();
+ e = foo1() && await foo2();
+ f = await foo1() && foo2();
+ g = await foo1() && await foo2();
+ h = foo1() && foo2();
+ }""", """
function(d2) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, a, b, c, d, e, f, g, h, __temp1;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- __temp1 = foo1();
- if (__temp1) {
- // goto then
- __goto = 2;
- break;
- } else
- __result = __temp1;
- // goto join
- __goto = 3;
+ switch (__goto) {
+ case 0:
+ // Function start
+ __temp1 = foo1();
+ if (__temp1) {
+ // goto then
+ __goto = 2;
break;
- case 2:
- // then
- __goto = 4;
- return thenHelper(foo2(), __body, __completer);
- case 4:
- // returning from await.
- case 3:
- // join
- a = __result;
- __goto = 5;
- return thenHelper(foo1(), __body, __completer);
- case 5:
- // returning from await.
- b = __result || foo2();
- __goto = 8;
- return thenHelper(foo1(), __body, __completer);
- case 8:
- // returning from await.
- __temp1 = __result;
- if (__temp1) {
- // goto then
- __goto = 6;
- break;
- } else
- __result = __temp1;
- // goto join
- __goto = 7;
+ } else
+ __result = __temp1;
+ // goto join
+ __goto = 3;
+ break;
+ case 2:
+ // then
+ __goto = 4;
+ return thenHelper(foo2(), __body, __completer);
+ case 4:
+ // returning from await.
+ case 3:
+ // join
+ a = __result;
+ __goto = 5;
+ return thenHelper(foo1(), __body, __completer);
+ case 5:
+ // returning from await.
+ b = __result || foo2();
+ __goto = 8;
+ return thenHelper(foo1(), __body, __completer);
+ case 8:
+ // returning from await.
+ __temp1 = __result;
+ if (__temp1) {
+ // goto then
+ __goto = 6;
break;
- case 6:
- // then
- __temp1 = foo3;
- __goto = 9;
- return thenHelper(foo2(), __body, __completer);
- case 9:
- // returning from await.
- __result = __temp1(__result);
- case 7:
- // join
- c = __result;
- d = foo1() || foo2();
- __temp1 = foo1();
- if (__temp1)
- __result = __temp1;
- else {
- // goto then
- __goto = 10;
- break;
- }
- // goto join
- __goto = 11;
+ } else
+ __result = __temp1;
+ // goto join
+ __goto = 7;
+ break;
+ case 6:
+ // then
+ __temp1 = foo3;
+ __goto = 9;
+ return thenHelper(foo2(), __body, __completer);
+ case 9:
+ // returning from await.
+ __result = __temp1(__result);
+ case 7:
+ // join
+ c = __result;
+ d = foo1() || foo2();
+ __temp1 = foo1();
+ if (__temp1) {
+ __result = __temp1;
+ } else {
+ // goto then
+ __goto = 10;
break;
- case 10:
- // then
- __goto = 12;
- return thenHelper(foo2(), __body, __completer);
- case 12:
- // returning from await.
- case 11:
- // join
- e = __result;
- __goto = 13;
- return thenHelper(foo1(), __body, __completer);
- case 13:
- // returning from await.
- f = __result && foo2();
- __goto = 16;
- return thenHelper(foo1(), __body, __completer);
- case 16:
- // returning from await.
- __temp1 = __result;
- if (__temp1)
- __result = __temp1;
- else {
- // goto then
- __goto = 14;
- break;
- }
- // goto join
- __goto = 15;
+ }
+ // goto join
+ __goto = 11;
+ break;
+ case 10:
+ // then
+ __goto = 12;
+ return thenHelper(foo2(), __body, __completer);
+ case 12:
+ // returning from await.
+ case 11:
+ // join
+ e = __result;
+ __goto = 13;
+ return thenHelper(foo1(), __body, __completer);
+ case 13:
+ // returning from await.
+ f = __result && foo2();
+ __goto = 16;
+ return thenHelper(foo1(), __body, __completer);
+ case 16:
+ // returning from await.
+ __temp1 = __result;
+ if (__temp1) {
+ __result = __temp1;
+ } else {
+ // goto then
+ __goto = 14;
break;
- case 14:
- // then
- __goto = 17;
- return thenHelper(foo2(), __body, __completer);
- case 17:
- // returning from await.
- case 15:
- // join
- g = __result;
- h = foo1() && foo2();
- // implicit return
- return thenHelper(null, 0, __completer, null);
- case 1:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ }
+ // goto join
+ __goto = 15;
+ break;
+ case 14:
+ // then
+ __goto = 17;
+ return thenHelper(foo2(), __body, __completer);
+ case 17:
+ // returning from await.
+ case 15:
+ // join
+ g = __result;
+ h = foo1() && foo2();
+ // implicit return
+ return thenHelper(null, 0, __completer, null);
+ case 1:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
- testTransform("""
+ testTransform("""
function(x, y) async {
while (true) {
switch(y) { // Switch with no awaits in case key expressions
@@ -417,153 +393,141 @@
function(x, y) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- case 2:
- // while condition
- case 4:
- // switch
- switch (y) {
- case 0:
- // goto case
- __goto = 6;
- break;
- case 1:
- // goto case
- __goto = 7;
- break;
- case 1:
- // goto case
- __goto = 8;
- break;
- case 2:
- // goto case
- __goto = 9;
- break;
- }
- // goto after switch
- __goto = 5;
- break;
- case 6:
- // case
- case 7:
- // case
- __goto = 10;
- return thenHelper(foo(), __body, __completer);
- case 10:
- // returning from await.
- // goto while condition
- __goto = 2;
- break;
- case 8:
- // case
- __goto = 11;
- return thenHelper(foo(), __body, __completer);
- case 11:
- // returning from await.
- // goto after switch
- __goto = 5;
- break;
- case 9:
- // case
- foo();
- case 5:
- // after switch
- // goto while condition
- __goto = 2;
- break;
- case 3:
- // after while
- // implicit return
- return thenHelper(null, 0, __completer, null);
- case 1:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ switch (__goto) {
+ case 0:
+ // Function start
+ case 2:
+ // while condition
+ case 4:
+ // switch
+ switch (y) {
+ case 0:
+ // goto case
+ __goto = 6;
+ break;
+ case 1:
+ // goto case
+ __goto = 7;
+ break;
+ case 1:
+ // goto case
+ __goto = 8;
+ break;
+ case 2:
+ // goto case
+ __goto = 9;
+ break;
+ }
+ // goto after switch
+ __goto = 5;
+ break;
+ case 6:
+ // case
+ case 7:
+ // case
+ __goto = 10;
+ return thenHelper(foo(), __body, __completer);
+ case 10:
+ // returning from await.
+ // goto while condition
+ __goto = 2;
+ break;
+ case 8:
+ // case
+ __goto = 11;
+ return thenHelper(foo(), __body, __completer);
+ case 11:
+ // returning from await.
+ // goto after switch
+ __goto = 5;
+ break;
+ case 9:
+ // case
+ foo();
+ case 5:
+ // after switch
+ // goto while condition
+ __goto = 2;
+ break;
+ case 3:
+ // after while
+ // implicit return
+ return thenHelper(null, 0, __completer, null);
+ case 1:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
testTransform("""
-function(f) async {
- do {
- var a = await foo();
- if (a) // If with no awaits in body
- break;
- else
- continue;
- } while (await foo());
-}
-""", """
+ function(f) async {
+ do {
+ var a = await foo();
+ if (a) // If with no awaits in body
+ break;
+ else
+ continue;
+ } while (await foo());
+ }
+ """, """
function(f) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, a;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- case 2:
- // do body
- __goto = 5;
- return thenHelper(foo(), __body, __completer);
- case 5:
- // returning from await.
- a = __result;
- if (a) {
- // goto after do
- __goto = 4;
- break;
- } else {
- // goto do condition
- __goto = 3;
- break;
- }
- case 3:
- // do condition
- __goto = 6;
- return thenHelper(foo(), __body, __completer);
- case 6:
- // returning from await.
- if (__result) {
- // goto do body
- __goto = 2;
- break;
- }
- case 4:
- // after do
- // implicit return
- return thenHelper(null, 0, __completer, null);
- case 1:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ switch (__goto) {
+ case 0:
+ // Function start
+ case 2:
+ // do body
+ __goto = 5;
+ return thenHelper(foo(), __body, __completer);
+ case 5:
+ // returning from await.
+ a = __result;
+ if (a) {
+ // goto after do
+ __goto = 4;
+ break;
+ } else {
+ // goto do condition
+ __goto = 3;
+ break;
+ }
+ case 3:
+ // do condition
+ __goto = 6;
+ return thenHelper(foo(), __body, __completer);
+ case 6:
+ // returning from await.
+ if (__result) {
+ // goto do body
+ __goto = 2;
+ break;
+ }
+ case 4:
+ // after do
+ // implicit return
+ return thenHelper(null, 0, __completer, null);
+ case 1:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
- testTransform("""
+ testTransform("""
function(g) async {
for (var i = 0; i < await foo1(); i += await foo2()) {
if (foo(i))
@@ -581,166 +545,154 @@
function(g) {
var __goto = 0, __completer = new Completer(), __handler = 2, __currentError, __returnValue, i, __temp1;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- i = 0;
- case 3:
- // for condition
- __temp1 = i;
- __goto = 6;
- return thenHelper(foo1(), __body, __completer);
- case 6:
- // returning from await.
- if (!(__temp1 < __result)) {
- // goto after for
- __goto = 5;
- break;
- }
- if (foo(i)) {
- // goto for update
- __goto = 4;
- break;
- } else {
- // goto after for
- __goto = 5;
- break;
- }
- __goto = !foo(i) ? 7 : 8;
+ switch (__goto) {
+ case 0:
+ // Function start
+ i = 0;
+ case 3:
+ // for condition
+ __temp1 = i;
+ __goto = 6;
+ return thenHelper(foo1(), __body, __completer);
+ case 6:
+ // returning from await.
+ if (!(__temp1 < __result)) {
+ // goto after for
+ __goto = 5;
break;
- case 7:
- // then
- __goto = 9;
- return thenHelper(foo(), __body, __completer);
- case 9:
- // returning from await.
- // goto return
- __goto = 1;
+ }
+ if (foo(i)) {
+ // goto for update
+ __goto = 4;
break;
- case 8:
- // join
- __temp1 = print;
- __goto = 10;
- return thenHelper(foo(i), __body, __completer);
- case 10:
- // returning from await.
- __temp1(__result);
- case 4:
- // for update
- __goto = 11;
- return thenHelper(foo2(), __body, __completer);
- case 11:
- // returning from await.
- i = __result;
- // goto for condition
- __goto = 3;
+ } else {
+ // goto after for
+ __goto = 5;
break;
- case 5:
- // after for
- case 1:
- // return
- return thenHelper(__returnValue, 0, __completer, null);
- case 2:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ }
+ __goto = !foo(i) ? 7 : 8;
+ break;
+ case 7:
+ // then
+ __goto = 9;
+ return thenHelper(foo(), __body, __completer);
+ case 9:
+ // returning from await.
+ // goto return
+ __goto = 1;
+ break;
+ case 8:
+ // join
+ __temp1 = print;
+ __goto = 10;
+ return thenHelper(foo(i), __body, __completer);
+ case 10:
+ // returning from await.
+ __temp1(__result);
+ case 4:
+ // for update
+ __goto = 11;
+ return thenHelper(foo2(), __body, __completer);
+ case 11:
+ // returning from await.
+ i = __result;
+ // goto for condition
+ __goto = 3;
+ break;
+ case 5:
+ // after for
+ case 1:
+ // return
+ return thenHelper(__returnValue, 0, __completer, null);
+ case 2:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
testTransform("""
-function(a, h) async {
- var x = {"a": foo1(), "b": await foo2(), "c": foo3()};
- x["a"] = 2; // Different assignments
- (await foo()).a = 3;
- x[await foo()] = 4;
- x[(await foo1()).a = await foo2()] = 5;
- (await foo1())[await foo2()] = await foo3(6);
-}
-""", """
+ function(a, h) async {
+ var x = {"a": foo1(), "b": await foo2(), "c": foo3()};
+ x["a"] = 2; // Different assignments
+ (await foo()).a = 3;
+ x[await foo()] = 4;
+ x[(await foo1()).a = await foo2()] = 5;
+ (await foo1())[await foo2()] = await foo3(6);
+ }
+ """, """
function(a, h) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, x, __temp1, __temp2;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- __temp1 = foo1();
- __goto = 2;
- return thenHelper(foo2(), __body, __completer);
- case 2:
- // returning from await.
- x = {a: __temp1, b: __result, c: foo3()};
- x.a = 2;
- __goto = 3;
- return thenHelper(foo(), __body, __completer);
- case 3:
- // returning from await.
- __result.a = 3;
- __temp1 = x;
- __goto = 4;
- return thenHelper(foo(), __body, __completer);
- case 4:
- // returning from await.
- __temp1[__result] = 4;
- __temp1 = x;
- __goto = 5;
- return thenHelper(foo1(), __body, __completer);
- case 5:
- // returning from await.
- __temp2 = __result;
- __goto = 6;
- return thenHelper(foo2(), __body, __completer);
- case 6:
- // returning from await.
- __temp1[__temp2.a = __result] = 5;
- __goto = 7;
- return thenHelper(foo1(), __body, __completer);
- case 7:
- // returning from await.
- __temp1 = __result;
- __goto = 8;
- return thenHelper(foo2(), __body, __completer);
- case 8:
- // returning from await.
- __temp2 = __result;
- __goto = 9;
- return thenHelper(foo3(6), __body, __completer);
- case 9:
- // returning from await.
- __temp1[__temp2] = __result;
- // implicit return
- return thenHelper(null, 0, __completer, null);
- case 1:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ switch (__goto) {
+ case 0:
+ // Function start
+ __temp1 = foo1();
+ __goto = 2;
+ return thenHelper(foo2(), __body, __completer);
+ case 2:
+ // returning from await.
+ x = {a: __temp1, b: __result, c: foo3()};
+ x.a = 2;
+ __goto = 3;
+ return thenHelper(foo(), __body, __completer);
+ case 3:
+ // returning from await.
+ __result.a = 3;
+ __temp1 = x;
+ __goto = 4;
+ return thenHelper(foo(), __body, __completer);
+ case 4:
+ // returning from await.
+ __temp1[__result] = 4;
+ __temp1 = x;
+ __goto = 5;
+ return thenHelper(foo1(), __body, __completer);
+ case 5:
+ // returning from await.
+ __temp2 = __result;
+ __goto = 6;
+ return thenHelper(foo2(), __body, __completer);
+ case 6:
+ // returning from await.
+ __temp1[__temp2.a = __result] = 5;
+ __goto = 7;
+ return thenHelper(foo1(), __body, __completer);
+ case 7:
+ // returning from await.
+ __temp1 = __result;
+ __goto = 8;
+ return thenHelper(foo2(), __body, __completer);
+ case 8:
+ // returning from await.
+ __temp2 = __result;
+ __goto = 9;
+ return thenHelper(foo3(6), __body, __completer);
+ case 9:
+ // returning from await.
+ __temp1[__temp2] = __result;
+ // implicit return
+ return thenHelper(null, 0, __completer, null);
+ case 1:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
- testTransform("""
+ testTransform("""
function(c, i) async {
try {
var x = c ? await foo() : foo(); // conditional
@@ -757,185 +709,173 @@
}
""", """
function(c, i) {
- var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, x, y, __error1, __error2;
+ var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, __next, x, y, __error1, __error2;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- __handler = 3;
- __goto = c ? 6 : 8;
- break;
- case 6:
- // then
- __goto = 9;
- return thenHelper(foo(), __body, __completer);
- case 9:
- // returning from await.
- // goto join
- __goto = 7;
- break;
- case 8:
- // else
- __result = foo();
- case 7:
- // join
- x = __result;
- y = {};
- __handler = 1;
- // goto after finally
- __goto = 5;
- break;
- case 3:
- // catch
- __handler = 2;
- __error1 = __currentError;
- __handler = 11;
- __goto = c ? 14 : 16;
- break;
- case 14:
- // then
- __goto = 17;
- return thenHelper(fooError(__error1), __body, __completer);
- case 17:
- // returning from await.
- // goto join
- __goto = 15;
- break;
- case 16:
- // else
- __result = fooError(__error1);
- case 15:
- // join
- x = __result;
- __next = [13];
- // goto finally
- __goto = 12;
- break;
- case 11:
- // catch
- __handler = 10;
- __error2 = __currentError;
- y.x = foo(__error2);
- __next = [13];
- // goto finally
- __goto = 12;
- break;
- case 10:
- // uncaught
- __next = [2];
- case 12:
- // finally
- __handler = 2;
- foo(x);
- // goto the next finally handler
- __goto = __next.pop();
- break;
- case 13:
- // after finally
- // goto after finally
- __goto = 5;
- break;
- case 2:
- // uncaught
- // goto rethrow
- __goto = 1;
- break;
- case 5:
- // after finally
- // implicit return
- return thenHelper(null, 0, __completer, null);
- case 1:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ switch (__goto) {
+ case 0:
+ // Function start
+ __handler = 3;
+ __goto = c ? 6 : 8;
+ break;
+ case 6:
+ // then
+ __goto = 9;
+ return thenHelper(foo(), __body, __completer);
+ case 9:
+ // returning from await.
+ // goto join
+ __goto = 7;
+ break;
+ case 8:
+ // else
+ __result = foo();
+ case 7:
+ // join
+ x = __result;
+ y = {};
+ __handler = 1;
+ // goto after finally
+ __goto = 5;
+ break;
+ case 3:
+ // catch
+ __handler = 2;
+ __error1 = __currentError;
+ __handler = 11;
+ __goto = c ? 14 : 16;
+ break;
+ case 14:
+ // then
+ __goto = 17;
+ return thenHelper(fooError(__error1), __body, __completer);
+ case 17:
+ // returning from await.
+ // goto join
+ __goto = 15;
+ break;
+ case 16:
+ // else
+ __result = fooError(__error1);
+ case 15:
+ // join
+ x = __result;
+ __next = [13];
+ // goto finally
+ __goto = 12;
+ break;
+ case 11:
+ // catch
+ __handler = 10;
+ __error2 = __currentError;
+ y.x = foo(__error2);
+ __next = [13];
+ // goto finally
+ __goto = 12;
+ break;
+ case 10:
+ // uncaught
+ __next = [2];
+ case 12:
+ // finally
+ __handler = 2;
+ foo(x);
+ // goto the next finally handler
+ __goto = __next.pop();
+ break;
+ case 13:
+ // after finally
+ // goto after finally
+ __goto = 5;
+ break;
+ case 2:
+ // uncaught
+ // goto rethrow
+ __goto = 1;
+ break;
+ case 5:
+ // after finally
+ // implicit return
+ return thenHelper(null, 0, __completer, null);
+ case 1:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
testTransform("""
-function(x, y, j) async {
- print(await(foo(x))); // calls
- (await print)(foo(x));
- print(foo(await x));
- await (print(foo(await x)));
- print(foo(x, await y, z));
-}
-""", """
+ function(x, y, j) async {
+ print(await(foo(x))); // calls
+ (await print)(foo(x));
+ print(foo(await x));
+ await (print(foo(await x)));
+ print(foo(x, await y, z));
+ }
+ """, """
function(x, y, j) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, __temp1, __temp2, __temp3;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- __temp1 = print;
- __goto = 2;
- return thenHelper(foo(x), __body, __completer);
- case 2:
- // returning from await.
- __temp1(__result);
- __goto = 3;
- return thenHelper(print, __body, __completer);
- case 3:
- // returning from await.
- __result(foo(x));
- __temp1 = print;
- __temp2 = foo;
- __goto = 4;
- return thenHelper(x, __body, __completer);
- case 4:
- // returning from await.
- __temp1(__temp2(__result));
- __temp1 = print;
- __temp2 = foo;
- __goto = 6;
- return thenHelper(x, __body, __completer);
- case 6:
- // returning from await.
- __goto = 5;
- return thenHelper(__temp1(__temp2(__result)), __body, __completer);
- case 5:
- // returning from await.
- __temp1 = print;
- __temp2 = foo;
- __temp3 = x;
- __goto = 7;
- return thenHelper(y, __body, __completer);
- case 7:
- // returning from await.
- __temp1(__temp2(__temp3, __result, z));
- // implicit return
- return thenHelper(null, 0, __completer, null);
- case 1:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ switch (__goto) {
+ case 0:
+ // Function start
+ __temp1 = print;
+ __goto = 2;
+ return thenHelper(foo(x), __body, __completer);
+ case 2:
+ // returning from await.
+ __temp1(__result);
+ __goto = 3;
+ return thenHelper(print, __body, __completer);
+ case 3:
+ // returning from await.
+ __result(foo(x));
+ __temp1 = print;
+ __temp2 = foo;
+ __goto = 4;
+ return thenHelper(x, __body, __completer);
+ case 4:
+ // returning from await.
+ __temp1(__temp2(__result));
+ __temp1 = print;
+ __temp2 = foo;
+ __goto = 6;
+ return thenHelper(x, __body, __completer);
+ case 6:
+ // returning from await.
+ __goto = 5;
+ return thenHelper(__temp1(__temp2(__result)), __body, __completer);
+ case 5:
+ // returning from await.
+ __temp1 = print;
+ __temp2 = foo;
+ __temp3 = x;
+ __goto = 7;
+ return thenHelper(y, __body, __completer);
+ case 7:
+ // returning from await.
+ __temp1(__temp2(__temp3, __result, z));
+ // implicit return
+ return thenHelper(null, 0, __completer, null);
+ case 1:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
- testTransform("""
+ testTransform("""
function(x, y, k) async {
while (await(foo())) {
lab: { // labelled statement
@@ -964,121 +904,115 @@
function(x, y, k) {
var __goto = 0, __completer = new Completer(), __handler = 2, __currentError, __returnValue, __temp1;
function __body(__errorCode, __result) {
- if (__errorCode == 1) {
+ if (__errorCode === 1) {
__currentError = __result;
__goto = __handler;
}
while (true)
- try {
- switch (__goto) {
- case 0:
- // Function start
- case 3:
- // while condition
- __goto = 5;
- return thenHelper(foo(), __body, __completer);
- case 5:
- // returning from await.
- if (!__result) {
- // goto after while
- __goto = 4;
- break;
- }
- case 7:
- // continue lab
- case 8:
- // switch
- __temp1 = y;
- if (__temp1 === 0) {
- // goto case
- __goto = 10;
- break;
- }
- if (__temp1 === 0) {
- // goto case
- __goto = 11;
- break;
- }
- __goto = 13;
- return thenHelper(bar(), __body, __completer);
- case 13:
- // returning from await.
- if (__temp1 === __result) {
- // goto case
- __goto = 12;
- break;
- }
- if (__temp1 === x) {
- // goto case
- __goto = 14;
- break;
- }
- // goto default
- __goto = 15;
+ switch (__goto) {
+ case 0:
+ // Function start
+ case 3:
+ // while condition
+ __goto = 5;
+ return thenHelper(foo(), __body, __completer);
+ case 5:
+ // returning from await.
+ if (!__result) {
+ // goto after while
+ __goto = 4;
break;
- case 10:
- // case
- foo();
- case 11:
- // case
- __temp1 = print;
- __goto = 16;
- return thenHelper(foo1(x), __body, __completer);
- case 16:
- // returning from await.
- __temp1(__result);
- __returnValue = y;
- // goto return
- __goto = 1;
+ }
+ case 7:
+ // continue lab
+ case 8:
+ // switch
+ __temp1 = y;
+ if (__temp1 === 0) {
+ // goto case
+ __goto = 10;
break;
- case 12:
- // case
- __temp1 = print;
- __goto = 17;
- return thenHelper(foobar(x), __body, __completer);
- case 17:
- // returning from await.
- __temp1(__result);
- __returnValue = y;
- // goto return
- __goto = 1;
+ }
+ if (__temp1 === 0) {
+ // goto case
+ __goto = 11;
break;
- case 14:
- // case
- if (a) {
- throw new Error();
- } else {
- // goto while condition
- __goto = 3;
- break;
- }
- case 15:
- // default
- // goto break lab
- __goto = 6;
+ }
+ __goto = 13;
+ return thenHelper(bar(), __body, __completer);
+ case 13:
+ // returning from await.
+ if (__temp1 === __result) {
+ // goto case
+ __goto = 12;
break;
- case 9:
- // after switch
- foo();
- case 6:
- // break lab
+ }
+ if (__temp1 === x) {
+ // goto case
+ __goto = 14;
+ break;
+ }
+ // goto default
+ __goto = 15;
+ break;
+ case 10:
+ // case
+ foo();
+ case 11:
+ // case
+ __temp1 = print;
+ __goto = 16;
+ return thenHelper(foo1(x), __body, __completer);
+ case 16:
+ // returning from await.
+ __temp1(__result);
+ __returnValue = y;
+ // goto return
+ __goto = 1;
+ break;
+ case 12:
+ // case
+ __temp1 = print;
+ __goto = 17;
+ return thenHelper(foobar(x), __body, __completer);
+ case 17:
+ // returning from await.
+ __temp1(__result);
+ __returnValue = y;
+ // goto return
+ __goto = 1;
+ break;
+ case 14:
+ // case
+ if (a) {
+ throw new Error();
+ } else {
// goto while condition
__goto = 3;
break;
- case 4:
- // after while
- case 1:
- // return
- return thenHelper(__returnValue, 0, __completer, null);
- case 2:
- // rethrow
- return thenHelper(__currentError, 1, __completer);
- }
- } catch (__error) {
- __currentError = __error;
- __goto = __handler;
+ }
+ case 15:
+ // default
+ // goto break lab
+ __goto = 6;
+ break;
+ case 9:
+ // after switch
+ foo();
+ case 6:
+ // break lab
+ // goto while condition
+ __goto = 3;
+ break;
+ case 4:
+ // after while
+ case 1:
+ // return
+ return thenHelper(__returnValue, 0, __completer, null);
+ case 2:
+ // rethrow
+ return thenHelper(__currentError, 1, __completer);
}
-
}
return thenHelper(null, __body, __completer, null);
}""");
diff --git a/tests/compiler/dart2js/backend_dart/dart_printer_test.dart b/tests/compiler/dart2js/backend_dart/dart_printer_test.dart
index 4c51201..407b149 100644
--- a/tests/compiler/dart2js/backend_dart/dart_printer_test.dart
+++ b/tests/compiler/dart2js/backend_dart/dart_printer_test.dart
@@ -658,7 +658,7 @@
}
Expression parseExpression(String code) {
- SourceFile file = new StringSourceFile('', code);
+ SourceFile file = new StringSourceFile.fromName('', code);
Scanner scan = new Scanner(file);
Token tok = scan.tokenize();
AstBuilder builder = new AstBuilder();
@@ -670,7 +670,7 @@
return builder.pop();
}
Statement parseStatement(String code) {
- SourceFile file = new StringSourceFile('', code);
+ SourceFile file = new StringSourceFile.fromName('', code);
Scanner scan = new Scanner(file);
Token tok = scan.tokenize();
AstBuilder builder = new AstBuilder();
@@ -730,7 +730,7 @@
}
void debugTokens(String code) {
- SourceFile file = new StringSourceFile('', code);
+ SourceFile file = new StringSourceFile.fromName('', code);
Scanner scan = new Scanner(file);
Token tok = scan.tokenize();
while (tok.next != tok) {
diff --git a/tests/compiler/dart2js/dart2js_batch2_run.dart b/tests/compiler/dart2js/dart2js_batch2_run.dart
new file mode 100644
index 0000000..aee55ef
--- /dev/null
+++ b/tests/compiler/dart2js/dart2js_batch2_run.dart
@@ -0,0 +1,10 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+@notExisting
+var x;
+
+main() {
+ print(x);
+}
diff --git a/tests/compiler/dart2js/dart2js_batch2_test.dart b/tests/compiler/dart2js/dart2js_batch2_test.dart
new file mode 100644
index 0000000..d2a1845
--- /dev/null
+++ b/tests/compiler/dart2js/dart2js_batch2_test.dart
@@ -0,0 +1,86 @@
+// 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 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:path/path.dart' as path;
+import 'package:async_helper/async_helper.dart';
+import 'package:expect/expect.dart';
+
+var tmpDir;
+
+copyDirectory(Directory sourceDir, Directory destinationDir) {
+ sourceDir.listSync().forEach((FileSystemEntity element) {
+ String newPath = path.join(destinationDir.path,
+ path.basename(element.path));
+ if (element is File) {
+ element.copySync(newPath);
+ } else if (element is Directory) {
+ Directory newDestinationDir = new Directory(newPath);
+ newDestinationDir.createSync();
+ copyDirectory(element, newDestinationDir);
+ }
+ });
+}
+
+Future<Directory> createTempDir() {
+ return Directory.systemTemp
+ .createTemp('dart2js_batch_test-')
+ .then((Directory dir) {
+ return dir;
+ });
+}
+
+Future setup() {
+ return createTempDir().then((Directory directory) {
+ tmpDir = directory;
+ String newPath = path.join(directory.path, "dart2js_batch2_run.dart");
+ File source =
+ new File(Platform.script.resolve("dart2js_batch2_run.dart").path);
+ source.copySync(newPath);
+ });
+}
+
+void cleanUp() {
+ print("Deleting '${tmpDir.path}'.");
+ tmpDir.deleteSync(recursive: true);
+}
+
+Future launchDart2Js(_) {
+ String ext = Platform.isWindows ? '.bat' : '';
+ String command =
+ path.normalize(path.join(path.fromUri(Platform.script),
+ '../../../../sdk/bin/dart2js${ext}'));
+ print("Running '$command --batch' from '${tmpDir}'.");
+ return Process.start(command, ['--batch'], workingDirectory: tmpDir.path);
+}
+
+Future runTests(Process process) {
+ String inFile = path.join(tmpDir.path, 'dart2js_batch2_run.dart');
+ String outFile = path.join(tmpDir.path, 'out.js');
+
+ process.stdin.writeln('--out="$outFile" "$inFile"');
+ process.stdin.close();
+ Future<String> output = process.stdout.transform(UTF8.decoder).join();
+ Future<String> errorOut = process.stderr.transform(UTF8.decoder).join();
+ return Future.wait([output, errorOut])
+ .then((result) {
+ String stdoutOutput = result[0];
+ String stderrOutput = result[1];
+
+ Expect.isFalse(stdoutOutput.contains("crashed"));
+ });
+}
+
+void main() {
+ var tmpDir;
+ asyncTest(() {
+ return setup()
+ .then(launchDart2Js)
+ .then(runTests)
+ .whenComplete(cleanUp);
+ });
+}
diff --git a/tests/compiler/dart2js/dart2js_batch_test.dart b/tests/compiler/dart2js/dart2js_batch_test.dart
index 8afe9e9..04b3ad6 100644
--- a/tests/compiler/dart2js/dart2js_batch_test.dart
+++ b/tests/compiler/dart2js/dart2js_batch_test.dart
@@ -74,9 +74,7 @@
return Future.wait([output, errorOut])
.then((result) {
String stdoutOutput = result[0];
- print('out:\n$stdoutOutput');
String stderrOutput = result[1];
- print('err:\n$stderrOutput');
Expect.equals(4, ">>> EOF STDERR".allMatches(stderrOutput).length);
Expect.equals(4, ">>>".allMatches(stderrOutput).length);
diff --git a/tests/compiler/dart2js/expect_annotations2_test.dart b/tests/compiler/dart2js/expect_annotations2_test.dart
new file mode 100644
index 0000000..4357c1d
--- /dev/null
+++ b/tests/compiler/dart2js/expect_annotations2_test.dart
@@ -0,0 +1,45 @@
+// 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.
+
+import "package:expect/expect.dart";
+import "package:async_helper/async_helper.dart";
+import 'memory_compiler.dart';
+
+const MEMORY_SOURCE_FILES = const {
+ 'main.dart': '''
+ import 'package:expect/expect.dart';
+
+ @NoInline()
+ foo(y) => 49912344 + y;
+
+ class A {
+ @NoInline()
+ static bar(x) => x + 123455;
+
+ @NoInline()
+ gee(x, y) => x + y + 81234512;
+ }
+
+ main() {
+ print(foo(23412));
+ print(A.bar(87654));
+ print(new A().gee(1337, 919182));
+ }'''};
+
+void main() {
+ OutputCollector collector = new OutputCollector();
+ var compiler = compilerFor(MEMORY_SOURCE_FILES, outputProvider: collector);
+ asyncTest(() => compiler.run(Uri.parse('memory:main.dart')).then((_) {
+ // Simply check that the constants of the small functions are still in the
+ // output, and that we don't see the result of constant folding.
+ String jsOutput = collector.getOutput('', 'js');
+
+ Expect.isTrue(jsOutput.contains('49912344'));
+ Expect.isTrue(jsOutput.contains('123455'));
+ Expect.isTrue(jsOutput.contains('81234512'));
+ Expect.isFalse(jsOutput.contains('49935756'));
+ Expect.isFalse(jsOutput.contains('211109'));
+ Expect.isFalse(jsOutput.contains('82155031'));
+ }));
+}
diff --git a/tests/compiler/dart2js/expect_annotations_test.dart b/tests/compiler/dart2js/expect_annotations_test.dart
index 3ee1fdc..6669d32 100644
--- a/tests/compiler/dart2js/expect_annotations_test.dart
+++ b/tests/compiler/dart2js/expect_annotations_test.dart
@@ -24,11 +24,11 @@
@TrustTypeAnnotations()
int methodTrustTypeAnnotations(String arg) => arg.length;
-@NoInlining()
-int methodNoInlining(String arg) => arg.length;
+@NoInline()
+int methodNoInline(String arg) => arg.length;
-@NoInlining() @TrustTypeAnnotations()
-int methodNoInliningTrustTypeAnnotations(String arg) => arg.length;
+@NoInline() @TrustTypeAnnotations()
+int methodNoInlineTrustTypeAnnotations(String arg) => arg.length;
@AssumeDynamic() @TrustTypeAnnotations()
int methodAssumeDynamicTrustTypeAnnotations(String arg) => arg.length;
@@ -39,9 +39,9 @@
print(methodAssumeDynamic('foo'));
print(methodTrustTypeAnnotations(42));
print(methodTrustTypeAnnotations("fourtyTwo"));
- print(methodNoInlining('bar'));
- print(methodNoInliningTrustTypeAnnotations(42));
- print(methodNoInliningTrustTypeAnnotations("fourtyTwo"));
+ print(methodNoInline('bar'));
+ print(methodNoInlineTrustTypeAnnotations(42));
+ print(methodNoInlineTrustTypeAnnotations("fourtyTwo"));
print(methodAssumeDynamicTrustTypeAnnotations(null));
}
"""
@@ -52,8 +52,8 @@
asyncTest(() => compiler.runCompiler(Uri.parse('memory:main.dart')).then((_) {
Expect.isFalse(compiler.compilationFailed, 'Unsuccessful compilation');
JavaScriptBackend backend = compiler.backend;
- Expect.isNotNull(backend.annotations.expectNoInliningClass,
- 'NoInliningClass is unresolved.');
+ Expect.isNotNull(backend.annotations.expectNoInlineClass,
+ 'NoInlineClass is unresolved.');
Expect.isNotNull(backend.annotations.expectTrustTypeAnnotationsClass,
'TrustTypeAnnotations is unresolved.');
Expect.isNotNull(backend.annotations.expectAssumeDynamicClass,
@@ -74,7 +74,7 @@
}
void test(String name,
- {bool expectNoInlining: false,
+ {bool expectNoInline: false,
bool expectTrustTypeAnnotations: false,
TypeMask expectedParameterType: null,
TypeMask expectedReturnType: null,
@@ -82,9 +82,9 @@
Element method = compiler.mainApp.find(name);
Expect.isNotNull(method);
Expect.equals(
- expectNoInlining,
- backend.annotations.noInlining(method),
- "Unexpected annotation of @NoInlining on '$method'.");
+ expectNoInline,
+ backend.annotations.noInline(method),
+ "Unexpected annotation of @NoInline on '$method'.");
Expect.equals(
expectTrustTypeAnnotations,
backend.annotations.trustTypeAnnotations(method),
@@ -112,9 +112,9 @@
test('methodTrustTypeAnnotations',
expectTrustTypeAnnotations: true,
expectedParameterType: jsStringType);
- test('methodNoInlining', expectNoInlining: true);
- test('methodNoInliningTrustTypeAnnotations',
- expectNoInlining: true,
+ test('methodNoInline', expectNoInline: true);
+ test('methodNoInlineTrustTypeAnnotations',
+ expectNoInline: true,
expectTrustTypeAnnotations: true,
expectedParameterType: jsStringType,
expectedReturnType: jsIntType);
diff --git a/tests/compiler/dart2js/js_backend_cps_ir_basic_test.dart b/tests/compiler/dart2js/js_backend_cps_ir_basic_test.dart
index 004d80f..60deac3 100644
--- a/tests/compiler/dart2js/js_backend_cps_ir_basic_test.dart
+++ b/tests/compiler/dart2js/js_backend_cps_ir_basic_test.dart
@@ -26,8 +26,7 @@
print('($m)');
}""",r"""
function() {
- var e, l, m;
- e = 1;
+ var l, m;
l = [1, 2, 3];
m = P.LinkedHashMap_LinkedHashMap$_literal(["s", 1]);
P.print("()");
@@ -35,7 +34,7 @@
P.print("(" + 1 + ")");
P.print("(" + H.S([1, 2, 3]) + ")");
P.print("(" + H.S(P.LinkedHashMap_LinkedHashMap$_literal(["s", 1])) + ")");
- P.print("(" + H.S(e) + ")");
+ P.print("(" + 1 + ")");
P.print("(" + H.S(l) + ")");
P.print("(" + H.S(m) + ")");
return null;
@@ -54,14 +53,11 @@
""",
"""
function() {
- var v0, v1;
V.foo(0, "b");
V.foo(1, 2);
V.bar(3, "b", "c");
V.bar(4, 5, "c");
- v0 = 6;
- v1 = 7;
- V.bar(v0, "b", v1);
+ V.bar(6, "b", 7);
V.bar(8, 9, 10);
return null;
}"""),
diff --git a/tests/compiler/dart2js/js_backend_cps_ir_closures_test.dart b/tests/compiler/dart2js/js_backend_cps_ir_closures_test.dart
index 100f26d..ddad2f6 100644
--- a/tests/compiler/dart2js/js_backend_cps_ir_closures_test.dart
+++ b/tests/compiler/dart2js/js_backend_cps_ir_closures_test.dart
@@ -21,13 +21,12 @@
""",
r"""
function(x) {
- var box_0, a, v0;
+ var box_0, a;
box_0 = {};
box_0.x_0 = x;
a = new V.main_a(box_0);
x = box_0.x_0;
- v0 = "1";
- box_0.x_0 = J.getInterceptor$ns(x).$add(x, v0);
+ box_0.x_0 = J.getInterceptor$ns(x).$add(x, "1");
P.print(a.call$0());
return null;
}"""),
@@ -56,13 +55,12 @@
""",
r"""
function() {
- var box_0, a, x, v0;
+ var box_0, a, x;
box_0 = {};
box_0.x_0 = 122;
a = new V.main_closure(box_0);
x = box_0.x_0;
- v0 = 1;
- box_0.x_0 = J.getInterceptor$ns(x).$add(x, v0);
+ box_0.x_0 = J.getInterceptor$ns(x).$add(x, 1);
P.print(a.call$0());
return null;
}"""),
@@ -80,13 +78,12 @@
""",
r"""
function() {
- var box_0, a, x, v0;
+ var box_0, a, x;
box_0 = {};
box_0.x_0 = 122;
a = new V.main_closure(box_0);
x = box_0.x_0;
- v0 = 1;
- box_0.x_0 = J.getInterceptor$ns(x).$add(x, v0);
+ box_0.x_0 = J.getInterceptor$ns(x).$add(x, 1);
P.print(a.call$0().call$0());
return null;
}"""),
@@ -102,20 +99,29 @@
""",
r"""
function() {
- var a, i, v0, v1;
+ var a, i;
a = null;
i = 0;
- while (true) {
- v0 = 10;
- if (P.identical(J.getInterceptor$n(i).$lt(i, v0), true)) {
- a = new V.main_closure(i);
- v1 = 1;
- i = J.getInterceptor$ns(i).$add(i, v1);
- } else {
- P.print(a.call$0());
- return null;
- }
+ while (P.identical(J.getInterceptor$n(i).$lt(i, 10), true)) {
+ a = new V.main_closure(i);
+ i = J.getInterceptor$ns(i).$add(i, 1);
}
+ P.print(a.call$0());
+ return null;
+}"""),
+
+ const TestEntry.forMethod('function(A#b)', """
+class A {
+ a() => 1;
+ b() => () => a();
+}
+main() {
+ print(new A().b()());
+}
+""",
+r"""
+function() {
+ return new V.A_b_closure(this);
}"""),
];
diff --git a/tests/compiler/dart2js/js_backend_cps_ir_constructor_test.dart b/tests/compiler/dart2js/js_backend_cps_ir_constructor_test.dart
index abf40d0..1e5f4bf 100644
--- a/tests/compiler/dart2js/js_backend_cps_ir_constructor_test.dart
+++ b/tests/compiler/dart2js/js_backend_cps_ir_constructor_test.dart
@@ -159,14 +159,9 @@
""",
r"""
function() {
- var x, y, w, z, q, v0;
- x = "x";
- y = "y";
- w = "w";
- z = "z";
- q = null;
+ var v0;
v0 = new V.Foo();
- v0.Bar$5$q$w$y$z(x, q, w, y, z);
+ v0.Bar$5$q$w$y$z("x", null, "w", "y", "z");
return v0;
}"""),
];
diff --git a/tests/compiler/dart2js/js_backend_cps_ir_interceptors_test.dart b/tests/compiler/dart2js/js_backend_cps_ir_interceptors_test.dart
index da56918..e15bf3e 100644
--- a/tests/compiler/dart2js/js_backend_cps_ir_interceptors_test.dart
+++ b/tests/compiler/dart2js/js_backend_cps_ir_interceptors_test.dart
@@ -19,10 +19,9 @@
}""",
r"""
function() {
- var g, v0;
+ var g;
g = 1;
- v0 = 3;
- P.print(J.getInterceptor$ns(g).$add(g, v0));
+ P.print(J.getInterceptor$ns(g).$add(g, 3));
return null;
}"""),
const TestEntry("""
@@ -38,7 +37,7 @@
}""",
r"""
function() {
- var l, i, v0, x, j, v1, v2, v3;
+ var l, i, v0, x, j, v1;
l = ["hest", ["h", "e", "s", "t"]];
P.print(J.getInterceptor$as(l).get$length(l));
i = 0;
@@ -52,11 +51,9 @@
v1 = J.getInterceptor$as(x).get$length(x);
if (P.identical(J.getInterceptor$n(j).$lt(j, v1), true)) {
P.print(J.getInterceptor$as(x).$index(x, j));
- v2 = 1;
- j = J.getInterceptor$ns(j).$add(j, v2);
+ j = J.getInterceptor$ns(j).$add(j, 1);
} else {
- v3 = 1;
- i = J.getInterceptor$ns(i).$add(i, v3);
+ i = J.getInterceptor$ns(i).$add(i, 1);
continue L0;
}
}
diff --git a/tests/compiler/dart2js/js_backend_cps_ir_supercall_test.dart b/tests/compiler/dart2js/js_backend_cps_ir_supercall_test.dart
index 4ad6e78..18db6e0 100644
--- a/tests/compiler/dart2js/js_backend_cps_ir_supercall_test.dart
+++ b/tests/compiler/dart2js/js_backend_cps_ir_supercall_test.dart
@@ -24,10 +24,7 @@
}""",
r"""
function(x) {
- var v0, v1;
- v0 = 10;
- v1 = J.getInterceptor$ns(x).$add(x, v0);
- return V.Base.prototype.m$1.call(this, v1);
+ return V.Base.prototype.m$1.call(this, J.getInterceptor$ns(x).$add(x, 10));
}"""),
// Reenable when we support compiling functions that
diff --git a/tests/compiler/dart2js/js_parser_statements_test.dart b/tests/compiler/dart2js/js_parser_statements_test.dart
index 38ccd1c..e9bc2e1 100644
--- a/tests/compiler/dart2js/js_parser_statements_test.dart
+++ b/tests/compiler/dart2js/js_parser_statements_test.dart
@@ -325,5 +325,25 @@
testStatement('label: while (a) { label2: break label;}', [],
'label:\n while (a) {\n label2:\n break label;\n }'),
+
+ testStatement('var # = 3', ['x'], 'var x = 3;'),
+ testStatement('var # = 3',
+ [new jsAst.VariableDeclaration('x')],
+ 'var x = 3;'),
+ testStatement('var # = 3, # = #',
+ ['x', 'y', js.number(2)],
+ 'var x = 3, y = 2;'),
+ testStatement('var #a = 3, #b = #c',
+ {"a": 'x', "b": 'y', "c": js.number(2)},
+ 'var x = 3, y = 2;'),
+ testStatement('function #() {}', ['x'], 'function x() {\n}'),
+ testStatement('function #() {}',
+ [new jsAst.VariableDeclaration('x')],
+ 'function x() {\n}'),
+ testStatement('try {} catch (#) {}', ['x'], 'try {\n} catch (x) {\n}'),
+ testStatement('try {} catch (#a) {}', {"a": 'x'}, 'try {\n} catch (x) {\n}'),
+ testStatement('try {} catch (#a) {}',
+ {"a": new jsAst.VariableDeclaration('x')},
+ 'try {\n} catch (x) {\n}'),
]));
}
diff --git a/tests/compiler/dart2js/memory_source_file_helper.dart b/tests/compiler/dart2js/memory_source_file_helper.dart
index 827e5c1..4efb8ad 100644
--- a/tests/compiler/dart2js/memory_source_file_helper.dart
+++ b/tests/compiler/dart2js/memory_source_file_helper.dart
@@ -35,8 +35,8 @@
if (source == null) {
return new Future.error(new Exception('No such file $resourceUri'));
}
- String resourceName = '$resourceUri';
- this.sourceFiles[resourceName] = new StringSourceFile(resourceName, source);
+ this.sourceFiles[resourceUri] =
+ new StringSourceFile.fromUri(resourceUri, source);
return new Future.value(source);
}
diff --git a/tests/compiler/dart2js/mirrors_exports_test.dart b/tests/compiler/dart2js/mirrors_exports_test.dart
index a95d8516..0f0a127 100644
--- a/tests/compiler/dart2js/mirrors_exports_test.dart
+++ b/tests/compiler/dart2js/mirrors_exports_test.dart
@@ -15,6 +15,7 @@
export 'a.dart' show A2 hide A3, A1;
export 'b.dart' hide B1, B2 show B3;
import 'dart:core' as core;
+import 'c.dart' deferred as c;
main() {}
''',
@@ -27,6 +28,9 @@
class B1 {}
class B2 {}
class B3 {}
+''',
+'c.dart': '''
+foo() => 499;
'''
};
@@ -44,13 +48,17 @@
mirrors.libraries[Uri.parse('memory:b.dart')];
Expect.isNotNull(bLibrary);
+ LibrarySourceMirror cLibrary =
+ mirrors.libraries[Uri.parse('memory:c.dart')];
+ Expect.isNotNull(cLibrary);
+
LibrarySourceMirror coreLibrary =
mirrors.libraries[Uri.parse('dart:core')];
Expect.isNotNull(coreLibrary);
var dependencies = mainLibrary.libraryDependencies;
Expect.isNotNull(dependencies);
- Expect.equals(5, dependencies.length);
+ Expect.equals(6, dependencies.length);
// import 'a.dart' show A1, A2;
var dependency = dependencies[0];
@@ -60,6 +68,7 @@
Expect.equals(mainLibrary, dependency.sourceLibrary);
Expect.equals(aLibrary, dependency.targetLibrary);
Expect.isNull(dependency.prefix);
+ Expect.isFalse(dependency.isDeferred);
var combinators = dependency.combinators;
Expect.isNotNull(combinators);
@@ -79,6 +88,7 @@
Expect.equals(mainLibrary, dependency.sourceLibrary);
Expect.equals(bLibrary, dependency.targetLibrary);
Expect.equals('b', dependency.prefix);
+ Expect.isFalse(dependency.isDeferred);
combinators = dependency.combinators;
Expect.isNotNull(combinators);
@@ -98,6 +108,7 @@
Expect.equals(mainLibrary, dependency.sourceLibrary);
Expect.equals(aLibrary, dependency.targetLibrary);
Expect.isNull(dependency.prefix);
+ Expect.isFalse(dependency.isDeferred);
combinators = dependency.combinators;
Expect.isNotNull(combinators);
@@ -123,6 +134,7 @@
Expect.equals(mainLibrary, dependency.sourceLibrary);
Expect.equals(bLibrary, dependency.targetLibrary);
Expect.isNull(dependency.prefix);
+ Expect.isFalse(dependency.isDeferred);
combinators = dependency.combinators;
Expect.isNotNull(combinators);
@@ -148,6 +160,21 @@
Expect.equals(mainLibrary, dependency.sourceLibrary);
Expect.equals(coreLibrary, dependency.targetLibrary);
Expect.equals('core', dependency.prefix);
+ Expect.isFalse(dependency.isDeferred);
+
+ combinators = dependency.combinators;
+ Expect.isNotNull(combinators);
+ Expect.equals(0, combinators.length);
+
+ // import 'c.dart' deferred as c;
+ dependency = dependencies[5];
+ Expect.isNotNull(dependency);
+ Expect.isTrue(dependency.isImport);
+ Expect.isFalse(dependency.isExport);
+ Expect.equals(mainLibrary, dependency.sourceLibrary);
+ Expect.equals(cLibrary, dependency.targetLibrary);
+ Expect.equals('c', dependency.prefix);
+ Expect.isTrue(dependency.isDeferred);
combinators = dependency.combinators;
Expect.isNotNull(combinators);
diff --git a/tests/compiler/dart2js/mock_compiler.dart b/tests/compiler/dart2js/mock_compiler.dart
index f210f1e..978f924 100644
--- a/tests/compiler/dart2js/mock_compiler.dart
+++ b/tests/compiler/dart2js/mock_compiler.dart
@@ -377,7 +377,7 @@
if (kind == api.Diagnostic.VERBOSE_INFO && !verbose) return;
SourceFile sourceFile;
if (uri == null) {
- sourceFile = new StringSourceFile('analysis', text);
+ sourceFile = new StringSourceFile.fromName('analysis', text);
} else {
sourceFile = compiler.sourceFiles[uri.toString()];
}
diff --git a/tests/compiler/dart2js/number_output_test.dart b/tests/compiler/dart2js/number_output_test.dart
new file mode 100644
index 0000000..6ced21c
--- /dev/null
+++ b/tests/compiler/dart2js/number_output_test.dart
@@ -0,0 +1,49 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "package:expect/expect.dart";
+import "package:async_helper/async_helper.dart";
+import 'memory_compiler.dart';
+
+const MEMORY_SOURCE_FILES = const {
+ 'main.dart': '''
+ main() {
+ print(12300000);
+ print(1234567890123456789012345);
+ print(double.MAX_FINITE);
+ print(-22230000);
+ }'''};
+
+void test({bool minify}) {
+ OutputCollector collector = new OutputCollector();
+ var compiler = compilerFor(MEMORY_SOURCE_FILES,
+ outputProvider: collector,
+ options: minify ? ['--minify'] : []);
+ asyncTest(() => compiler.run(Uri.parse('memory:main.dart')).then((_) {
+ // Check that we use the shorter exponential representations.
+ String jsOutput = collector.getOutput('', 'js');
+ print(jsOutput);
+
+ if (minify) {
+ Expect.isTrue(jsOutput.contains('123e5')); // Shorter than 12300000.
+ Expect.isFalse(jsOutput.contains('12300000'));
+ Expect.isTrue(jsOutput.contains('-2223e4')); // Shorter than -22230000.
+ Expect.isFalse(jsOutput.contains('-22230000'));
+ } else {
+ Expect.isTrue(jsOutput.contains('12300000'));
+ Expect.isTrue(jsOutput.contains('-22230000'));
+ }
+ Expect.isTrue(jsOutput.contains('12345678901234568e8'));
+ Expect.isTrue(jsOutput.contains('17976931348623157e292'));
+ Expect.isFalse(jsOutput.contains('1234567890123456789012345'));
+ // The decimal expansion of double.MAX_FINITE has 308 digits. We only check
+ // for its prefix.
+ Expect.isFalse(jsOutput.contains('179769313486231570814527423731'));
+ }));
+}
+
+main() {
+ test(minify: true);
+ test(minify: false);
+}
diff --git a/tests/compiler/dart2js/parser_helper.dart b/tests/compiler/dart2js/parser_helper.dart
index 344111f..1e58768 100644
--- a/tests/compiler/dart2js/parser_helper.dart
+++ b/tests/compiler/dart2js/parser_helper.dart
@@ -102,7 +102,7 @@
class MockFile extends StringSourceFile {
MockFile(text)
- : super('<string>', text);
+ : super.fromName('<string>', text);
}
var sourceCounter = 0;
diff --git a/tests/compiler/dart2js/source_mapping_test.dart b/tests/compiler/dart2js/source_mapping_test.dart
index 8b5fa4e..77ab4d0 100644
--- a/tests/compiler/dart2js/source_mapping_test.dart
+++ b/tests/compiler/dart2js/source_mapping_test.dart
@@ -30,11 +30,12 @@
}
String code = codeWithMarkers.replaceAll('@', '');
- SourceFile sourceFile = new StringSourceFile('<test script>', code);
+ SourceFile sourceFile = new StringSourceFile.fromName('<test script>', code);
asyncTest(() => compileAll(sourceFile).then((CodeOutput output) {
Set<int> locations = new Set<int>();
output.forEachSourceLocation((int offset, var sourcePosition) {
- if (sourcePosition != null && sourcePosition.sourceFile == sourceFile) {
+ if (sourcePosition != null &&
+ sourcePosition.sourceUri == sourceFile.uri) {
locations.add(sourcePosition.token.charOffset);
}
});
@@ -44,7 +45,7 @@
if (!locations.contains(expectedLocation)) {
int originalLocation = expectedLocation + i;
SourceFile sourceFileWithMarkers =
- new StringSourceFile('<test script>', codeWithMarkers);
+ new StringSourceFile.fromName('<test script>', codeWithMarkers);
String message = sourceFileWithMarkers.getLocationMessage(
'Missing location', originalLocation, originalLocation + 1);
Expect.fail(message);
diff --git a/tests/compiler/dart2js/type_checker_test.dart b/tests/compiler/dart2js/type_checker_test.dart
index 387eb82..adf7513 100644
--- a/tests/compiler/dart2js/type_checker_test.dart
+++ b/tests/compiler/dart2js/type_checker_test.dart
@@ -1358,6 +1358,8 @@
// Check access in assignment.
check('m(Type val) => val = Class;');
check('m(int val) => val = Class;', warnings: NOT_ASSIGNABLE);
+ check('m(Type val) => val = dynamic;');
+ check('m(int val) => val = dynamic;', warnings: NOT_ASSIGNABLE);
// Check access as argument.
check('m(Type val) => m(int);');
@@ -1374,6 +1376,10 @@
// Check static method access.
check('m() => Class.method();');
check('m() => (Class).method();', warnings: MessageKind.METHOD_NOT_FOUND);
+
+ // Check access in invocation.
+ check('m() => Class();', warnings: MessageKind.NOT_CALLABLE);
+ check('m() => dynamic();', warnings: MessageKind.NOT_CALLABLE);
}
Future testInitializers(MockCompiler compiler) {
@@ -2213,7 +2219,7 @@
var endToken = node.getEndToken();
int begin = beginToken.charOffset;
int end = endToken.charOffset + endToken.charCount;
- SourceFile sourceFile = new StringSourceFile('analysis', text);
+ SourceFile sourceFile = new StringSourceFile.fromName('analysis', text);
print(sourceFile.getLocationMessage(message.message.toString(),
begin, end));
}
diff --git a/tests/compiler/dart2js/use_strict_test.dart b/tests/compiler/dart2js/use_strict_test.dart
new file mode 100644
index 0000000..777c77c
--- /dev/null
+++ b/tests/compiler/dart2js/use_strict_test.dart
@@ -0,0 +1,68 @@
+// Copyright (c) 2011, 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:async_helper/async_helper.dart';
+import 'package:expect/expect.dart';
+import 'memory_compiler.dart';
+
+// Use strict does not allow parameters or locals named "arguments" or "eval".
+
+const MEMORY_SOURCE_FILES = const {
+ 'main.dart': '''
+ class A {
+ final arguments;
+ final eval;
+ A(this.arguments, this.eval);
+
+ foo(x, y) => this.arguments + this.eval;
+ }
+
+ class B {
+ foo(arguments, eval) => arguments + eval;
+ }
+
+ class C {
+ foo(var x, var y) {
+ var arguments, eval;
+ arguments = x + y;
+ eval = x - y;
+ if (arguments < eval) return arguments;
+ return eval;
+ }
+ }
+
+ main() {
+ var list = [];
+ for (int i = 0; i < 1000; i++) {
+ list.add(new A(i, i + 1));
+ list.add(new B());
+ list.add(new C());
+ }
+ for (int i = 0; i < list.length; i++) {
+ print(list[i].foo(i, i + 1));
+ }
+ }'''};
+
+main() {
+ OutputCollector collector = new OutputCollector();
+ var compiler = compilerFor(MEMORY_SOURCE_FILES, outputProvider: collector);
+ asyncTest(() => compiler.run(Uri.parse('memory:main.dart')).then((_) {
+ String jsOutput = collector.getOutput('', 'js');
+
+ // Skip comments.
+ List<String> lines = jsOutput.split("\n");
+ RegExp commentLine = new RegExp(r' *//');
+ String filtered = lines
+ .where((String line) => !commentLine.hasMatch(line))
+ .join("\n");
+
+ // TODO(floitsch): we will need to adjust this filter if we start using
+ // 'eval' or 'arguments' ourselves. Currently we disallow any 'eval' or
+ // 'arguments'.
+ RegExp re = new RegExp(r'[^\w$](arguments|eval)[^\w$]');
+ Expect.isFalse(re.hasMatch(filtered));
+ }));
+}
diff --git a/tests/compiler/dart2js/warnings_checker.dart b/tests/compiler/dart2js/warnings_checker.dart
index 396f6b4..e1dba07 100644
--- a/tests/compiler/dart2js/warnings_checker.dart
+++ b/tests/compiler/dart2js/warnings_checker.dart
@@ -25,7 +25,7 @@
Uri uri = script.resolve('../../$test');
String source = UTF8.decode(readAll(uriPathToNative(uri.path)));
SourceFile file = new StringSourceFile(
- relativize(currentDirectory, uri, isWindows), source);
+ uri, relativize(currentDirectory, uri, isWindows), source);
Map<int,String> expectedWarnings = {};
int lineNo = 0;
for (String line in source.split('\n')) {
diff --git a/tests/compiler/dart2js_extra/async_stacktrace_test.dart b/tests/compiler/dart2js_extra/async_stacktrace_test.dart
new file mode 100644
index 0000000..4c8aa7f
--- /dev/null
+++ b/tests/compiler/dart2js_extra/async_stacktrace_test.dart
@@ -0,0 +1,116 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "dart:async";
+
+import "package:expect/expect.dart";
+import "package:async_helper/async_helper.dart";
+
+class Tracer {
+ final String expected;
+ final String name;
+ String _trace = "";
+
+ Tracer(this.expected, [this.name]);
+
+ void trace(msg) {
+ if (name != null) {
+ print("Tracing $name: $msg");
+ }
+ _trace += msg;
+ }
+
+ void done() {
+ Expect.equals(expected, _trace);
+ }
+}
+
+test1(Tracer tracer) {
+ foo() async
+ * /// asyncStar: ok
+ {
+ var savedStackTrace;
+ try {
+ try {
+ tracer.trace("a");
+ throw "Error";
+ } catch (e, st) {
+ tracer.trace("b");
+ savedStackTrace = st;
+ }
+ tracer.trace("c");
+ await new Future.error("Error 2", savedStackTrace);
+ tracer.trace("d");
+ } catch (e, st) {
+ tracer.trace("e");
+ Expect.equals(savedStackTrace.toString(), st.toString());
+ }
+ tracer.trace("f");
+ }
+ return foo()
+ .toList() /// asyncStar: continued
+ ;
+}
+
+test2(Tracer tracer) {
+ var savedStackTrace;
+ foo() async
+ * /// asyncStar: continued
+ {
+ try {
+ tracer.trace("a");
+ throw "Error";
+ } catch (e, st) {
+ tracer.trace("b");
+ savedStackTrace = st;
+ }
+ tracer.trace("c");
+ await new Future.error("Error 2", savedStackTrace);
+ tracer.trace("d");
+ }
+ return foo()
+ .toList() /// asyncStar: continued
+ .catchError((e, st) {
+ tracer.trace("e");
+ Expect.equals(savedStackTrace.toString(), st.toString());
+ });
+}
+
+test3(Tracer tracer) {
+ var savedStackTrace;
+ foo() async
+ * /// asyncStar: continued
+ {
+ try {
+ tracer.trace("a");
+ throw "Error";
+ } catch (e, st) {
+ tracer.trace("b");
+ savedStackTrace = st;
+ rethrow;
+ }
+ }
+ return foo()
+ .toList() /// asyncStar: continued
+ .catchError((e, st) {
+ tracer.trace("c");
+ Expect.equals(savedStackTrace.toString(), st.toString());
+ });
+}
+
+runTest(String expectedTrace, Future test(Tracer tracer)) async {
+ Tracer tracer = new Tracer(expectedTrace);
+ await test(tracer);
+ tracer.done();
+}
+
+runTests() async {
+ await runTest("abcef", test1);
+ await runTest("abce", test2);
+ await runTest("abc", test3);
+}
+
+main() {
+ asyncTest(runTests);
+}
\ No newline at end of file
diff --git a/tests/compiler/dart2js_native/catch_javascript_null_stack_trace_test.dart b/tests/compiler/dart2js_native/catch_javascript_null_stack_trace_test.dart
new file mode 100644
index 0000000..43a6b22
--- /dev/null
+++ b/tests/compiler/dart2js_native/catch_javascript_null_stack_trace_test.dart
@@ -0,0 +1,23 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:_foreign_helper' show JS;
+import "package:expect/expect.dart";
+
+// Try throwing a javascript null, and getting a stack-trace from it.
+
+main() {
+ var savedException;
+ try {
+ try {
+ JS('', '(function () {throw null;})()');
+ } catch (e, st) {
+ savedException = st;
+ rethrow;
+ }
+ } catch (error, st) {
+ // st will be empty, but should not throw on toString().
+ Expect.equals(savedException.toString(), st.toString());
+ }
+}
diff --git a/tests/compiler/dart2js_native/dart2js_native.status b/tests/compiler/dart2js_native/dart2js_native.status
index ca0ae5d..6a949b1 100644
--- a/tests/compiler/dart2js_native/dart2js_native.status
+++ b/tests/compiler/dart2js_native/dart2js_native.status
@@ -8,8 +8,8 @@
[ $compiler == dart2js ]
bound_closure_super_test: Fail
call_on_native_class_test: CompileTimeError # Issue 14813
-native_no_such_method_exception4_frog_test: Fail # Issue 9631
-native_no_such_method_exception5_frog_test: Fail # Issue 9631
+native_no_such_method_exception4_frog_test: CompileTimeError # Issue 9631
+native_no_such_method_exception5_frog_test: CompileTimeError # Issue 9631
[ $compiler == dart2js ]
fake_thing_test: Fail # Issue 13010
diff --git a/tests/compiler/dart2js_native/native_no_such_method_exception4_frog_test.dart b/tests/compiler/dart2js_native/native_no_such_method_exception4_frog_test.dart
index ee0af94..d8af826 100644
--- a/tests/compiler/dart2js_native/native_no_such_method_exception4_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_no_such_method_exception4_frog_test.dart
@@ -11,7 +11,7 @@
baz(x, y, z) => "baz";
}
-String getName(im) => reflect(new GetName()).delegate(im);;
+String getName(im) => reflect(new GetName()).delegate(im);
@Native("A")
class A {
diff --git a/tests/corelib/apply4_test.dart b/tests/corelib/apply4_test.dart
new file mode 100644
index 0000000..f617456
--- /dev/null
+++ b/tests/corelib/apply4_test.dart
@@ -0,0 +1,20 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "package:expect/expect.dart";
+
+// Testing Function.apply calls work correctly for arities that are not
+// otherwise present in the program (and thus might not have stubs
+// generated).
+
+class A {
+ foo(x, [y, z, a, b, c, d = 99, e, f, g, h, i, j]) => "$x $d";
+}
+
+main() {
+ var a = new A();
+ var clos = a.foo;
+ Expect.equals(Function.apply(clos, ["well"]), "well 99");
+ Expect.equals(Function.apply(clos, ["well", 0, 1, 2, 3, 4, 5, 6]), "well 5");
+}
diff --git a/tests/corelib/big_integer_arith_vm_test.dart b/tests/corelib/big_integer_arith_vm_test.dart
index 2e753a5..4c04c03 100644
--- a/tests/corelib/big_integer_arith_vm_test.dart
+++ b/tests/corelib/big_integer_arith_vm_test.dart
@@ -139,6 +139,90 @@
}
}
+testBigintModPow() {
+ var x, e, m;
+ x = 1234567890;
+ e = 1000000001;
+ m = 19;
+ Expect.equals(11, x.modPow(e, m));
+ x = 1234567890;
+ e = 19;
+ m = 1000000001;
+ Expect.equals(122998977, x.modPow(e, m));
+ x = 19;
+ e = 1234567890;
+ m = 1000000001;
+ Expect.equals(619059596, x.modPow(e, m));
+ x = 19;
+ e = 1000000001;
+ m = 1234567890;
+ Expect.equals(84910879, x.modPow(e, m));
+ x = 1000000001;
+ e = 19;
+ m = 1234567890;
+ Expect.equals(872984351, x.modPow(e, m));
+ x = 1000000001;
+ e = 1234567890;
+ m = 19;
+ Expect.equals(0, x.modPow(e, m));
+ x = 12345678901234567890;
+ e = 10000000000000000001;
+ m = 19;
+ Expect.equals(2, x.modPow(e, m));
+ x = 12345678901234567890;
+ e = 19;
+ m = 10000000000000000001;
+ Expect.equals(3239137215315834625, x.modPow(e, m));
+ x = 19;
+ e = 12345678901234567890;
+ m = 10000000000000000001;
+ Expect.equals(4544207837373941034, x.modPow(e, m));
+ x = 19;
+ e = 10000000000000000001;
+ m = 12345678901234567890;
+ Expect.equals(11135411705397624859, x.modPow(e, m));
+ x = 10000000000000000001;
+ e = 19;
+ m = 12345678901234567890;
+ Expect.equals(2034013733189773841, x.modPow(e, m));
+ x = 10000000000000000001;
+ e = 12345678901234567890;
+ m = 19;
+ Expect.equals(1, x.modPow(e, m));
+ x = 12345678901234567890;
+ e = 19;
+ m = 10000000000000000001;
+ Expect.equals(3239137215315834625, x.modPow(e, m));
+ x = 12345678901234567890;
+ e = 10000000000000000001;
+ m = 19;
+ Expect.equals(2, x.modPow(e, m));
+ x = 123456789012345678901234567890;
+ e = 123456789012345678901234567891;
+ m = 123456789012345678901234567899;
+ Expect.equals(116401406051033429924651549616, x.modPow(e, m));
+ x = 123456789012345678901234567890;
+ e = 123456789012345678901234567899;
+ m = 123456789012345678901234567891;
+ Expect.equals(123456789012345678901234567890, x.modPow(e, m));
+ x = 123456789012345678901234567899;
+ e = 123456789012345678901234567890;
+ m = 123456789012345678901234567891;
+ Expect.equals(35088523091000351053091545070, x.modPow(e, m));
+ x = 123456789012345678901234567899;
+ e = 123456789012345678901234567891;
+ m = 123456789012345678901234567890;
+ Expect.equals(18310047270234132455316941949, x.modPow(e, m));
+ x = 123456789012345678901234567891;
+ e = 123456789012345678901234567899;
+ m = 123456789012345678901234567890;
+ Expect.equals(1, x.modPow(e, m));
+ x = 123456789012345678901234567891;
+ e = 123456789012345678901234567890;
+ m = 123456789012345678901234567899;
+ Expect.equals(40128068573873018143207285483, x.modPow(e, m));
+}
+
testBigintNegate() {
var a = 0xF000000000000000F;
var b = ~a; // negate.
@@ -166,9 +250,10 @@
testBigintAdd();
testBigintSub();
testBigintMul();
- testBigintModulo();
testBigintTruncDiv();
testBigintDiv();
+ testBigintModulo();
+ testBigintModPow();
testBigintNegate();
testShiftAmount();
Expect.equals(12345678901234567890, (12345678901234567890).abs());
@@ -177,5 +262,4 @@
var b = 10000000000000000001;
Expect.equals(false, a.hashCode == b.hashCode);
Expect.equals(true, a.hashCode == (b - 1).hashCode);
- // TODO(regis): Add a test for modPow once it is public.
}
diff --git a/tests/corelib/errors_test.dart b/tests/corelib/errors_test.dart
new file mode 100644
index 0000000..d5eca35
--- /dev/null
+++ b/tests/corelib/errors_test.dart
@@ -0,0 +1,73 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "package:expect/expect.dart";
+
+// Test that error constructors do what they are documented as doing.
+
+main() {
+ Expect.equals("Invalid argument(s)",
+ new ArgumentError().toString());
+ Expect.equals("Invalid argument(s): message",
+ new ArgumentError("message").toString());
+ Expect.equals("Invalid argument: null",
+ new ArgumentError.value(null).toString());
+ Expect.equals("Invalid argument (foo): null",
+ new ArgumentError.value(null, "foo").toString());
+ Expect.equals("Invalid argument (foo): 42",
+ new ArgumentError.value(42, "foo").toString());
+ Expect.equals("Invalid argument (foo): message: 42",
+ new ArgumentError.value(42, "foo", "message").toString());
+ Expect.equals("Invalid argument: message: 42",
+ new ArgumentError.value(42, null, "message").toString());
+ Expect.equals("Invalid argument: Must not be null: null",
+ new ArgumentError.notNull().toString());
+ Expect.equals("Invalid argument (foo): Must not be null: null",
+ new ArgumentError.notNull("foo").toString());
+
+ Expect.equals("RangeError",
+ new RangeError(null).toString());
+ Expect.equals("RangeError: message",
+ new RangeError("message").toString());
+ Expect.equals("RangeError: Value not in range: 42",
+ new RangeError.value(42).toString());
+ Expect.equals("RangeError (foo): Value not in range: 42",
+ new RangeError.value(42, "foo").toString());
+ Expect.equals("RangeError (foo): message: 42",
+ new RangeError.value(42, "foo", "message").toString());
+ Expect.equals("RangeError: message: 42",
+ new RangeError.value(42, null, "message").toString());
+
+ Expect.equals("RangeError: Invalid value: Not in range 2..9, inclusive: 42",
+ new RangeError.range(42, 2, 9).toString());
+ Expect.equals("RangeError (foo): Invalid value: Not in range 2..9, "
+ "inclusive: 42",
+ new RangeError.range(42, 2, 9, "foo").toString());
+ Expect.equals("RangeError (foo): message: Not in range 2..9, inclusive: 42",
+ new RangeError.range(42, 2, 9, "foo", "message").toString());
+ Expect.equals("RangeError: message: Not in range 2..9, inclusive: 42",
+ new RangeError.range(42, 2, 9, null, "message").toString());
+
+ Expect.equals("RangeError: Index out of range: "
+ "index should be less than 3: 42",
+ new RangeError.index(42, [1, 2, 3]).toString());
+ Expect.equals("RangeError (foo): Index out of range: "
+ "index should be less than 3: 42",
+ new RangeError.index(42, [1, 2, 3], "foo").toString());
+ Expect.equals("RangeError (foo): message: "
+ "index should be less than 3: 42",
+ new RangeError.index(42, [1, 2, 3],
+ "foo", "message").toString());
+ Expect.equals("RangeError: message: "
+ "index should be less than 3: 42",
+ new RangeError.index(42, [1, 2, 3],
+ null, "message").toString());
+ Expect.equals("RangeError (foo): message: "
+ "index should be less than 2: 42",
+ new RangeError.index(42, [1, 2, 3],
+ "foo", "message", 2).toString());
+ Expect.equals("RangeError: Index out of range: "
+ "index must not be negative: -5",
+ new RangeError.index(-5, [1, 2, 3]).toString());
+}
diff --git a/tests/corelib/hash_map2_internal_test.dart b/tests/corelib/hash_map2_internal_test.dart
deleted file mode 100644
index 73a1c77..0000000
--- a/tests/corelib/hash_map2_internal_test.dart
+++ /dev/null
@@ -1,293 +0,0 @@
-// Copyright (c) 2013, 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.
-
-// This copy of hash_map2_test exercises the internal Map implementation.
-// VMOptions=--use_internal_hash_map
-
-// Tests of hash map behavior, with focus in iteration and concurrent
-// modification errors.
-
-library hash_map2_test;
-import "package:expect/expect.dart";
-import 'dart:collection';
-
-testMap(Map newMap(), Map newMapFrom(Map map)) {
- Map gen(int from, int to) {
- Map map = new LinkedHashMap();
- for (int i = from; i < to; i++) map[i] = i;
- return map;
- }
-
- bool odd(int n) => (n & 1) == 1;
- bool even(int n) => (n & 1) == 0;
- void addAll(Map toMap, Map fromMap) {
- fromMap.forEach((k, v) { toMap[k] = v; });
- }
-
- { // Test growing to largish capacity.
- Map map = newMap();
-
- for (int i = 0; i < 256; i++) {
- map[i] = i;
- }
- addAll(map, gen(256, 512));
- addAll(map, newMapFrom(gen(512, 1000)));
- Expect.equals(1000, map.length);
-
- // Remove half.
- for (int i = 0; i < 1000; i += 2) map.remove(i);
- Expect.equals(500, map.length);
- Expect.isFalse(map.keys.any(even));
- Expect.isTrue(map.keys.every(odd));
-
- // Re-add all.
- addAll(map, gen(0, 1000));
- Expect.equals(1000, map.length);
- }
-
- { // Test having many deleted elements.
- Map map = newMap();
- map[0] = 0;
- for (int i = 0; i < 1000; i++) {
- map[i + 1] = i + 1;
- map.remove(i);
- Expect.equals(1, map.length);
- }
- }
-
- { // Test having many elements with same hashCode
- Map map = newMap();
- for (int i = 0; i < 1000; i++) {
- map[new BadHashCode()] = 0;
- }
- Expect.equals(1000, map.length);
- }
-
- { // Check concurrent modification
- Map map = newMap()..[0] = 0..[1] = 1;
-
- { // Test adding before a moveNext.
- Iterator iter = map.keys.iterator;
- iter.moveNext();
- map[1] = 9; // Updating existing key isn't a modification.
- iter.moveNext();
- map[2] = 2;
- Expect.throws(iter.moveNext, (e) => e is Error);
- }
-
- { // Test adding after last element.
- Iterator iter = map.keys.iterator;
- Expect.equals(3, map.length);
- iter.moveNext();
- iter.moveNext();
- iter.moveNext();
- map[3] = 3;
- Expect.throws(iter.moveNext, (e) => e is Error);
- }
-
- { // Test removing during iteration.
- Iterator iter = map.keys.iterator;
- iter.moveNext();
- map.remove(1000); // Not a modification if it's not there.
- iter.moveNext();
- int n = iter.current;
- map.remove(n);
- // Removing doesn't change current.
- Expect.equals(n, iter.current);
- Expect.throws(iter.moveNext, (e) => e is Error);
- }
-
- { // Test removing after last element.
- Iterator iter = map.keys.iterator;
- Expect.equals(3, map.length);
- iter.moveNext();
- iter.moveNext();
- iter.moveNext();
- int n = iter.current;
- map.remove(n);
- // Removing doesn't change current.
- Expect.equals(n, iter.current);
- Expect.throws(iter.moveNext, (e) => e is Error);
- }
-
- { // Test that updating value of existing key doesn't cause concurrent
- // modification error.
- Iterator iter = map.keys.iterator;
- Expect.equals(2, map.length);
- iter.moveNext();
- int n = iter.current;
- map[n] = n * 2;
- iter.moveNext();
- Expect.equals(map[iter.current], iter.current);
- }
-
- { // Test that modification during putIfAbsent is not an error.
- map.putIfAbsent(4, () {
- map[5] = 5;
- map[4] = -1;
- return 4;
- });
- Expect.equals(4, map[4]);
- Expect.equals(5, map[5]);
- }
-
- { // Check adding many existing keys isn't considered modification.
- Map map2 = newMap();
- for (var key in map.keys) {
- map2[key] = map[key] + 1;
- }
- Iterator iter = map.keys.iterator;
- addAll(map, map2);
- // Shouldn't throw.
- iter.moveNext();
- }
- }
-
- { // Regression test for bug in putIfAbsent where adding an element
- // that make the table grow, can be lost.
- Map map = newMap();
- map.putIfAbsent("S", () => 0);
- map.putIfAbsent("T", () => 0);
- map.putIfAbsent("U", () => 0);
- map.putIfAbsent("C", () => 0);
- map.putIfAbsent("a", () => 0);
- map.putIfAbsent("b", () => 0);
- map.putIfAbsent("n", () => 0);
- Expect.isTrue(map.containsKey("n"));
- }
-
- { // Check that putIfAbsent works just as well as put.
- Map map = newMap();
- for (int i = 0; i < 128; i++) {
- map.putIfAbsent(i, () => i);
- Expect.isTrue(map.containsKey(i));
- map.putIfAbsent(i >> 1, () => -1); // Never triggers.
- }
- for (int i = 0; i < 128; i++) {
- Expect.equals(i, map[i]);
- }
- }
-
- { // Check that updating existing elements is not a modification.
- // This must be the case even if the underlying data structure is
- // nearly full.
- for (int i = 1; i < 128; i++) {
- // Create maps of different sizes, some of which should be
- // at a limit of the underlying data structure.
- Map map = newMapFrom(gen(0, i));
-
- // ForEach-iteration.
- map.forEach((key, v) {
- Expect.equals(key, map[key]);
- map[key] = key + 1;
- map.remove(1000); // Removing something not there.
- map.putIfAbsent(key, () => Expect.fail("SHOULD NOT BE ABSENT"));
- // Doesn't cause ConcurrentModificationError.
- });
-
- // for-in iteration.
- for (int key in map.keys) {
- Expect.equals(key + 1, map[key]);
- map[key] = map[key] + 1;
- map.remove(1000); // Removing something not there.
- map.putIfAbsent(key, () => Expect.fail("SHOULD NOT BE ABSENT"));
- // Doesn't cause ConcurrentModificationError.
- }
-
- // Raw iterator.
- Iterator iter = map.keys.iterator;
- for (int key = 0; key < i; key++) {
- Expect.equals(key + 2, map[key]);
- map[key] = key + 3;
- map.remove(1000); // Removing something not there.
- map.putIfAbsent(key, () => Expect.fail("SHOULD NOT BE ABSENT"));
- // Doesn't cause ConcurrentModificationError on the moveNext.
- }
- iter.moveNext(); // Should not throw.
-
- // Remove a lot of elements, which can cause a re-tabulation.
- for (int key = 1; key < i; key++) {
- Expect.equals(key + 3, map[key]);
- map.remove(key);
- }
- iter = map.keys.iterator;
- map[0] = 2;
- iter.moveNext(); // Should not throw.
- }
- }
-
-
- { // Check that null can be in the map.
- Map map = newMap();
- map[null] = 0;
- Expect.equals(1, map.length);
- Expect.isTrue(map.containsKey(null));
- Expect.isNull(map.keys.first);
- Expect.isNull(map.keys.last);
- map[null] = 1;
- Expect.equals(1, map.length);
- Expect.isTrue(map.containsKey(null));
- map.remove(null);
- Expect.isTrue(map.isEmpty);
- Expect.isFalse(map.containsKey(null));
-
- // Created using map.from.
- map = newMapFrom(new Map()..[null] = 0);
- Expect.equals(1, map.length);
- Expect.isTrue(map.containsKey(null));
- Expect.isNull(map.keys.first);
- Expect.isNull(map.keys.last);
- map[null] = 1;
- Expect.equals(1, map.length);
- Expect.isTrue(map.containsKey(null));
- map.remove(null);
- Expect.isTrue(map.isEmpty);
- Expect.isFalse(map.containsKey(null));
-
- Map fromMap = new Map();
- fromMap[1] = 0;
- fromMap[2] = 0;
- fromMap[3] = 0;
- fromMap[null] = 0;
- fromMap[4] = 0;
- fromMap[5] = 0;
- fromMap[6] = 0;
- Expect.equals(7, fromMap.length);
-
- // map that grows with null in it.
- map = newMapFrom(fromMap);
- Expect.equals(7, map.length);
- for (int i = 7; i < 128; i++) {
- map[i] = 0;
- }
- Expect.equals(128, map.length);
- Expect.isTrue(map.containsKey(null));
- map[null] = 1;
- Expect.equals(128, map.length);
- Expect.isTrue(map.containsKey(null));
- map.remove(null);
- Expect.equals(127, map.length);
- Expect.isFalse(map.containsKey(null));
- }
-}
-
-void main() {
- Expect.isTrue(new HashMap<int, String>() is Map<int, String>);
- Expect.isTrue(new LinkedHashMap<int, String>() is Map<int, String>);
- Expect.isTrue(new HashMap<String, int>.from({}) is Map<String, int>);
- Expect.isTrue(new LinkedHashMap<String, int>.from({}) is Map<String, int>);
- Expect.isTrue(<String, int>{} is Map<String, int>);
- Expect.isTrue(const <String, int>{} is Map<String, int>);
-
- testMap(() => new HashMap(), (m) => new HashMap.from(m));
- testMap(() => new LinkedHashMap(), (m) => new LinkedHashMap.from(m));
-}
-
-
-class BadHashCode {
- static int idCounter = 0;
- final int id;
- BadHashCode() : id = idCounter++;
- int get hashCode => 42;
-}
diff --git a/tests/corelib/hash_map2_test.dart b/tests/corelib/hash_map2_test.dart
index cc4ed3e..32c72eb 100644
--- a/tests/corelib/hash_map2_test.dart
+++ b/tests/corelib/hash_map2_test.dart
@@ -1,6 +1,12 @@
// Copyright (c) 2013, 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.
+<<<<<<< .working
+//
+// VMOptions=
+// VMOptions=--use_compact_hash=false
+// VMOptions=--use_internal_hash_map --use_compact_hash=false
+>>>>>>> .merge-right.r43886
// Tests of hash map behavior, with focus in iteration and concurrent
// modification errors.
diff --git a/tests/corelib/hash_map_internal_test.dart b/tests/corelib/hash_map_internal_test.dart
deleted file mode 100644
index 8d80012..0000000
--- a/tests/corelib/hash_map_internal_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2011, 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.
-
-// This copy of hash_map_test exercises the internal Map implementation.
-// VMOptions=--use_internal_hash_map
-
-import "package:expect/expect.dart";
-
-// Test program for the HashMap class.
-
-class HashMapTest {
-
- static testMain() {
- var m = new Map();
- Expect.equals(0, m.length);
- Expect.equals(true, m.isEmpty);
- m["one"] = 1;
- Expect.equals(1, m.length);
- Expect.equals(false, m.isEmpty);
- Expect.equals(1, m["one"]);
- }
-}
-
-main() {
- HashMapTest.testMain();
-}
diff --git a/tests/corelib/hash_map_test.dart b/tests/corelib/hash_map_test.dart
index 52848e1..4d9ca76 100644
--- a/tests/corelib/hash_map_test.dart
+++ b/tests/corelib/hash_map_test.dart
@@ -1,6 +1,12 @@
// Copyright (c) 2011, 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.
+<<<<<<< .working
+//
+// VMOptions=
+// VMOptions=--use_compact_hash=false
+// VMOptions=--use_internal_hash_map --use_compact_hash=false
+>>>>>>> .merge-right.r43886
import "package:expect/expect.dart";
diff --git a/tests/corelib/hash_set_test.dart b/tests/corelib/hash_set_test.dart
index 835e300..c3fbd68 100644
--- a/tests/corelib/hash_set_test.dart
+++ b/tests/corelib/hash_set_test.dart
@@ -1,6 +1,11 @@
// Copyright (c) 2013, 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.
+<<<<<<< .working
+//
+// VMOptions=
+// VMOptions=--use_compact_hash=false
+>>>>>>> .merge-right.r43886
// Tests of hash set behavior, with focus in iteration and concurrent
// modification errors.
@@ -8,6 +13,7 @@
library hash_map2_test;
import "package:expect/expect.dart";
import 'dart:collection';
+import 'dart:math' as math;
testSet(Set newSet(), Set newSetFrom(Iterable from)) {
@@ -251,6 +257,21 @@
set.add(-0.0);
Expect.identical(-0.0, set.lookup(0.0));
}
+
+ { // Test special hash codes
+ Set set = newSet();
+ List keys = [];
+ // Powers of two
+ for (int i = 65; i >= 2; --i) {
+ keys.add(new Mutable(math.pow(2, i)));
+ }
+ for (var key in keys) {
+ Expect.isTrue(set.add(key));
+ }
+ for (var key in keys) {
+ Expect.isTrue(set.contains(key));
+ }
+ }
}
diff --git a/tests/corelib/string_replace_test.dart b/tests/corelib/string_replace_test.dart
index df426fa..b8486ae 100644
--- a/tests/corelib/string_replace_test.dart
+++ b/tests/corelib/string_replace_test.dart
@@ -4,92 +4,215 @@
import "package:expect/expect.dart";
-class StringReplaceTest {
- static testMain() {
- Expect.equals(
- "AtoBtoCDtoE", "AfromBtoCDtoE".replaceFirst("from", "to"));
+main() {
+ // Test replaceFirst.
+ Expect.equals(
+ "AtoBtoCDtoE", "AfromBtoCDtoE".replaceFirst("from", "to"));
- // Test with the replaced string at the begining.
- Expect.equals(
- "toABtoCDtoE", "fromABtoCDtoE".replaceFirst("from", "to"));
+ // Test with the replaced string at the begining.
+ Expect.equals(
+ "toABtoCDtoE", "fromABtoCDtoE".replaceFirst("from", "to"));
- // Test with the replaced string at the end.
- Expect.equals(
- "toABtoCDtoEto", "fromABtoCDtoEto".replaceFirst("from", "to"));
+ // Test with the replaced string at the end.
+ Expect.equals(
+ "toABtoCDtoEto", "fromABtoCDtoEto".replaceFirst("from", "to"));
- // Test when there are no occurence of the string to replace.
- Expect.equals("ABC", "ABC".replaceFirst("from", "to"));
+ // Test when there are no occurence of the string to replace.
+ Expect.equals("ABC", "ABC".replaceFirst("from", "to"));
- // Test when the string to change is the empty string.
- Expect.equals("", "".replaceFirst("from", "to"));
+ // Test when the string to change is the empty string.
+ Expect.equals("", "".replaceFirst("from", "to"));
- // Test when the string to change is a substring of the string to
- // replace.
- Expect.equals("fro", "fro".replaceFirst("from", "to"));
+ // Test when the string to change is a substring of the string to
+ // replace.
+ Expect.equals("fro", "fro".replaceFirst("from", "to"));
- // Test when the string to change is the replaced string.
- Expect.equals("to", "from".replaceFirst("from", "to"));
+ // Test when the string to change is the replaced string.
+ Expect.equals("to", "from".replaceFirst("from", "to"));
- // Test when the string to change is the replacement string.
- Expect.equals("to", "to".replaceFirst("from", "to"));
+ // Test when the string to change is the replacement string.
+ Expect.equals("to", "to".replaceFirst("from", "to"));
- // Test replacing by the empty string.
- Expect.equals("", "from".replaceFirst("from", ""));
- Expect.equals("AB", "AfromB".replaceFirst("from", ""));
+ // Test replacing by the empty string.
+ Expect.equals("", "from".replaceFirst("from", ""));
+ Expect.equals("AB", "AfromB".replaceFirst("from", ""));
- // Test changing the empty string.
- Expect.equals("to", "".replaceFirst("", "to"));
+ // Test changing the empty string.
+ Expect.equals("to", "".replaceFirst("", "to"));
- // Test replacing the empty string.
- Expect.equals("toAtoBtoCto", "AtoBtoCto".replaceFirst("", "to"));
+ // Test replacing the empty string.
+ Expect.equals("toAtoBtoCto", "AtoBtoCto".replaceFirst("", "to"));
- // Test startIndex.
- Expect.equals(
- "foo-AAA-foo-bar", "foo-bar-foo-bar".replaceFirst("bar", "AAA", 4));
+ // Test startIndex.
+ Expect.equals(
+ "foo-AAA-foo-bar", "foo-bar-foo-bar".replaceFirst("bar", "AAA", 4));
- // Test startIndex skipping one case at the begining.
- Expect.equals(
- "foo-bar-AAA-bar", "foo-bar-foo-bar".replaceFirst("foo", "AAA", 1));
+ // Test startIndex skipping one case at the begining.
+ Expect.equals(
+ "foo-bar-AAA-bar", "foo-bar-foo-bar".replaceFirst("foo", "AAA", 1));
- // Test startIndex skipping one case at the begining.
- Expect.equals(
- "foo-bar-foo-AAA", "foo-bar-foo-bar".replaceFirst("bar", "AAA", 5));
+ // Test startIndex skipping one case at the begining.
+ Expect.equals(
+ "foo-bar-foo-AAA", "foo-bar-foo-bar".replaceFirst("bar", "AAA", 5));
- // Test startIndex replacing with the empty string.
- Expect.equals(
- "foo-bar--bar", "foo-bar-foo-bar".replaceFirst("foo", "", 1));
+ // Test startIndex replacing with the empty string.
+ Expect.equals(
+ "foo-bar--bar", "foo-bar-foo-bar".replaceFirst("foo", "", 1));
- // Test startIndex with a RegExp with carat
- Expect.equals(
- "foo-bar-foo-bar",
- "foo-bar-foo-bar".replaceFirst(new RegExp(r"^foo"), "", 8));
+ // Test startIndex with a RegExp with carat
+ Expect.equals(
+ "foo-bar-foo-bar",
+ "foo-bar-foo-bar".replaceFirst(new RegExp(r"^foo"), "", 8));
- // Test startIndex with a RegExp
- Expect.equals(
- "aaa{3}X{3}", "aaa{3}aaa{3}".replaceFirst(new RegExp(r"a{3}"), "X", 1));
+ // Test startIndex with a RegExp
+ Expect.equals(
+ "aaa{3}X{3}", "aaa{3}aaa{3}".replaceFirst(new RegExp(r"a{3}"), "X", 1));
- // Test startIndex with regexp-looking String
- Expect.equals(
- "aaa{3}aaX", "aaa{3}aaa{3}".replaceFirst("a{3}", "X", 3));
+ // Test startIndex with regexp-looking String
+ Expect.equals(
+ "aaa{3}aaX", "aaa{3}aaa{3}".replaceFirst("a{3}", "X", 3));
- // Test negative startIndex
- Expect.throws(
- () => "hello".replaceFirst("h", "X", -1), (e) => e is RangeError);
+ // Test negative startIndex
+ Expect.throws(
+ () => "hello".replaceFirst("h", "X", -1), (e) => e is RangeError);
- // Test startIndex too large
- Expect.throws(
- () => "hello".replaceFirst("h", "X", 6), (e) => e is RangeError);
+ // Test startIndex too large
+ Expect.throws(
+ () => "hello".replaceFirst("h", "X", 6), (e) => e is RangeError);
- // Test null startIndex
- Expect.throws(
- () => "hello".replaceFirst("h", "X", null), (e) => e is ArgumentError);
+ // Test null startIndex
+ Expect.throws(
+ () => "hello".replaceFirst("h", "X", null), (e) => e is ArgumentError);
- // Test object startIndex
- Expect.throws(
- () => "hello".replaceFirst("h", "X", new Object()));
- }
+ // Test object startIndex
+ Expect.throws(
+ () => "hello".replaceFirst("h", "X", new Object()));
+
+
+ // Test replaceFirstMapped.
+
+ Expect.equals(
+ "AtoBtoCDtoE", "AfromBtoCDtoE".replaceFirstMapped("from", (_) => "to"));
+
+ // Test with the replaced string at the begining.
+ Expect.equals(
+ "toABtoCDtoE", "fromABtoCDtoE".replaceFirstMapped("from", (_) => "to"));
+
+ // Test with the replaced string at the end.
+ Expect.equals(
+ "toABtoCDtoEto",
+ "fromABtoCDtoEto".replaceFirstMapped("from", (_) => "to"));
+
+ // Test when there are no occurence of the string to replace.
+ Expect.equals("ABC", "ABC".replaceFirstMapped("from", (_) => "to"));
+
+ // Test when the string to change is the empty string.
+ Expect.equals("", "".replaceFirstMapped("from", (_) => "to"));
+
+ // Test when the string to change is a substring of the string to
+ // replace.
+ Expect.equals("fro", "fro".replaceFirstMapped("from", (_) => "to"));
+
+ // Test when the string to change is the replaced string.
+ Expect.equals("to", "from".replaceFirstMapped("from", (_) => "to"));
+
+ // Test when the string to change is the replacement string.
+ Expect.equals("to", "to".replaceFirstMapped("from", (_) => "to"));
+
+ // Test replacing by the empty string.
+ Expect.equals("", "from".replaceFirstMapped("from", (_) => ""));
+ Expect.equals("AB", "AfromB".replaceFirstMapped("from", (_) => ""));
+
+ // Test changing the empty string.
+ Expect.equals("to", "".replaceFirstMapped("", (_) => "to"));
+
+ // Test replacing the empty string.
+ Expect.equals("toAtoBtoCto", "AtoBtoCto".replaceFirstMapped("", (_) => "to"));
+
+ // Test startIndex.
+ Expect.equals(
+ "foo-AAA-foo-bar",
+ "foo-bar-foo-bar".replaceFirstMapped("bar", (_) => "AAA", 4));
+
+ // Test startIndex skipping one case at the begining.
+ Expect.equals(
+ "foo-bar-AAA-bar",
+ "foo-bar-foo-bar".replaceFirstMapped("foo", (_) => "AAA", 1));
+
+ // Test startIndex skipping one case at the begining.
+ Expect.equals(
+ "foo-bar-foo-AAA",
+ "foo-bar-foo-bar".replaceFirstMapped("bar", (_) => "AAA", 5));
+
+ // Test startIndex replacing with the empty string.
+ Expect.equals(
+ "foo-bar--bar", "foo-bar-foo-bar".replaceFirstMapped("foo", (_) => "", 1));
+
+ // Test startIndex with a RegExp with carat
+ Expect.equals(
+ "foo-bar-foo-bar",
+ "foo-bar-foo-bar".replaceFirstMapped(new RegExp(r"^foo"), (_) => "", 8));
+
+ // Test startIndex with a RegExp
+ Expect.equals(
+ "aaa{3}X{3}",
+ "aaa{3}aaa{3}".replaceFirstMapped(new RegExp(r"a{3}"), (_) => "X", 1));
+
+ // Test startIndex with regexp-looking String
+ Expect.equals(
+ "aaa{3}aaX", "aaa{3}aaa{3}".replaceFirstMapped("a{3}", (_) => "X", 3));
+
+ // Test negative startIndex
+ Expect.throws(
+ () => "hello".replaceFirstMapped("h", (_) => "X", -1),
+ (e) => e is RangeError);
+
+ // Test startIndex too large
+ Expect.throws(
+ () => "hello".replaceFirstMapped("h", (_) => "X", 6),
+ (e) => e is RangeError);
+
+ // Test null startIndex
+ Expect.throws(
+ () => "hello".replaceFirstMapped("h", (_) => "X", null),
+ (e) => e is ArgumentError);
+
+ // Test object startIndex
+ Expect.throws(
+ () => "hello".replaceFirstMapped("h", (_) => "X", new Object()));
+
+ // Test replacement depending on argument.
+ Expect.equals(
+ "foo-BAR-foo-bar",
+ "foo-bar-foo-bar".replaceFirstMapped("bar", (v) => v[0].toUpperCase()));
+
+ Expect.equals(
+ "foo-[bar]-foo-bar",
+ "foo-bar-foo-bar".replaceFirstMapped("bar", (v) => "[${v[0]}]"));
+
+ Expect.equals("foo-foo-bar-foo-bar-foo-bar",
+ "foo-bar-foo-bar".replaceFirstMapped("bar", (v) => v.input));
+
+ // Test replacement throwing.
+ Expect.throws(
+ () => "foo-bar".replaceFirstMapped("bar", (v) => throw 42),
+ (e) => e == 42);
+
+ // Test replacement returning non-String.
+ var o = new Object();
+ Expect.equals("foo-$o", "foo-bar".replaceFirstMapped("bar",
+ (v) { return o; }));
+
+ Expect.equals("foo-42", "foo-bar".replaceFirstMapped("bar",
+ (v) { return 42; }));
+
+ // Test replacement returning object throwing on string-conversion.
+ var n = new Naughty();
+ Expect.throws(
+ () => "foo-bar".replaceFirstMapped("bar", (v) { return n; }));
}
-main() {
- StringReplaceTest.testMain();
+// Fails to return a String on toString, throws if converted by "$naughty".
+class Naughty {
+ toString() => this;
}
diff --git a/tests/html/html.status b/tests/html/html.status
index 0d80d41..68f0451 100644
--- a/tests/html/html.status
+++ b/tests/html/html.status
@@ -9,8 +9,6 @@
[ $compiler == none && ($runtime == drt || $runtime == dartium || $runtime == ContentShellOnAndroid) ]
custom/attribute_changed_callback_test/unsupported_on_polyfill: Fail # Issue 18931 (Disabled for Chrome 35 roll)
-custom/document_register_basic_test: RuntimeError # Issue 20813
-fontface_loaded_test: Skip # Issue 21359
form_data_test/functional: Skip # Issue 19726
indexeddb_1_test/functional: Skip # Issue 19512 (timing out)
indexeddb_4_test: Skip # Issue 19726
@@ -256,7 +254,7 @@
shadow_dom_test/supported: Fail
speechrecognition_test/supported: Fail
-[ ($runtime == safari && $builder_tag == mac10_7) || $runtime == safarimobilesim ]
+[ $runtime == safarimobilesim ]
indexeddb_1_test/supported: Fail
element_types_test/supported_template: Fail
xhr_test/json: Fail # Safari doesn't support JSON response type
@@ -269,7 +267,7 @@
input_element_test/supported_datetime-local: Fail
touchevent_test/supported: Fail
-[ $runtime == safari && ($builder_tag == mac10_8 || $builder_tag == mac10_9) ]
+[ $runtime == safari ]
indexeddb_1_test/functional: Skip # Times out. Issue 21433
indexeddb_2_test: RuntimeError # Issue 21433
indexeddb_4_test: RuntimeError # Issue 21433
diff --git a/tests/isolate/browser/issue_12474_child.dart b/tests/isolate/browser/issue_12474_child.dart
new file mode 100644
index 0000000..510fdbb
--- /dev/null
+++ b/tests/isolate/browser/issue_12474_child.dart
@@ -0,0 +1,10 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:isolate';
+import 'package:issue_12474_lib.dart';
+
+void main([args, port]) {
+ testPackageRoot(args);
+}
diff --git a/tests/isolate/browser/issue_12474_test.dart b/tests/isolate/browser/issue_12474_test.dart
new file mode 100644
index 0000000..b2c2caa
--- /dev/null
+++ b/tests/isolate/browser/issue_12474_test.dart
@@ -0,0 +1,24 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Note: the following comment is used by test.dart to additionally compile the
+// other isolate's code.
+// OtherScripts=issue_12474_child.dart
+// OtherScripts=package/issue_12474_lib.dart
+
+import 'dart:isolate';
+
+final SPAWN_PACKAGE_ROOT = Uri.parse(".");
+
+void main([args, port]) {
+ var p = new ReceivePort();
+ Isolate.spawnUri(Uri.parse("issue_12474_child.dart"),
+ [p.sendPort],
+ {},
+ packageRoot: SPAWN_PACKAGE_ROOT);
+ p.listen((msg) {
+ print("Received message");
+ p.close();
+ });
+}
diff --git a/tests/isolate/browser/package/issue_12474_lib.dart b/tests/isolate/browser/package/issue_12474_lib.dart
new file mode 100644
index 0000000..f9beb27
--- /dev/null
+++ b/tests/isolate/browser/package/issue_12474_lib.dart
@@ -0,0 +1,7 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+void testPackageRoot(args) {
+ args[0].send(null);
+}
diff --git a/tests/isolate/deferred_loaded_lib.dart b/tests/isolate/deferred_loaded_lib.dart
new file mode 100644
index 0000000..3b3e097
--- /dev/null
+++ b/tests/isolate/deferred_loaded_lib.dart
@@ -0,0 +1,9 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+class FromChildIsolate {
+ String toString() => 'from child isolate';
+ int get fld => 10;
+}
+
diff --git a/tests/isolate/isolate.status b/tests/isolate/isolate.status
index aee29a9..8f9e66f 100644
--- a/tests/isolate/isolate.status
+++ b/tests/isolate/isolate.status
@@ -52,10 +52,12 @@
spawn_uri_exported_main_test: SkipByDesign # Test uses a ".dart" URI.
issue_21398_parent_isolate_test: SkipByDesign # Test uses a ".dart" URI.
issue_21398_parent_isolate1_test: SkipByDesign # Test uses a ".dart" URI.
+issue_21398_parent_isolate2_test: SkipByDesign # Test uses a ".dart" URI.
message3_test/constList: RuntimeError # Issue 21817
message3_test/constList_identical: RuntimeError # Issue 21817
message3_test/constMap: RuntimeError # Issue 21817
message3_test/constInstance: RuntimeError # Issue 21817
+browser/issue_12474_test: CompileTimeError # Issue 22529
[ $compiler == dart2js && $jscl ]
spawn_uri_test: SkipByDesign # Loading another file is not supported in JS shell
@@ -74,6 +76,7 @@
spawn_uri_exported_main_test: RuntimeError # Issue 16549
issue_21398_parent_isolate_test: RuntimeError # Issue 16549
issue_21398_parent_isolate1_test: RuntimeError # Issue 16549
+issue_21398_parent_isolate2_test: Skip # Not implemented yet
[ $compiler == dart2js && ( $runtime == ff || $runtime == safari || $runtime == drt || $runtime == chrome || $runtime == chromeOnAndroid) ]
isolate_stress_test: Pass, Slow # Issue 10697
@@ -107,7 +110,7 @@
object_leak_test: Fail, OK # Issue 13921 Dom isolates don't support spawnFunction
simple_message_test/none: Fail, OK # Issue 13921 Dom isolates don't support spawnFunction
spawn_uri_missing_from_isolate_test: RuntimeError # Issue 17649
-spawn_uri_missing_test: Skip # Times out.
+spawn_uri_missing_test: SkipSlow # Times out.
isolate_current_test: Fail, OK # Issue 13921 Dom isolates don't support spawnFunction
[ $compiler == dartanalyzer || $compiler == dart2analyzer ]
diff --git a/tests/isolate/issue_21398_parent_isolate1_test.dart b/tests/isolate/issue_21398_parent_isolate1_test.dart
index 1763e4c..1c3aeb8 100644
--- a/tests/isolate/issue_21398_parent_isolate1_test.dart
+++ b/tests/isolate/issue_21398_parent_isolate1_test.dart
@@ -2,6 +2,11 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
+// Note: the following comment is used by test.dart to additionally compile the
+// other isolate's code.
+// OtherScripts=issue_21398_child_isolate1.dart
+// OtherScripts=issue_21398_child_isolate11.dart
+
import 'dart:isolate';
import 'dart:async';
import "package:expect/expect.dart";
diff --git a/tests/isolate/issue_21398_parent_isolate2_test.dart b/tests/isolate/issue_21398_parent_isolate2_test.dart
new file mode 100644
index 0000000..92754fd
--- /dev/null
+++ b/tests/isolate/issue_21398_parent_isolate2_test.dart
@@ -0,0 +1,53 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Note: the following comment is used by test.dart to additionally compile the
+// other isolate's code.
+// OtherScripts=deferred_loaded_lib.dart
+
+import 'dart:isolate';
+import 'dart:async';
+import "package:expect/expect.dart";
+
+import "deferred_loaded_lib.dart" deferred as lib;
+
+// In this test case we send an object created from a deferred library
+// that is loaded in the child isolate but not the parent isolate. The
+// parent isolate does not know about the type of this object and throws
+// an unhandled exception.
+funcChild(args) {
+ var replyPort = args[0];
+ // Deferred load a library, create an object from that library and send
+ // it over to the parent isolate which has not yet loaded that library.
+ lib.loadLibrary().then((_) {
+ replyPort.send(new lib.FromChildIsolate());
+ });
+}
+
+void helperFunction() {
+ var receivePort = new ReceivePort();
+
+ // Spawn an isolate using spawnFunction.
+ Isolate.spawn(funcChild, [receivePort.sendPort]).then(
+ (isolate) {
+ receivePort.listen(
+ (msg) {
+ // We don't expect to receive any valid messages.
+ Expect.fail("We don't expect to receive any valid messages");
+ receivePort.close();
+ },
+ onError: (e) {
+ // We don't expect to receive any error messages, per spec listen
+ // does not receive an error object.
+ Expect.fail("We don't expect to receive any error messages");
+ receivePort.close();
+ }
+ );
+ }
+ );
+}
+
+main() {
+ helperFunction(); /// 01: runtime error
+}
diff --git a/tests/isolate/issue_21398_parent_isolate_test.dart b/tests/isolate/issue_21398_parent_isolate_test.dart
index d342497..fb4b0fb 100644
--- a/tests/isolate/issue_21398_parent_isolate_test.dart
+++ b/tests/isolate/issue_21398_parent_isolate_test.dart
@@ -2,6 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
+// Note: the following comment is used by test.dart to additionally compile the
+// other isolate's code.
+// OtherScripts=issue_21398_child_isolate.dart
+
import 'dart:isolate';
import 'dart:async';
import "package:expect/expect.dart";
diff --git a/tests/language/and_operation_on_non_integer_operand_test.dart b/tests/language/and_operation_on_non_integer_operand_test.dart
new file mode 100644
index 0000000..9d7b067
--- /dev/null
+++ b/tests/language/and_operation_on_non_integer_operand_test.dart
@@ -0,0 +1,20 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Regression test for dart2js that used to miscompile boolean add operations
+// if one of the operands was an int and the other was not (issue 22427).
+
+import "package:expect/expect.dart";
+
+class NotAnInt {
+ NotAnInt operator&(b) => this;
+}
+
+@AssumeDynamic() @NoInline()
+id(x) => x;
+
+main () {
+ var a = id(new NotAnInt());
+ Expect.equals(a, a & 5 & 2);
+}
diff --git a/tests/language/assert_with_type_test_or_cast_test.dart b/tests/language/assert_with_type_test_or_cast_test.dart
index e00d0d3..f9ec08b 100644
--- a/tests/language/assert_with_type_test_or_cast_test.dart
+++ b/tests/language/assert_with_type_test_or_cast_test.dart
@@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
// Issue 3741: generic type tests and casts fail in assertion statements
-// when run in production mode.
+// when run in production mode.
//
// The cause was incomplete generic type skipping, so each of the assert
// statements below would fail.
@@ -13,16 +13,16 @@
main() {
var names = new List<int>();
-
+
// Generic type test.
assert(names is List<int>);
-
+
// Negated generic type test.
assert(names is !List<String>);
-
+
// Generic type cast.
assert((names as List<num>).length == 0);
-
+
// Generic type test inside expression.
assert((names is List<int>));
}
diff --git a/tests/language/async_rethrow_test.dart b/tests/language/async_rethrow_test.dart
new file mode 100644
index 0000000..0712005
--- /dev/null
+++ b/tests/language/async_rethrow_test.dart
@@ -0,0 +1,44 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "dart:async";
+import "package:expect/expect.dart";
+
+const String exceptionString = "exceptionalString";
+
+throwString() async {
+ try {
+ throw exceptionString;
+ } catch (e) {
+ await 1;
+ throw e;
+ }
+}
+
+rethrowString() async {
+ try {
+ throw exceptionString;
+ } catch (e) {
+ await 1;
+ rethrow;
+ }
+}
+
+testThrow() {
+ Future f = throwString();
+ f.then((v) { Expect.fail("Exception not thrown"); },
+ onError: (e) { Expect.equals(exceptionString, e);});
+}
+
+
+testRethrow() {
+ Future f = rethrowString();
+ f.then((v) { Expect.fail("Exception not thrown"); },
+ onError: (e) { Expect.equals(exceptionString, e);});
+}
+
+main() {
+ testThrow();
+ testRethrow();
+}
\ No newline at end of file
diff --git a/tests/language/asyncstar_throw_in_catch_test.dart b/tests/language/asyncstar_throw_in_catch_test.dart
index a6f6a33..37eb183 100644
--- a/tests/language/asyncstar_throw_in_catch_test.dart
+++ b/tests/language/asyncstar_throw_in_catch_test.dart
@@ -9,6 +9,7 @@
class Tracer {
final String expected;
final String name;
+ String _trace = "";
int counter = 0;
Tracer(this.expected, [this.name]);
@@ -17,12 +18,12 @@
if (name != null) {
print("Tracing $name: $msg");
}
- Expect.equals(expected[counter], msg);
+ _trace += msg;
counter++;
}
void done() {
- Expect.equals(expected.length, counter, "Received too few traces");
+ Expect.equals(expected, _trace);
}
}
@@ -33,6 +34,55 @@
tracer.trace("b");
throw "Error";
} catch (e) {
+ Expect.equals("Error", e);
+ tracer.trace("c");
+ yield 1;
+ tracer.trace("d");
+ yield 2;
+ tracer.trace("e");
+ yield 3;
+ tracer.trace("f");
+ } finally {
+ tracer.trace("f");
+ }
+ tracer.trace("g");
+}
+
+foo2(Tracer tracer) async* {
+ try {
+ tracer.trace("a");
+ throw "Error";
+ } catch (error) {
+ Expect.equals("Error", error);
+ tracer.trace("b");
+ rethrow;
+ } finally {
+ tracer.trace("c");
+ }
+}
+
+foo3(Tracer tracer) async* {
+ try {
+ tracer.trace("a");
+ throw "Error";
+ } catch (error) {
+ Expect.equals("Error", error);
+ tracer.trace("b");
+ rethrow;
+ } finally {
+ tracer.trace("c");
+ yield 1;
+ }
+}
+
+foo4(Tracer tracer) async* {
+ try {
+ tracer.trace("a");
+ await new Future.value(3);
+ tracer.trace("b");
+ throw "Error";
+ } catch (e) {
+ Expect.equals("Error", e);
tracer.trace("c");
yield 1;
tracer.trace("d");
@@ -45,18 +95,34 @@
tracer.trace("g");
}
-test() async {
- Tracer tracer;
-
- Completer foo1Done = new Completer();
- tracer = new Tracer("abcdf");
+runTest(test, expectedTrace, expectedError, shouldCancel) {
+ Tracer tracer = new Tracer(expectedTrace, expectedTrace);
+ Completer done = new Completer();
var subscription;
- subscription = foo1(tracer).listen((event) async {
- await subscription.cancel();
- tracer.done();
- foo1Done.complete(null);
+ subscription = test(tracer).listen((event) async {
+ tracer.trace("Y");
+ if (shouldCancel) {
+ await subscription.cancel();
+ tracer.trace("C");
+ done.complete(null);
+ }
+ }, onError: (error) {
+ Expect.equals(expectedError, error);
+ tracer.trace("X");
+ }, onDone: () {
+ tracer.done();
+ done.complete(null);
});
- await foo1Done.future;
+ return done.future.then((_) => tracer.done());
+}
+
+test() async {
+ // TODO(sigurdm): These tests are too dependent on scheduling, and buffering
+ // behavior.
+ await runTest(foo1, "abcdYefC", null, true);
+ await runTest(foo2, "abcX", "Error", false);
+ await runTest(foo3, "abcYX", "Error", false);
+ await runTest(foo4, "abcdYeYfX", "Error2", false);
}
diff --git a/tests/language/compile_time_constant12_test.dart b/tests/language/compile_time_constant12_test.dart
index 60a2533..0acf8b0 100644
--- a/tests/language/compile_time_constant12_test.dart
+++ b/tests/language/compile_time_constant12_test.dart
@@ -4,10 +4,12 @@
const String s = "foo";
const int i = s.length;
+const int l = "foo".length + 1;
use(x) => x;
main() {
use(s);
use(i);
+ use(l);
}
diff --git a/tests/language/custom_await_stack_trace_test.dart b/tests/language/custom_await_stack_trace_test.dart
new file mode 100644
index 0000000..cff9181
--- /dev/null
+++ b/tests/language/custom_await_stack_trace_test.dart
@@ -0,0 +1,29 @@
+import "dart:async";
+import "package:expect/expect.dart";
+
+class Blah extends StackTrace {
+ Blah(this._trace);
+
+ toString() {
+ return "Blah " + _trace.toString();
+ }
+
+ var _trace;
+}
+
+foo() {
+ var x = "\nBloop\nBleep\n";
+ return new Future.error(42, new Blah(x));
+}
+
+main() async {
+ try {
+ var x = await foo();
+ Expect.fail("Should not reach here.");
+ } on int catch (e, s) {
+ Expect.equals(42, e);
+ Expect.equals("Blah \nBloop\nBleep\n", s.toString());
+ return;
+ }
+ Expect.fail("Unreachable.");
+}
diff --git a/tests/language/enum_is_keyword_test.dart b/tests/language/enum_is_keyword_test.dart
new file mode 100644
index 0000000..2d24d94
--- /dev/null
+++ b/tests/language/enum_is_keyword_test.dart
@@ -0,0 +1,10 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Test that `enum` is considered a keyword and therefore invalid as the name of
+// declarations.
+
+main() {
+ var enum; /// 01: compile-time error
+}
diff --git a/tests/language/error_stacktrace_test.dart b/tests/language/error_stacktrace_test.dart
index 9064dc0..90eb3f3 100644
--- a/tests/language/error_stacktrace_test.dart
+++ b/tests/language/error_stacktrace_test.dart
@@ -55,7 +55,6 @@
} on ArgumentError catch (e, s) {
i = 200;
Expect.isNotNull(e.stackTrace, "Errors need a stackTrace on throw");
- Expect.isFalse(identical(e.stackTrace, s));
Expect.equals(e.stackTrace.toString(), s.toString());
}
return i;
diff --git a/tests/language/function_type3_test.dart b/tests/language/function_type3_test.dart
new file mode 100644
index 0000000..6c10c9f
--- /dev/null
+++ b/tests/language/function_type3_test.dart
@@ -0,0 +1,28 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "package:expect/expect.dart";
+
+class A<T> {
+ @NoInline()
+ A();
+
+ @NoInline()
+ foo() => new B<T>();
+}
+
+class B<T> {
+ T bar() => null;
+}
+
+typedef F();
+typedef F2(x);
+
+// Dart2js realized that the generic type for A was not needed, but then used
+// it nevertheless when it constructed the closure.
+main() {
+ var f = new A<int>().foo().bar;
+ Expect.isTrue(f is F);
+ Expect.isFalse(f is F2);
+}
diff --git a/tests/language/language.status b/tests/language/language.status
index 71c570c..d306d89 100644
--- a/tests/language/language.status
+++ b/tests/language/language.status
@@ -44,7 +44,7 @@
cyclic_type2_test: Fail, OK
least_upper_bound_expansive_test/*: Fail, OK
-compile_time_constant12_test: Fail # Issue 21000
+
async_await_syntax_test/a09a: CompileTimeError # Issue 21404
async_await_syntax_test/a10a: CompileTimeError # Issue 21404
async_await_syntax_test/b09a: CompileTimeError # Issue 21404
@@ -56,7 +56,6 @@
[ $compiler == none || ($compiler == dart2dart && $builder_tag != new_backend) ]
async_throw_in_catch_test: Crash # Issue 22445, 22446
-compile_time_constant_c_test/01: Fail # Issue 21000
asyncstar_throw_in_catch_test: CompileTimeError # Issue 21404
async_await_syntax_test/a03a: CompileTimeError # Issue 21404
async_await_syntax_test/a03b: CompileTimeError # Issue 21404
@@ -138,13 +137,13 @@
[ $compiler == none && $runtime == vm && $arch == mips && $mode == debug ]
stack_overflow_test: Skip # Crashes. Issue 17440.
stack_overflow_stacktrace_test: Skip # Crashes. Issue 17440.
-large_class_declaration_test: Skip # Times out. Issue 20352
+large_class_declaration_test: SkipSlow # Times out. Issue 20352
[ $compiler == none && ($runtime == dartium || $runtime == drt || $runtime == ContentShellOnAndroid) && $mode == debug ]
-large_class_declaration_test: Skip # Times out. Issue 20352
+large_class_declaration_test: SkipSlow # Times out. Issue 20352
[ $compiler == none && $runtime == ContentShellOnAndroid ]
-gc_test: Skip # Times out flakily. Issue 20956
+gc_test: SkipSlow # Times out flakily. Issue 20956
[ $compiler == none && $runtime == vm && ( $arch == simarm || $arch == arm || $arch == simarm64 || $arch == arm64 || $arch == simmips || $arch == mips) ]
vm/load_to_load_unaligned_forwarding_vm_test: Pass, Crash # Unaligned offset. Issue 22151
diff --git a/tests/language/language_analyzer.status b/tests/language/language_analyzer.status
index 67fe963..d845652 100644
--- a/tests/language/language_analyzer.status
+++ b/tests/language/language_analyzer.status
@@ -8,8 +8,6 @@
async_return_types_test/nestedFuture: MissingStaticWarning # Issue 22410
await_backwards_compatibility_test/none: CompileTimeError # Issue 22052
await_test: CompileTimeError # Issue 22052
-asyncstar_yield_test: StaticWarning # Issue 22411
-sync_generator1_test/01: MissingStaticWarning # Issue 22412
sync_generator2_test/01: MissingCompileTimeError # Issue 22252
sync_generator2_test/02: MissingCompileTimeError # Issue 22252
@@ -30,7 +28,6 @@
async_await_syntax_test/a10a: MissingStaticWarning
async_await_syntax_test/b10a: MissingStaticWarning
async_await_syntax_test/c10a: MissingStaticWarning
-async_await_syntax_test/d08b: MissingStaticWarning # Issue 22412
async_await_syntax_test/d10a: MissingStaticWarning
# Runtime negative test. No static errors or warnings.
diff --git a/tests/language/language_analyzer2.status b/tests/language/language_analyzer2.status
index 9b07cd8..683ef88 100644
--- a/tests/language/language_analyzer2.status
+++ b/tests/language/language_analyzer2.status
@@ -13,9 +13,6 @@
enum_syntax_test/05: Fail # 21649
enum_syntax_test/06: Fail # 21649
-compile_time_constant_c_test/01: Fail # Issue 21000
-compile_time_constant12_test: Fail # Issue 21000
-
# Test issue 12694 (was analyzer issue), (1) when "abstract" is import prefix using it as type is warning; (2) currently analyzer resolves prefix as field (don't ask)
built_in_identifier_prefix_test: CompileTimeError # Issue 12694
diff --git a/tests/language/language_dart2js.status b/tests/language/language_dart2js.status
index 8048046..c68c922 100644
--- a/tests/language/language_dart2js.status
+++ b/tests/language/language_dart2js.status
@@ -191,18 +191,14 @@
[ $compiler == dart2dart && $builder_tag == new_backend ]
asyncstar_throw_in_catch_test: CompileTimeError # Issue 21404
-await_for_test: RuntimeError # Issue 22051
-await_regression_test: RuntimeError # Issue 22051
-async_await_syntax_test/a06a: RuntimeError # Issue 22051
-async_await_syntax_test/b06a: RuntimeError # Issue 22051
-async_await_syntax_test/c06a: RuntimeError # Issue 22051
-async_await_syntax_test/d06a: RuntimeError # Issue 22051
-async_control_structures_test: RuntimeError # Issue 22051
-async_test/none: RuntimeError # Issue 22051
-async_test/type-mismatch1: RuntimeError # Issue 22051
-async_test/type-mismatch2: RuntimeError # Issue 22051
-async_test/type-mismatch3: RuntimeError # Issue 22051
-async_test/type-mismatch4: RuntimeError # Issue 22051
+async_await_syntax_test/a03a: CompileTimeError # Issue 21404
+async_await_syntax_test/a03b: CompileTimeError # Issue 21404
+async_await_syntax_test/a11d: CompileTimeError # Issue 21404
+async_await_syntax_test/b03a: CompileTimeError # Issue 21404
+async_await_syntax_test/b11d: CompileTimeError # Issue 21404
+sync_generator3_test/test2: RuntimeError # Issue 21404
+async_await_syntax_test/c03a: CompileTimeError # Issue 21404
+async_await_syntax_test/d03a: CompileTimeError # Issue 21404
[ $compiler == dart2dart && $builder_tag == new_backend && $minified == true ]
# This test fails in minified, because the type-argument is
diff --git a/tests/language/propagate_past_constant_test.dart b/tests/language/propagate_past_constant_test.dart
new file mode 100644
index 0000000..03858b4
--- /dev/null
+++ b/tests/language/propagate_past_constant_test.dart
@@ -0,0 +1,20 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:expect/expect.dart';
+
+foo(x) => x;
+
+check(y) {
+ Expect.equals('foo', y);
+}
+
+main() {
+ var x = foo('foo');
+ var y = foo(x);
+ x = 'constant';
+ check(y); // 'y' should not propagate here unless reference to 'x' is rewritten
+ foo(x);
+ foo(x);
+}
diff --git a/tests/language/vm/optimized_testsmi_test.dart b/tests/language/vm/optimized_testsmi_test.dart
index d538f20..c5ac9e2 100644
--- a/tests/language/vm/optimized_testsmi_test.dart
+++ b/tests/language/vm/optimized_testsmi_test.dart
@@ -7,8 +7,7 @@
import "package:expect/expect.dart";
-test(bool b) {
- var a = 0;
+test1(a, bool b) {
if (b) {
a++;
} else {
@@ -20,11 +19,38 @@
return "odd";
}
+test2(a, bool b) {
+ if (b) {
+ a++;
+ } else {
+ a += 2;
+ }
+ if (a & 1 == 1) {
+ return "odd";
+ }
+ return "even";
+}
+
+test3(a, bool b) {
+ return test1(0, b);
+}
+
+test4(a, bool b) {
+ return test2(0, b);
+}
+
+run(test) {
+ Expect.equals("odd", test(0, true));
+ Expect.equals("even", test(0, false));
+ for (var i=0; i<20; i++) test(0, false);
+ Expect.equals("odd", test(0, true));
+ Expect.equals("even", test(0, false));
+}
+
main() {
- Expect.equals("odd", test(true));
- Expect.equals("even", test(false));
- for (var i=0; i<20; i++) test(false);
- Expect.equals("odd", test(true));
- Expect.equals("even", test(false));
+ run(test1);
+ run(test2);
+ run(test3);
+ run(test4);
}
diff --git a/tests/language/vm/regress_22480_test.dart b/tests/language/vm/regress_22480_test.dart
new file mode 100644
index 0000000..3cbe98a
--- /dev/null
+++ b/tests/language/vm/regress_22480_test.dart
@@ -0,0 +1,20 @@
+// 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.
+// VMOptions=--optimization_counter_threshold=10
+
+import 'package:expect/expect.dart';
+
+test(j) {
+ var result = true;
+ j++;
+ for (var i = 0; i < 100; i++) {
+ result = (i < 50 || j < (1 << 32)) && result;
+ }
+ return result;
+}
+
+main() {
+ Expect.isTrue(test(30));
+}
+
diff --git a/tests/lib/analyzer/analyze_library.status b/tests/lib/analyzer/analyze_library.status
index e48684e..652386e 100644
--- a/tests/lib/analyzer/analyze_library.status
+++ b/tests/lib/analyzer/analyze_library.status
@@ -16,15 +16,8 @@
lib/web_gl/dart2js/web_gl_dart2js: CompileTimeError # Issue 16522
lib/web_sql/dart2js/web_sql_dart2js: CompileTimeError # Issue 16522
-# The async_await compiler isn't part of the repo so it shouldn't be tested by
-# repo tests.
-lib/_internal/pub_generated/bin/async_compile: Skip
-
-# Pub is starting to use the new async syntax, which isn't supported on the
-# analyzer bots yet.
-lib/_internal/pub/*: Pass, CompileTimeError
-
[ $compiler == dart2analyzer ]
+lib/async/async: CompileTimeError # Issue 22415
lib/web_gl/dartium/web_gl_dartium: CompileTimeError # Issue 21647
lib/web_sql/dartium/web_sql_dartium: CompileTimeError # Issue 21647
lib/html/dartium/html_dartium: CompileTimeError # Issue 21647
diff --git a/tests/lib/async/stream_controller_test.dart b/tests/lib/async/stream_controller_test.dart
index 685222d..e4ddecf 100644
--- a/tests/lib/async/stream_controller_test.dart
+++ b/tests/lib/async/stream_controller_test.dart
@@ -673,6 +673,52 @@
c.close();
}
+void testSyncControllerNotReentrant() {
+ Stream emptyStream = (new StreamController.broadcast()..close()).stream;
+ asyncStart();
+ for (int listenerCount = 1; listenerCount <= 2; listenerCount++) {
+ StreamController c = new StreamController.broadcast(sync: true);
+ for (int i = 0; i < listenerCount; i++) {
+ asyncStart();
+ asyncStart();
+ c.stream.listen((v) {
+ Expect.equals(42, v);
+ Expect.throws(() {
+ c.add(37);
+ });
+ Expect.throws(() {
+ c.addError(37);
+ });
+ Expect.throws(() {
+ c.addStream(emptyStream);
+ });
+ Expect.throws(() {
+ c.close();
+ });
+ asyncEnd();
+ }, onError: (e, s) {
+ Expect.equals(87, e);
+ Expect.throws(() {
+ c.add(37);
+ });
+ Expect.throws(() {
+ c.addError(37);
+ });
+ Expect.throws(() {
+ c.addStream(emptyStream);
+ });
+ Expect.throws(() {
+ c.close();
+ });
+ asyncEnd();
+ });
+ }
+ c.add(42);
+ c.addError(87);
+ }
+ asyncEnd();
+}
+
main() {
asyncStart();
testMultiController();
@@ -691,5 +737,6 @@
testAsBroadcastListenAfterClose();
testAsBroadcastListenAfterClosePaused();
testEventInListen();
+ testSyncControllerNotReentrant();
asyncEnd();
}
diff --git a/tests/lib/async/stream_transformation_broadcast_test.dart b/tests/lib/async/stream_transformation_broadcast_test.dart
index 11928fe..ce9c882 100644
--- a/tests/lib/async/stream_transformation_broadcast_test.dart
+++ b/tests/lib/async/stream_transformation_broadcast_test.dart
@@ -10,6 +10,16 @@
import 'package:unittest/unittest.dart';
import "package:expect/expect.dart";
+main() {
+ testStream("singlesub", () => new StreamController(), (c) => c.stream);
+ testStream("broadcast", () => new StreamController.broadcast(),
+ (c) => c.stream);
+ testStream("asBroadcast", () => new StreamController(),
+ (c) => c.stream.asBroadcastStream());
+ testStream("broadcast.asBroadcast", () => new StreamController.broadcast(),
+ (c) => c.stream.asBroadcastStream());
+}
+
void testStream(String name,
StreamController create(),
Stream getStream(controller)) {
@@ -171,14 +181,182 @@
c.add(42);
c.close();
});
-}
-main() {
- testStream("singlesub", () => new StreamController(), (c) => c.stream);
- testStream("broadcast", () => new StreamController.broadcast(),
- (c) => c.stream);
- testStream("asBroadcast", () => new StreamController(),
- (c) => c.stream.asBroadcastStream());
- testStream("broadcast.asBroadcast", () => new StreamController.broadcast(),
- (c) => c.stream.asBroadcastStream());
+ // The following tests are only on broadcast streams, they require listening
+ // more than once.
+ if (name.startsWith("singlesub")) return;
+
+ test("$name-skip-multilisten", () {
+ if (name.startsWith("singlesub") ||
+ name.startsWith("asBroadcast")) return;
+ var c = create();
+ var s = getStream(c);
+ Stream newStream = s.skip(5);
+ // Listen immediately, to ensure that an asBroadcast stream is started.
+ var sub = newStream.listen((_){});
+ int i = 0;
+ var expect1 = 11;
+ var expect2 = 21;
+ var handler2 = expectAsync((v) {
+ expect(v, expect2);
+ expect2++;
+ }, count: 5);
+ var handler1 = expectAsync((v) {
+ expect(v, expect1);
+ expect1++;
+ }, count: 15);
+ var loop;
+ loop = expectAsync(() {
+ i++;
+ c.add(i);
+ if (i == 5) {
+ scheduleMicrotask(() {
+ newStream.listen(handler1);
+ });
+ }
+ if (i == 15) {
+ scheduleMicrotask(() {
+ newStream.listen(handler2);
+ });
+ }
+ if (i < 25) {
+ scheduleMicrotask(loop);
+ } else {
+ sub.cancel();
+ c.close();
+ }
+ }, count: 25);
+ scheduleMicrotask(loop);
+ });
+
+ test("$name-take-multilisten", () {
+ var c = create();
+ var s = getStream(c);
+ Stream newStream = s.take(10);
+ // Listen immediately, to ensure that an asBroadcast stream is started.
+ var sub = newStream.listen((_){});
+ int i = 0;
+ var expect1 = 6;
+ var expect2 = 11;
+ var handler2 = expectAsync((v) {
+ expect(v, expect2);
+ expect(v <= 20, isTrue);
+ expect2++;
+ }, count: 10);
+ var handler1 = expectAsync((v) {
+ expect(v, expect1);
+ expect(v <= 15, isTrue);
+ expect1++;
+ }, count: 10);
+ var loop;
+ loop = expectAsync(() {
+ i++;
+ c.add(i);
+ if (i == 5) {
+ scheduleMicrotask(() {
+ newStream.listen(handler1);
+ });
+ }
+ if (i == 10) {
+ scheduleMicrotask(() {
+ newStream.listen(handler2);
+ });
+ }
+ if (i < 25) {
+ scheduleMicrotask(loop);
+ } else {
+ sub.cancel();
+ c.close();
+ }
+ }, count: 25);
+ scheduleMicrotask(loop);
+ });
+
+ test("$name-skipWhile-multilisten", () {
+ if (name.startsWith("singlesub") ||
+ name.startsWith("asBroadcast")) return;
+ var c = create();
+ var s = getStream(c);
+ Stream newStream = s.skipWhile((x) => (x % 10) != 1);
+ // Listen immediately, to ensure that an asBroadcast stream is started.
+ var sub = newStream.listen((_){});
+ int i = 0;
+ var expect1 = 11;
+ var expect2 = 21;
+ var handler2 = expectAsync((v) {
+ expect(v, expect2);
+ expect2++;
+ }, count: 5);
+ var handler1 = expectAsync((v) {
+ expect(v, expect1);
+ expect1++;
+ }, count: 15);
+ var loop;
+ loop = expectAsync(() {
+ i++;
+ c.add(i);
+ if (i == 5) {
+ scheduleMicrotask(() {
+ newStream.listen(handler1);
+ });
+ }
+ if (i == 15) {
+ scheduleMicrotask(() {
+ newStream.listen(handler2);
+ });
+ }
+ if (i < 25) {
+ scheduleMicrotask(loop);
+ } else {
+ sub.cancel();
+ c.close();
+ }
+ }, count: 25);
+ scheduleMicrotask(loop);
+ });
+
+ test("$name-takeWhile-multilisten", () {
+ var c = create();
+ var s = getStream(c);
+ Stream newStream = s.takeWhile((x) => (x % 10) != 5);
+ // Listen immediately, to ensure that an asBroadcast stream is started.
+ var sub = newStream.listen((_){});
+ int i = 0;
+ // Non-overlapping ranges means the test must not remember its first
+ // failure.
+ var expect1 = 6;
+ var expect2 = 16;
+ var handler2 = expectAsync((v) {
+ expect(v, expect2);
+ expect(v <= 25, isTrue);
+ expect2++;
+ }, count: 9);
+ var handler1 = expectAsync((v) {
+ expect(v, expect1);
+ expect(v <= 15, isTrue);
+ expect1++;
+ }, count: 9);
+ var loop;
+ loop = expectAsync(() {
+ i++;
+ c.add(i);
+ if (i == 5) {
+ scheduleMicrotask(() {
+ newStream.listen(handler1);
+ });
+ }
+ if (i == 15) {
+ scheduleMicrotask(() {
+ newStream.listen(handler2);
+ });
+ }
+ if (i < 25) {
+ scheduleMicrotask(loop);
+ } else {
+ sub.cancel();
+ c.close();
+ }
+ }, count: 25);
+ scheduleMicrotask(loop);
+ });
}
diff --git a/tests/lib/lib.status b/tests/lib/lib.status
index c23efbe..de56b1c 100644
--- a/tests/lib/lib.status
+++ b/tests/lib/lib.status
@@ -18,6 +18,7 @@
mirrors/abstract_class_test: RuntimeError # Issue 12826
mirrors/class_declarations_test/none: RuntimeError # Issue 13440
+mirrors/class_mirror_location_test: RuntimeError # Issue 6490
mirrors/constructor_kinds_test: RuntimeError # Issue 13799
mirrors/constructor_private_name_test: CompileTimeError # Issue 13597
mirrors/fake_function_with_call_test: RuntimeError # Issue 11612
@@ -49,13 +50,14 @@
mirrors/library_declarations_test/none: RuntimeError # Issue 13439, Issue 13733
mirrors/library_exports_shown_test: RuntimeError # Issue 6490
mirrors/library_exports_hidden_test: RuntimeError # Issue 6490
+mirrors/library_imports_deferred_test: RuntimeError # Issue 6490
mirrors/library_imports_metadata_test: RuntimeError # Issue 6490
mirrors/library_imports_bad_metadata_test/none: RuntimeError # Issue 6490
mirrors/library_imports_shown_test: RuntimeError # Issue 6490
mirrors/library_imports_hidden_test: RuntimeError # Issue 6490
mirrors/library_imports_prefixed_test: RuntimeError # Issue 6490
mirrors/library_imports_prefixed_show_hide_test: RuntimeError # Issue 6490
-mirrors/library_uri_io_test: Skip # Not intended for dart2js as it uses dart:io.
+mirrors/library_uri_io_test: SkipByDesign # Uses dart:io.
mirrors/local_function_is_static_test: RuntimeError # Issue 6335
mirrors/lru_test: Skip # dart2js_native/lru_test is used instead
mirrors/metadata_allowed_values_test/01: MissingCompileTimeError # Issue 14548
@@ -74,6 +76,7 @@
mirrors/mirrors_nsm_test/dart2js: RuntimeError # Issue 19353
mirrors/mixin_test: RuntimeError # Issue 12464
mirrors/mixin_application_test: RuntimeError # Issue 12464
+mirrors/other_declarations_location_test: CompileTimeError # Issue 10905
mirrors/parameter_test/none: RuntimeError # Issue 6490
mirrors/parameter_of_mixin_app_constructor_test: RuntimeError # Issue 6490
mirrors/private_symbol_test: CompileTimeError # Issue 13597
@@ -210,11 +213,11 @@
mirrors/mirrors_reader_test: Timeout, Slow, RuntimeError # Issue 16589
[ $runtime == chrome || $runtime == ff || $runtime == ContentShellOnAndroid ]
-convert/streamed_conversion_utf8_encode_test: Skip # Times out. Issue 22050
-convert/streamed_conversion_json_utf8_encode_test: Skip # Times out. Issue 22050
-convert/streamed_conversion_json_utf8_decode_test: Skip # Times out. Issue 22050
-async/slow_consumer2_test: Skip # Times out. Issue 22050
-async/stream_timeout_test: Skip # Times out. Issue 22050
+convert/streamed_conversion_utf8_encode_test: SkipSlow # Times out. Issue 22050
+convert/streamed_conversion_json_utf8_encode_test: SkipSlow # Times out. Issue 22050
+convert/streamed_conversion_json_utf8_decode_test: SkipSlow # Times out. Issue 22050
+async/slow_consumer2_test: SkipSlow # Times out. Issue 22050
+async/stream_timeout_test: SkipSlow # Times out. Issue 22050
[ $compiler == dart2js ]
typed_data/typed_data_hierarchy_int64_test: RuntimeError # Issue 10275
@@ -238,7 +241,7 @@
mirrors/generic_local_function_test: RuntimeError # Issue 14913
mirrors/symbol_validation_test: RuntimeError # Issue 13596
-mirrors/mirrors_used*: Skip # Invalid tests.
+mirrors/mirrors_used*: SkipByDesign # Invalid tests. MirrorsUsed does not have a specification, and dart:mirrors is not required to hide declarations that are not covered by any MirrorsUsed annotation.
[ $compiler == none && ( $runtime == drt || $runtime == dartium || $runtime == ContentShellOnAndroid) ]
async/schedule_microtask6_test: Fail # Issue 10910
@@ -247,10 +250,10 @@
async/stream_periodic3_test: Fail, Pass # Issue 15487
async/timer_isolate_test: Fail, Pass # Issue 15487. Issue 13921: spawnFunction is not allowed on Dartium's DOM thread.
async/timer_isActive_test: Fail, Pass # Issue 22352
-mirrors/immutable_collections_test: Skip # Dartium debug uses -O0, so this will just timeout and waste bot cycles.
-mirrors/mirrors_reader_test: Skip # Dartium debug uses -O0, so this will just timeout and waste bot cycles.
-mirrors/library_uri_io_test: Skip # Not intended for drt as it uses dart:io.
-mirrors/local_isolate_test: Skip # Issue 12188
+mirrors/immutable_collections_test: SkipSlow # Dartium debug uses -O0, so this will just timeout and waste bot cycles.
+mirrors/mirrors_reader_test: SkipSlow # Dartium debug uses -O0, so this will just timeout and waste bot cycles.
+mirrors/library_uri_io_test: SkipByDesign # Uses dart:io.
+mirrors/local_isolate_test: RuntimeError # Issue 12188
[ $compiler == none && $runtime == drt && $system == windows ]
async/multiple_timer_test: Fail, Pass # See Issue 10982
@@ -262,15 +265,15 @@
[$compiler == none && $runtime == ContentShellOnAndroid ]
async/stream_timeout_test: RuntimeError, Pass # Issue 19127
-async/slow_consumer3_test: Skip # Times out flakily. Issue 20956
-async/slow_consumer2_test: Skip # Times out flakily. Issue 20956
-convert/streamed_conversion_utf8_encode_test: Skip # Times out or passes. Issue 19127
-convert/streamed_conversion_utf8_decode_test: Skip # Times out or passes. Issue 19127
-mirrors/lazy_static_test: Skip # Times out. Issue 19127
-mirrors/mirrors_reader_test: Skip # Times out. Issue 19127
+async/slow_consumer3_test: SkipSlow # Times out flakily. Issue 20956
+async/slow_consumer2_test: SkipSlow # Times out flakily. Issue 20956
+convert/streamed_conversion_utf8_encode_test: SkipSlow # Times out or passes. Issue 19127
+convert/streamed_conversion_utf8_decode_test: SkipSlow # Times out or passes. Issue 19127
+mirrors/lazy_static_test: SkipSlow # Times out. Issue 19127
+mirrors/mirrors_reader_test: SkipSlow # Times out. Issue 19127
[ $compiler == dart2js && $runtime == safarimobilesim ]
-mirrors/mirrors_reader_test: Skip # Times out. Issue 20806.
+mirrors/mirrors_reader_test: SkipSlow # Times out. Issue 20806.
[ $compiler == dart2dart ]
# Deferred loading is not supported by dart2dart.
@@ -328,5 +331,5 @@
convert/streamed_conversion_json_utf8_decode_test: Skip # Verification not yet implemented.
[ $runtime == vm && $mode == debug && $builder_tag == asan ]
-mirrors/immutable_collections_test: Skip # Timeout.
+mirrors/immutable_collections_test: SkipSlow # Timeout.
convert/streamed_conversion_json_utf8_decode_test: Skip # Timeout.
diff --git a/tests/lib/mirrors/class_mirror_location_other.dart b/tests/lib/mirrors/class_mirror_location_other.dart
new file mode 100644
index 0000000..eb94d21
--- /dev/null
+++ b/tests/lib/mirrors/class_mirror_location_other.dart
@@ -0,0 +1,11 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+part of test.class_location;
+
+class ClassInOtherFile {}
+
+ class SpaceIndentedInOtherFile {}
+
+ class TabIndentedInOtherFile {}
diff --git a/tests/lib/mirrors/class_mirror_location_test.dart b/tests/lib/mirrors/class_mirror_location_test.dart
new file mode 100644
index 0000000..c6aa596
--- /dev/null
+++ b/tests/lib/mirrors/class_mirror_location_test.dart
@@ -0,0 +1,68 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library test.class_location;
+
+import "dart:mirrors";
+import "package:expect/expect.dart";
+
+part 'class_mirror_location_other.dart';
+
+class ClassInMainFile {}
+ class SpaceIndentedInMainFile {}
+ class TabIndentedInMainFile {}
+
+abstract class AbstractClass {}
+typedef bool Predicate(num n);
+
+class M {}
+class S {}
+class MA extends S with M {}
+class MA2 = S with M;
+
+const metadata = 'metadata';
+
+@metadata
+class WithMetadata {}
+
+enum Enum { RED, GREEN, BLUE }
+
+@metadata
+enum AnnotatedEnum { SALT, PEPPER }
+
+// We only check for a suffix of the uri because the test might be run from
+// any number of absolute paths.
+expectLocation(DeclarationMirror mirror, String uriSuffix, int line, int column) {
+ Uri uri = mirror.location.sourceUri;
+ Expect.isTrue(uri.toString().endsWith(uriSuffix),
+ "Expected suffix $uriSuffix in $uri");
+ Expect.equals(line, mirror.location.line, "line");
+ Expect.equals(column, mirror.location.column, "column");
+}
+
+main() {
+ String mainSuffix = 'class_mirror_location_test.dart';
+ String otherSuffix = 'class_mirror_location_other.dart';
+
+ // This file.
+ expectLocation(reflectClass(ClassInMainFile), mainSuffix, 12, 1);
+ expectLocation(reflectClass(SpaceIndentedInMainFile), mainSuffix, 13, 3);
+ expectLocation(reflectClass(TabIndentedInMainFile), mainSuffix, 14, 2);
+ expectLocation(reflectClass(AbstractClass), mainSuffix, 16, 1);
+ expectLocation(reflectType(Predicate), mainSuffix, 17, 1);
+ expectLocation(reflectClass(MA), mainSuffix, 21, 1);
+ expectLocation(reflectClass(MA2), mainSuffix, 22, 1);
+ expectLocation(reflectClass(WithMetadata), mainSuffix, 26, 1);
+ expectLocation(reflectClass(Enum), mainSuffix, 29, 1);
+ expectLocation(reflectClass(AnnotatedEnum), mainSuffix, 31, 1);
+
+ // Another part.
+ expectLocation(reflectClass(ClassInOtherFile), otherSuffix, 7, 1);
+ expectLocation(reflectClass(SpaceIndentedInOtherFile), otherSuffix, 9, 3);
+ expectLocation(reflectClass(TabIndentedInOtherFile), otherSuffix, 11, 2);
+
+ // Synthetic classes.
+ Expect.isNull(reflectClass(MA).superclass.location);
+ Expect.isNull((reflect(main) as ClosureMirror).type.location);
+}
diff --git a/tests/lib/mirrors/library_imports_deferred_test.dart b/tests/lib/mirrors/library_imports_deferred_test.dart
new file mode 100644
index 0000000..be0cef9
--- /dev/null
+++ b/tests/lib/mirrors/library_imports_deferred_test.dart
@@ -0,0 +1,44 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library test.library_imports_deferred;
+
+import 'dart:mirrors';
+import 'package:expect/expect.dart';
+import 'stringify.dart';
+
+import 'dart:collection' as eagercollection;
+import 'dart:collection' deferred as lazycollection;
+
+test(MirrorSystem mirrors) {
+ LibraryMirror thisLibrary =
+ mirrors.findLibrary(#test.library_imports_deferred);
+ LibraryMirror collection =
+ mirrors.findLibrary(#dart.collection);
+
+ var importsOfCollection = thisLibrary.libraryDependencies.where(
+ (dep) => dep.targetLibrary == collection).toList();
+ Expect.equals(2, importsOfCollection.length);
+ Expect.notEquals(importsOfCollection[0].isDeferred,
+ importsOfCollection[1].isDeferred); // One deferred, one not.
+
+ // Only collection is defer-imported.
+ LibraryDependencyMirror dep =
+ thisLibrary.libraryDependencies.singleWhere((dep) => dep.isDeferred);
+ Expect.equals(collection, dep.targetLibrary);
+
+ Expect.stringEquals(
+ 'import dart.collection as eagercollection\n'
+ 'import dart.collection deferred as lazycollection\n'
+ ' hide loadLibrary\n'
+ 'import dart.core\n'
+ 'import dart.mirrors\n'
+ 'import expect\n'
+ 'import test.stringify\n',
+ stringifyDependencies(thisLibrary));
+}
+
+main() {
+ test(currentMirrorSystem());
+}
diff --git a/tests/lib/mirrors/library_with_annotated_declaration.dart b/tests/lib/mirrors/library_with_annotated_declaration.dart
new file mode 100644
index 0000000..eeff40d
--- /dev/null
+++ b/tests/lib/mirrors/library_with_annotated_declaration.dart
@@ -0,0 +1,10 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+@metadata
+library library_with_annotated_declaration;
+
+const metadata = 'metadata';
+
+class ClassInLibraryWithAnnotatedDeclaration {}
\ No newline at end of file
diff --git a/tests/lib/mirrors/library_without_declaration.dart b/tests/lib/mirrors/library_without_declaration.dart
new file mode 100644
index 0000000..4f21997
--- /dev/null
+++ b/tests/lib/mirrors/library_without_declaration.dart
@@ -0,0 +1,7 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// NO LIBRARY DECLARATION
+
+class ClassInLibraryWithoutDeclaration {}
\ No newline at end of file
diff --git a/tests/lib/mirrors/method_mirror_location_test.dart b/tests/lib/mirrors/method_mirror_location_test.dart
index 8d154fa..446f313 100644
--- a/tests/lib/mirrors/method_mirror_location_test.dart
+++ b/tests/lib/mirrors/method_mirror_location_test.dart
@@ -33,7 +33,7 @@
method() {}
}
-topLevelInMainFile() {}
+void topLevelInMainFile() {}
spaceIdentedInMainFile() {}
tabIdentedInMainFile() {}
diff --git a/tests/lib/mirrors/mirrors_reader_test.dart b/tests/lib/mirrors/mirrors_reader_test.dart
index e66c5f0..5528701 100644
--- a/tests/lib/mirrors/mirrors_reader_test.dart
+++ b/tests/lib/mirrors/mirrors_reader_test.dart
@@ -33,6 +33,9 @@
bool allowUnsupported(var receiver, String tag, UnsupportedError exception) {
if (mirrorSystemType == '_LocalMirrorSystem') {
// VM mirror system.
+ if (tag.endsWith('location')) {
+ return receiver is ParameterMirror;
+ }
} else if (mirrorSystemType == 'JsMirrorSystem') {
// Dart2js runtime mirror system.
if (tag.endsWith('.metadata')) {
@@ -48,9 +51,6 @@
if (mirrorSystemType == '_LocalMirrorSystem') {
// VM mirror system.
- if (receiver is DeclarationMirror && tag == 'location') {
- return receiver is! MethodMirror;
- }
} else if (mirrorSystemType == 'JsMirrorSystem') {
// Dart2js runtime mirror system.
if (receiver is DeclarationMirror && tag == 'location') {
diff --git a/tests/lib/mirrors/other_declarations_location_test.dart b/tests/lib/mirrors/other_declarations_location_test.dart
new file mode 100644
index 0000000..6a119c3
--- /dev/null
+++ b/tests/lib/mirrors/other_declarations_location_test.dart
@@ -0,0 +1,55 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library test.declarations_location;
+
+import "dart:mirrors";
+import "package:expect/expect.dart";
+import "library_without_declaration.dart";
+import "library_with_annotated_declaration.dart";
+
+const metadata = 'metadata';
+
+class C<S, @metadata T> {
+ var a;
+ final b = 2;
+ static var c;
+ static final d = 4;
+ @metadata var e;
+ List<C> f;
+}
+
+
+// We only check for a suffix of the uri because the test might be run from
+// any number of absolute paths.
+expectLocation(DeclarationMirror mirror, String uriSuffix, int line, int column) {
+ Uri uri = mirror.location.sourceUri;
+ Expect.isTrue(uri.toString().endsWith(uriSuffix),
+ "Expected suffix $uriSuffix in $uri");
+ Expect.equals(line, mirror.location.line, "line");
+ Expect.equals(column, mirror.location.column, "column");
+}
+
+main() {
+ String mainSuffix = 'other_declarations_location_test.dart';
+
+ // Fields.
+ expectLocation(reflectClass(C).declarations[#a], mainSuffix, 15, 7);
+ expectLocation(reflectClass(C).declarations[#b], mainSuffix, 16, 9);
+ expectLocation(reflectClass(C).declarations[#c], mainSuffix, 17, 14);
+ expectLocation(reflectClass(C).declarations[#d], mainSuffix, 18, 16);
+ expectLocation(reflectClass(C).declarations[#e], mainSuffix, 19, 17);
+ expectLocation(reflectClass(C).declarations[#f], mainSuffix, 20, 11);
+
+ // Type variables.
+ expectLocation(reflectClass(C).declarations[#S], mainSuffix, 14, 9);
+ expectLocation(reflectClass(C).declarations[#T], mainSuffix, 14, 12);
+
+ // Libraries.
+ expectLocation(reflectClass(C).owner, mainSuffix, 5, 1);
+ expectLocation(reflectClass(ClassInLibraryWithoutDeclaration).owner,
+ "library_without_declaration.dart", 1, 1);
+ expectLocation(reflectClass(ClassInLibraryWithAnnotatedDeclaration).owner,
+ "library_with_annotated_declaration.dart", 5, 1);
+}
diff --git a/tests/lib/mirrors/stringify.dart b/tests/lib/mirrors/stringify.dart
index 067769a..51298e9 100644
--- a/tests/lib/mirrors/stringify.dart
+++ b/tests/lib/mirrors/stringify.dart
@@ -116,8 +116,15 @@
stringifyDependencies(LibraryMirror l) {
n(s) => s is Symbol ? MirrorSystem.getName(s) : s;
- compareDep(a, b) =>
- n(a.targetLibrary.simpleName).compareTo(n(b.targetLibrary.simpleName));
+ compareDep(a, b) {
+ if (a.targetLibrary == b.targetLibrary) {
+ if ((a.prefix != null) && (b.prefix != null)) {
+ return n(a.prefix).compareTo(n(b.prefix));
+ }
+ return a.prefix == null ? 1 : -1;
+ }
+ return n(a.targetLibrary.simpleName).compareTo(n(b.targetLibrary.simpleName));
+ }
compareCom(a, b) => n(a.identifier).compareTo(n(b.identifier));
compareFirst(a, b) => a[0].compareTo(b[0]);
sortBy(c, p) => new List.from(c)..sort(p);
@@ -127,6 +134,7 @@
if (dep.isImport) buffer.write('import ');
if (dep.isExport) buffer.write('export ');
buffer.write(n(dep.targetLibrary.simpleName));
+ if (dep.isDeferred) buffer.write(' deferred');
if (dep.prefix != null) buffer.write(' as ${n(dep.prefix)}');
buffer.write('\n');
diff --git a/tests/standalone/debugger/debug_lib.dart b/tests/standalone/debugger/debug_lib.dart
index 19540fa..92a0d10 100644
--- a/tests/standalone/debugger/debug_lib.dart
+++ b/tests/standalone/debugger/debug_lib.dart
@@ -338,6 +338,43 @@
}
+// Used to check if local variables are visible.
+class AssertLocalsNotVisibleMatcher extends Command {
+ List<String> locals;
+ int frame_index;
+
+ AssertLocalsNotVisibleMatcher(this.locals, this.frame_index) {
+ template = {"id": 0, "command": "getStackTrace", "params": {"isolateId": 0}};
+ }
+
+ void matchResponse(Debugger debugger) {
+ super.matchResponse(debugger);
+
+ List frames = getJsonValue(debugger.currentMessage, "result:callFrames");
+ assert(frames != null);
+
+ String functionName = frames[frame_index]['functionName'];
+ List localsList = frames[frame_index]['locals'];
+ Map reportedLocals = {};
+ localsList.forEach((local) => reportedLocals[local['name']] = local['value']);
+ for (String key in locals) {
+ if (reportedLocals[key] != null) {
+ debugger.error("Error in $functionName(): local variable $key not "
+ "expected in scope (reported value "
+ "${reportedLocals[key]['text']})");
+ return;
+ }
+ }
+ print("Matched locals $locals");
+ }
+}
+
+
+AssertLocalsNotVisible(List<String> locals, [int frame_index = 0]) {
+ return new AssertLocalsNotVisibleMatcher(locals, frame_index);
+}
+
+
class EventMatcher {
String eventName;
Map params;
diff --git a/tests/standalone/debugger/local_variables_test.dart b/tests/standalone/debugger/local_variables_test.dart
new file mode 100644
index 0000000..b7871d4
--- /dev/null
+++ b/tests/standalone/debugger/local_variables_test.dart
@@ -0,0 +1,77 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// This test forks a second vm process that runs this dart script as
+// a debug target.
+// Run this test with option --wire to see the json messages sent
+// between the processes.
+// Run this test with option --verbose to see the stdout and stderr output
+// of the debug target process.
+
+import "debug_lib.dart";
+
+foo() {
+ var y; // Breakpoint
+ return 123;
+}
+
+test() {
+ if (true) {
+ var temp = 777;
+ }
+ if (true) {
+ var a = foo(); // Breakpoint
+ if (true) {
+ var s = 456;
+ print(s);
+ }
+ }
+}
+
+test_no_init() {
+ if (true) {
+ var temp = 777;
+ }
+ if (true) {
+ var a; // Breakpoint
+ if (true) {
+ var s = 456;
+ print(s);
+ }
+ }
+}
+
+
+main(List<String> arguments) {
+ if (RunScript(testScript, arguments)) return;
+ print("Hello from debuggee");
+ test();
+ test_no_init();
+ print("Hello again");
+}
+
+
+// Expected debugger events and commands.
+var testScript = [
+ MatchFrame(0, "main"), // Top frame in trace is function "main".
+ Step(),
+ MatchFrame(0, "main"), // Should still be in "main".
+ SetBreakpoint(15), // Set breakpoint in function foo.
+ SetBreakpoint(24), // Set breakpoint in function test.
+ SetBreakpoint(37), // Set breakpoint in function test_no_init.
+ Resume(),
+ MatchFrames(["test", "main"]),
+ AssertLocalsNotVisible(["a"]), // Here, a is not in scope yet.
+ Resume(),
+ MatchFrames(["foo", "test", "main"]),
+ AssertLocalsNotVisible(["a"], 1), // In the caller, a is not in scope.
+ Step(),
+ MatchLocals({"y": "null"}), // Expect y initialized to null.
+ Resume(),
+ MatchFrames(["test_no_init", "main"]),
+ AssertLocalsNotVisible(["a"]), // a is not in scope.
+ Step(),
+ MatchLocals({"a": "null"}),
+ Resume()
+];
diff --git a/tests/standalone/io/platform_test.dart b/tests/standalone/io/platform_test.dart
index bf59383..b0036f6 100644
--- a/tests/standalone/io/platform_test.dart
+++ b/tests/standalone/io/platform_test.dart
@@ -66,9 +66,51 @@
});
}
+
+testVersion() {
+ checkValidVersion(String version) {
+ RegExp re = new RegExp(r'(\d+)\.(\d+)\.(\d+)(-dev\.([^\.]*)\.([^\.]*))?');
+ var match = re.firstMatch(version);
+ Expect.isNotNull(match);
+ // Major version.
+ Expect.isTrue(int.parse(match.group(1)) == 1);
+ // Minor version.
+ Expect.isTrue(int.parse(match.group(2)) >= 9);
+ // Patch version.
+ Expect.isTrue(int.parse(match.group(3)) >= 0);
+ // Dev
+ if (match.group(4) != null) {
+ // Dev prerelease minor version
+ Expect.isTrue(int.parse(match.group(5)) >= 0);
+ // Dev prerelease patch version
+ Expect.isTrue(int.parse(match.group(6)) >= 0);
+ }
+ }
+ // Ensure we can match valid versions.
+ checkValidVersion('1.9.0');
+ checkValidVersion('1.9.0-dev.0.0');
+ checkValidVersion('1.9.0-edge');
+ checkValidVersion('1.9.0-edge.r41234');
+ // Test current version.
+ checkValidVersion(Platform.version);
+ // Test some invalid versions.
+ Expect.throws(() => checkValidVersion('1.9'));
+ Expect.throws(() => checkValidVersion('2.0.0'));
+ Expect.throws(() => checkValidVersion('..'));
+ Expect.throws(() => checkValidVersion('1..'));
+ Expect.throws(() => checkValidVersion('1.9.'));
+ Expect.throws(() => checkValidVersion('1.9.0-dev..'));
+ Expect.throws(() => checkValidVersion('1.9.0-dev..0'));
+ Expect.throws(() => checkValidVersion('1.9.0-dev.0.'));
+ Expect.throws(() => checkValidVersion('1.9.0-dev.x.y'));
+ Expect.throws(() => checkValidVersion('x'));
+ Expect.throws(() => checkValidVersion('x.y.z'));
+}
+
main() {
// This tests assumes paths relative to dart main directory
Directory.current = Platform.script.resolve('../../..').toFilePath();
test();
testIsolate();
+ testVersion();
}
diff --git a/tests/standalone/io/socket_source_address_test.dart b/tests/standalone/io/socket_source_address_test.dart
index a341568..4b95433 100644
--- a/tests/standalone/io/socket_source_address_test.dart
+++ b/tests/standalone/io/socket_source_address_test.dart
@@ -23,28 +23,30 @@
}
Future testArguments(connectFunction) async {
+ var sourceAddress;
asyncStart();
var server = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0);
- server.listen((_) { throw 'Connection unexpected'; },
- onDone: () => asyncEnd());
+ server.listen((_) {
+ throw 'Unexpected connection from address $sourceAddress';
+ }, onDone: () => asyncEnd());
asyncStart();
// Illegal type for sourceAddress.
- for (var sourceAddress in ['www.google.com', 'abc']) {
+ for (sourceAddress in ['www.google.com', 'abc']) {
await throws(() => connectFunction('127.0.0.1',
server.port,
sourceAddress: sourceAddress),
(e) => e is ArgumentError);
}
// Unsupported local address.
- for (var sourceAddress in ['8.8.8.8', new InternetAddress('8.8.8.8')]) {
+ for (sourceAddress in ['8.8.8.8', new InternetAddress('8.8.8.8')]) {
await throws(() => connectFunction('127.0.0.1',
server.port,
sourceAddress: sourceAddress),
(e) => e is SocketException);
}
// Address family mismatch.
- for (var sourceAddress in ['::1', InternetAddress.LOOPBACK_IP_V6]) {
+ for (sourceAddress in ['::1', InternetAddress.LOOPBACK_IP_V6]) {
await throws(() => connectFunction('127.0.0.1',
server.port,
sourceAddress: sourceAddress),
diff --git a/tests/standalone/standalone.status b/tests/standalone/standalone.status
index 18861b0..20d016c 100644
--- a/tests/standalone/standalone.status
+++ b/tests/standalone/standalone.status
@@ -39,14 +39,14 @@
[ $compiler == none && ($runtime == drt || $runtime == dartium || $runtime == ContentShellOnAndroid) ]
typed_array_test: Fail # Issue 13921
typed_array_int64_uint64_test: Fail # Issue 13921
-typed_data_isolate_test: Skip # This test uses dart:io
-io/*: Skip # Don't run tests using dart:io in the browser
+typed_data_isolate_test: SkipByDesign # This test uses dart:io
+io/*: SkipByDesign # Don't run tests using dart:io in the browser
package/*: Skip # Do not run those in Dartium.
-debugger/*: Skip # Do not run standalone debugger tests in browser.
+debugger/*: SkipByDesign # Do not run standalone debugger tests in browser.
coverage_test: Skip
full_coverage_test: Skip
http_launch_test: Skip
-vmservice/*: Skip # Do not run standalone vm service tests in browser.
+vmservice/*: SkipByDesign # Do not run standalone vm service tests in browser.
issue14236_test: Skip # Issue 14236 Script snapshots do not work in the browser.
javascript_compatibility_errors_test: Skip
javascript_compatibility_warnings_test: Skip
@@ -126,9 +126,9 @@
io/file_read_special_device_test: Fail # Issue 17440
[ $arch == mips && $mode == debug ]
-io/web_socket_test: Skip # Times out. Issue 20352
+io/web_socket_test: SkipSlow # Times out. Issue 20352
io/test_runner_test: Skip # Flakily times out in a subtest. Issue 201351
-full_coverage_test: Skip # Times out. Issue 20352
+full_coverage_test: SkipSlow # Times out. Issue 20352
io/http_client_stays_alive_test: Skip # Timing dependent test, MIPS machine too slow.
[ $compiler == none && ($runtime == dartium || $runtime == ContentShellOnAndroid) && $unchecked ]
diff --git a/tests/try/poi/diff_test.dart b/tests/try/poi/diff_test.dart
index eaf9c1c..33cffb5 100644
--- a/tests/try/poi/diff_test.dart
+++ b/tests/try/poi/diff_test.dart
@@ -79,7 +79,8 @@
Future<LibraryElement> future = compiler.libraryLoader.loadLibrary(scriptUri);
return future.then((LibraryElement library) {
Script sourceScript = new Script(
- scriptUri, scriptUri, new StringSourceFile('$scriptUri', afterSource));
+ scriptUri, scriptUri,
+ new StringSourceFile.fromUri(scriptUri, afterSource));
var dartPrivacyIsBroken = compiler.libraryLoader;
LibraryElement newLibrary = dartPrivacyIsBroken.createLibrarySync(
null, sourceScript, scriptUri);
diff --git a/tests/try/poi/library_updater_test.dart b/tests/try/poi/library_updater_test.dart
index dbaea15e..8513442 100644
--- a/tests/try/poi/library_updater_test.dart
+++ b/tests/try/poi/library_updater_test.dart
@@ -23,7 +23,7 @@
Script newScriptFrom(LibraryElement library, String newSource) {
Script script = library.entryCompilationUnit.script;
return script.copyWithFile(
- new StringSourceFile(script.file.filename, newSource));
+ new StringSourceFile.fromUri(script.file.uri, newSource));
}
class LibraryUpdaterTestCase extends CompilerTestCase {
diff --git a/tests/try/poi/poi_find_test.dart b/tests/try/poi/poi_find_test.dart
index 496697a..af4bec7 100644
--- a/tests/try/poi/poi_find_test.dart
+++ b/tests/try/poi/poi_find_test.dart
@@ -35,7 +35,7 @@
Expect.stringEquals('$script', '$foundScript');
Expect.stringEquals('main', element.name);
- String source = handler.provider.sourceFiles['$script'].slowText();
+ String source = handler.provider.sourceFiles[script].slowText();
final int position = source.indexOf('main()');
Expect.isTrue(position > 0, '$position > 0');
diff --git a/tests/try/try.status b/tests/try/try.status
index 40ac392..b481a5d 100644
--- a/tests/try/try.status
+++ b/tests/try/try.status
@@ -12,7 +12,7 @@
[ $csp ]
web/end_to_end_test: Fail, OK # Issue 17935
-web/incremental_compilation_update_test: Skip # Test uses eval, not supported in CSP mode.
+web/incremental_compilation_update_test: SkipByDesign # Test uses eval, not supported in CSP mode.
[ $runtime == safari || $runtime == safarimobilesim ]
web/cursor_position_test: Fail # Issue 19836
diff --git a/tests/utils/utils.status b/tests/utils/utils.status
index fadb64d..8f8e406 100644
--- a/tests/utils/utils.status
+++ b/tests/utils/utils.status
@@ -13,7 +13,7 @@
*: Skip
[ $compiler == none && $runtime != vm ]
-dart2js_test: Skip # Uses dart:io.
+dart2js_test: SkipByDesign # Uses dart:io.
[ $compiler == dart2js && $mode == debug ]
diff --git a/tools/VERSION b/tools/VERSION
index 8185edc..b1a42ea 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -27,5 +27,5 @@
MAJOR 1
MINOR 9
PATCH 0
-PRERELEASE 8
-PRERELEASE_PATCH 4
+PRERELEASE 9
+PRERELEASE_PATCH 0
diff --git a/tools/archive_crash.py b/tools/archive_crash.py
index 5da173c..ef08b34 100755
--- a/tools/archive_crash.py
+++ b/tools/archive_crash.py
@@ -17,6 +17,8 @@
import utils
import uuid
+from glob import glob
+
GCS_FOLDER = 'dart-temp-crash-archive'
GSUTIL='/b/build/scripts/slave/gsutil'
@@ -35,12 +37,22 @@
print 'Dump now available in %s' % archived_filename
def TEMPArchiveBuild():
- d = '/b/build/slave/vm-linux-debug-x64-asan-be/build/dart/out/DebugX64/dart'
- CopyToGCS(d)
+ if not 'PWD' in os.environ:
+ return
+ pwd = os.environ['PWD']
+ print pwd
+ if not 'vm-' in pwd:
+ return
+ if 'win' in pwd or 'release' in pwd:
+ return
+ files = glob('%s/out/Debug*/dart' % pwd)
+ files.extend(glob('%s/xcodebuild/Debug*/dart' % pwd))
+ print('Archiving: %s' % files)
+ for f in files:
+ CopyToGCS(f)
def Main():
- if 'PWD' in os.environ and 'x64-asan' in os.environ['PWD']:
- TEMPArchiveBuild()
+ TEMPArchiveBuild()
if utils.GuessOS() != 'linux':
print 'Currently only archiving crash dumps on linux'
return 0
diff --git a/tools/dom/src/dartium_CustomElementSupport.dart b/tools/dom/src/dartium_CustomElementSupport.dart
index 3afc56a..a14e07f 100644
--- a/tools/dom/src/dartium_CustomElementSupport.dart
+++ b/tools/dom/src/dartium_CustomElementSupport.dart
@@ -49,6 +49,11 @@
}
var className = MirrorSystem.getName(cls.simpleName);
+ if (cls.isAbstract) {
+ throw new UnsupportedError('Invalid custom element '
+ 'class $className is abstract.');
+ }
+
var createdConstructor = cls.declarations[new Symbol('$className.created')];
if (createdConstructor == null ||
createdConstructor is! MethodMirror ||
diff --git a/tools/run_pub.py b/tools/run_pub.py
index e11701d..c43b039 100755
--- a/tools/run_pub.py
+++ b/tools/run_pub.py
@@ -12,8 +12,7 @@
SCRIPT_DIR = os.path.dirname(sys.argv[0])
DART_ROOT = os.path.realpath(os.path.join(SCRIPT_DIR, '..'))
-PUB_PATH = os.path.join(DART_ROOT,
- 'sdk/lib/_internal/pub_generated/bin/pub.dart')
+PUB_PATH = os.path.join(DART_ROOT, 'sdk/lib/_internal/pub/bin/pub.dart')
CANARY_PATH = os.path.join(DART_ROOT, 'tools', 'canary.dart')
usage = """run_pub.py --package-root=<package root>"""
@@ -102,4 +101,4 @@
if __name__ == '__main__':
- sys.exit(main());
\ No newline at end of file
+ sys.exit(main())
diff --git a/tools/status_clean.dart b/tools/status_clean.dart
index 14b0f79..fb97590 100644
--- a/tools/status_clean.dart
+++ b/tools/status_clean.dart
@@ -36,8 +36,7 @@
"tests/compiler/dart2js_native/dart2js_native.status"],
["dart2js", "tests/compiler/dart2js",
"tests/compiler/dart2js/dart2js.status"],
- ["pub", "sdk/lib/_internal/pub_generated",
- "sdk/lib/_internal/pub/pub.status"],
+ ["pub", "sdk/lib/_internal/pub", "sdk/lib/_internal/pub/pub.status"],
["benchmark_smoke", "tests/benchmark_smoke",
"tests/benchmark_smoke/benchmark_smoke.status"],
["co19", "tests/co19/src", "tests/co19/co19-analyzer2.status"],
diff --git a/tools/testing/dart/status_file_parser.dart b/tools/testing/dart/status_file_parser.dart
index 918e664..8c32e6e 100644
--- a/tools/testing/dart/status_file_parser.dart
+++ b/tools/testing/dart/status_file_parser.dart
@@ -33,6 +33,7 @@
static Expectation OK = byName('Ok');
static Expectation SLOW = byName('Slow');
static Expectation SKIP = byName('Skip');
+ static Expectation SKIP_SLOW = byName('SkipSlow');
static Expectation SKIP_BY_DESIGN = byName('SkipByDesign');
static Expectation byName(String name) {
@@ -72,8 +73,9 @@
build("PubGetError", group: fail);
- build("Skip", isMetaExpectation: true);
+ var skip = build("Skip", isMetaExpectation: true);
build("SkipByDesign", isMetaExpectation: true);
+ build("SkipSlow", group: skip, isMetaExpectation: true);
build("Ok", isMetaExpectation: true);
build("Slow", isMetaExpectation: true);
}
diff --git a/tools/testing/dart/summary_report.dart b/tools/testing/dart/summary_report.dart
index d6db9a9..2f740b5 100644
--- a/tools/testing/dart/summary_report.dart
+++ b/tools/testing/dart/summary_report.dart
@@ -36,7 +36,8 @@
bool containsFail = expectations
.any((expectation) => expectation.canBeOutcomeOf(Expectation.FAIL));
bool containsPass = expectations.contains(Expectation.PASS);
- bool containsSkip = expectations.contains(Expectation.SKIP);
+ bool containsSkip = expectations
+ .any((expectation) => expectation.canBeOutcomeOf(Expectation.SKIP));
bool containsSkipByDesign =
expectations.contains(Expectation.SKIP_BY_DESIGN);
bool containsCrash = expectations.contains(Expectation.CRASH);
diff --git a/tools/testing/dart/test_configurations.dart b/tools/testing/dart/test_configurations.dart
index 6edd93c..c49bfca 100644
--- a/tools/testing/dart/test_configurations.dart
+++ b/tools/testing/dart/test_configurations.dart
@@ -199,7 +199,7 @@
// TODO(rnystrom): Move pub back into TEST_SUITE_DIRECTORIES once
// #104 is fixed.
testSuites.add(new StandardTestSuite(conf, 'pub',
- new Path('sdk/lib/_internal/pub_generated'),
+ new Path('sdk/lib/_internal/pub'),
['sdk/lib/_internal/pub/pub.status'],
isTestFilePredicate: (file) => file.endsWith('_test.dart'),
recursive: true));
diff --git a/tools/testing/dart/test_runner.dart b/tools/testing/dart/test_runner.dart
index 1bdd0c7..40d238d 100644
--- a/tools/testing/dart/test_runner.dart
+++ b/tools/testing/dart/test_runner.dart
@@ -128,12 +128,17 @@
deepJsonCompare(environmentOverrides, other.environmentOverrides);
String get reproductionCommand {
+ var env = new StringBuffer();
+ environmentOverrides.forEach((key, value) =>
+ (io.Platform.operatingSystem == 'windows') ?
+ env.write('set $key=${escapeCommandLineArgument(value)} & ') :
+ env.write('$key=${escapeCommandLineArgument(value)} '));
var command = ([executable]..addAll(arguments))
.map(escapeCommandLineArgument).join(' ');
if (workingDirectory != null) {
command = "$command (working directory: $workingDirectory)";
}
- return command;
+ return "$env$command";
}
Future<bool> get outputIsUpToDate => new Future.value(false);
diff --git a/tools/testing/dart/test_suite.dart b/tools/testing/dart/test_suite.dart
index b7aaedb..0689ad7 100644
--- a/tools/testing/dart/test_suite.dart
+++ b/tools/testing/dart/test_suite.dart
@@ -292,7 +292,8 @@
// Handle skipped tests
if (expectations.contains(Expectation.SKIP) ||
- expectations.contains(Expectation.SKIP_BY_DESIGN)) {
+ expectations.contains(Expectation.SKIP_BY_DESIGN) ||
+ expectations.contains(Expectation.SKIP_SLOW)) {
return;
}
diff --git a/utils/pub/pub.gyp b/utils/pub/pub.gyp
index d75a395..13d0b09 100644
--- a/utils/pub/pub.gyp
+++ b/utils/pub/pub.gyp
@@ -32,7 +32,7 @@
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
'--package-root=<(PRODUCT_DIR)/packages/',
'--snapshot=<(SHARED_INTERMEDIATE_DIR)/pub.dart.snapshot',
- '../../sdk/lib/_internal/pub_generated/bin/pub.dart',
+ '../../sdk/lib/_internal/pub/bin/pub.dart',
]
},
],
@@ -78,7 +78,7 @@
'inputs': [
'../../tools/create_timestamp_file.py',
'<!@(["python", "../../tools/list_files.py", "\\.dart$",'
- ' "../../sdk/lib/_internal/pub_generated"])',
+ ' "../../sdk/lib/_internal/pub"])',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/pub_files.stamp',