Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(92)

Unified Diff: lib/compiler/implementation/lib/isolate_patch.dart

Issue 10828411: Re-apply 'Unify dart:isolate.' with fixes for autogenerated dart2js and dartium html files. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Review fixes. Created 8 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « lib/_internal/libraries.dart ('k') | lib/compiler/implementation/library_map.dart » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: lib/compiler/implementation/lib/isolate_patch.dart
diff --git a/lib/isolate/dart2js/isolateimpl.dart b/lib/compiler/implementation/lib/isolate_patch.dart
similarity index 52%
rename from lib/isolate/dart2js/isolateimpl.dart
rename to lib/compiler/implementation/lib/isolate_patch.dart
index bec8d1799154b5cae0a48c49ea59dee9352e2b40..cced45e552dc0e05bf73ad4f1ef2409723e46a2a 100644
--- a/lib/isolate/dart2js/isolateimpl.dart
+++ b/lib/compiler/implementation/lib/isolate_patch.dart
@@ -2,6 +2,64 @@
// for 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 file for the dart:isolate library.
+
+#import("dart:uri");
+
+// Source in shared isolate serialization implementation.
+#source("../../../js_isolate_impl/isolate.dart");
+
+/**
+ * Called by the compiler to support switching
+ * between isolates when we get a callback from the DOM.
+ */
+void _callInIsolate(_IsolateContext isolate, Function function) {
+ isolate.eval(function);
+ _globalState.topEventLoop.run();
+}
+
+/**
+ * Called by the compiler to fetch the current isolate context.
+ */
+void _currentIsolate() => _globalState.currentContext;
+
+/********************************************************
+ Inserted from lib/isolate/dart2js/compiler_hooks.dart
+ ********************************************************/
+
+/**
+ * Wrapper that takes the dart entry point and runs it within an isolate. The
+ * dart2js compiler will inject a call of the form
+ * [: startRootIsolate(main); :] when it determines that this wrapping
+ * is needed. For single-isolate applications (e.g. hello world), this
+ * call is not emitted.
+ */
+void startRootIsolate(entry) {
+ _globalState = new _Manager();
+
+ // Don't start the main loop again, if we are in a worker.
+ if (_globalState.isWorker) return;
+ final rootContext = new _IsolateContext();
+ _globalState.rootContext = rootContext;
+ _fillStatics(rootContext);
+
+ // BUG(5151491): Setting currentContext should not be necessary, but
+ // because closures passed to the DOM as event handlers do not bind their
+ // isolate automatically we try to give them a reasonable context to live in
+ // by having a "default" isolate (the first one created).
+ _globalState.currentContext = rootContext;
+
+ if (_window != null) {
+ rootContext.eval(() => _setTimerFactoryClosure( _timerFactory));
+ }
+ rootContext.eval(entry);
+ _globalState.topEventLoop.run();
+}
+
+/********************************************************
+ Inserted from lib/isolate/dart2js/isolateimpl.dart
+ ********************************************************/
+
/**
* Concepts used here:
*
@@ -39,14 +97,14 @@ void _fillStatics(context) native @"""
""";
ReceivePort _lazyPort;
-ReceivePort get _port() {
+patch ReceivePort get port() {
if (_lazyPort === null) {
_lazyPort = new ReceivePort();
}
return _lazyPort;
}
-SendPort _spawnFunction(void topLevelFunction()) {
+patch SendPort spawnFunction(void topLevelFunction()) {
final name = _IsolateNatives._getJSFunctionName(topLevelFunction);
if (name == null) {
throw new UnsupportedOperationException(
@@ -55,7 +113,7 @@ SendPort _spawnFunction(void topLevelFunction()) {
return _IsolateNatives._spawn(name, null, false);
}
-SendPort _spawnUri(String uri) {
+patch SendPort spawnUri(String uri) {
return _IsolateNatives._spawn(null, uri, false);
}
@@ -543,3 +601,466 @@ class _IsolateNatives {
'functionName': functionName }));
}
}
+
+/********************************************************
+ Inserted from lib/isolate/dart2js/ports.dart
+ ********************************************************/
+
+/** Common functionality to all send ports. */
+class _BaseSendPort implements SendPort {
+ /** Id for the destination isolate. */
+ final int _isolateId;
+
+ const _BaseSendPort(this._isolateId);
+
+ void _checkReplyTo(SendPort replyTo) {
+ if (replyTo !== null
+ && replyTo is! _NativeJsSendPort
+ && replyTo is! _WorkerSendPort
+ && replyTo is! _BufferingSendPort) {
+ throw new Exception("SendPort.send: Illegal replyTo port type");
+ }
+ }
+
+ Future call(var message) {
+ final completer = new Completer();
+ final port = new _ReceivePortImpl();
+ send(message, port.toSendPort());
+ port.receive((value, ignoreReplyTo) {
+ port.close();
+ if (value is Exception) {
+ completer.completeException(value);
+ } else {
+ completer.complete(value);
+ }
+ });
+ return completer.future;
+ }
+
+ abstract void send(var message, [SendPort replyTo]);
+ abstract bool operator ==(var other);
+ abstract int hashCode();
+}
+
+/** A send port that delivers messages in-memory via native JavaScript calls. */
+class _NativeJsSendPort extends _BaseSendPort implements SendPort {
+ final _ReceivePortImpl _receivePort;
+
+ const _NativeJsSendPort(this._receivePort, int isolateId) : super(isolateId);
+
+ void send(var message, [SendPort replyTo = null]) {
+ _waitForPendingPorts([message, replyTo], () {
+ _checkReplyTo(replyTo);
+ // Check that the isolate still runs and the port is still open
+ final isolate = _globalState.isolates[_isolateId];
+ if (isolate == null) return;
+ if (_receivePort._callback == null) return;
+
+ // We force serialization/deserialization as a simple way to ensure
+ // isolate communication restrictions are respected between isolates that
+ // live in the same worker. [_NativeJsSendPort] delivers both messages
+ // from the same worker and messages from other workers. In particular,
+ // messages sent from a worker via a [_WorkerSendPort] are received at
+ // [_processWorkerMessage] and forwarded to a native port. In such cases,
+ // here we'll see [_globalState.currentContext == null].
+ final shouldSerialize = _globalState.currentContext != null
+ && _globalState.currentContext.id != _isolateId;
+ var msg = message;
+ var reply = replyTo;
+ if (shouldSerialize) {
+ msg = _serializeMessage(msg);
+ reply = _serializeMessage(reply);
+ }
+ _globalState.topEventLoop.enqueue(isolate, () {
+ if (_receivePort._callback != null) {
+ if (shouldSerialize) {
+ msg = _deserializeMessage(msg);
+ reply = _deserializeMessage(reply);
+ }
+ _receivePort._callback(msg, reply);
+ }
+ }, 'receive $message');
+ });
+ }
+
+ bool operator ==(var other) => (other is _NativeJsSendPort) &&
+ (_receivePort == other._receivePort);
+
+ int hashCode() => _receivePort._id;
+}
+
+/** A send port that delivers messages via worker.postMessage. */
+// TODO(eub): abstract this for iframes.
+class _WorkerSendPort extends _BaseSendPort implements SendPort {
+ final int _workerId;
+ final int _receivePortId;
+
+ const _WorkerSendPort(this._workerId, int isolateId, this._receivePortId)
+ : super(isolateId);
+
+ void send(var message, [SendPort replyTo = null]) {
+ _waitForPendingPorts([message, replyTo], () {
+ _checkReplyTo(replyTo);
+ final workerMessage = _serializeMessage({
+ 'command': 'message',
+ 'port': this,
+ 'msg': message,
+ 'replyTo': replyTo});
+
+ if (_globalState.isWorker) {
+ // communication from one worker to another go through the main worker:
+ _globalState.mainManager.postMessage(workerMessage);
+ } else {
+ _globalState.managers[_workerId].postMessage(workerMessage);
+ }
+ });
+ }
+
+ bool operator ==(var other) {
+ return (other is _WorkerSendPort) &&
+ (_workerId == other._workerId) &&
+ (_isolateId == other._isolateId) &&
+ (_receivePortId == other._receivePortId);
+ }
+
+ int hashCode() {
+ // TODO(sigmund): use a standard hash when we get one available in corelib.
+ return (_workerId << 16) ^ (_isolateId << 8) ^ _receivePortId;
+ }
+}
+
+/** A port that buffers messages until an underlying port gets resolved. */
+class _BufferingSendPort extends _BaseSendPort implements SendPort {
+ /** Internal counter to assign unique ids to each port. */
+ static int _idCount = 0;
+
+ /** For implementing equals and hashcode. */
+ final int _id;
+
+ /** Underlying port, when resolved. */
+ SendPort _port;
+
+ /**
+ * Future of the underlying port, so that we can detect when this port can be
+ * sent on messages.
+ */
+ Future<SendPort> _futurePort;
+
+ /** Pending messages (and reply ports). */
+ List pending;
+
+ _BufferingSendPort(isolateId, this._futurePort)
+ : super(isolateId), _id = _idCount, pending = [] {
+ _idCount++;
+ _futurePort.then((p) {
+ _port = p;
+ for (final item in pending) {
+ p.send(item['message'], item['replyTo']);
+ }
+ pending = null;
+ });
+ }
+
+ _BufferingSendPort.fromPort(isolateId, this._port)
+ : super(isolateId), _id = _idCount {
+ _idCount++;
+ }
+
+ void send(var message, [SendPort replyTo]) {
+ if (_port != null) {
+ _port.send(message, replyTo);
+ } else {
+ pending.add({'message': message, 'replyTo': replyTo});
+ }
+ }
+
+ bool operator ==(var other) =>
+ other is _BufferingSendPort && _id == other._id;
+ int hashCode() => _id;
+}
+
+/** Default factory for receive ports. */
+patch class _ReceivePortFactory {
+ patch factory ReceivePort() {
+ return new _ReceivePortImpl();
+ }
+
+}
+
+/** Implementation of a multi-use [ReceivePort] on top of JavaScript. */
+class _ReceivePortImpl {
+ int _id;
+ Function _callback;
+ static int _nextFreeId = 1;
+
+ _ReceivePortImpl()
+ : _id = _nextFreeId++ {
+ _globalState.currentContext.register(_id, this);
+ }
+
+ void receive(void onMessage(var message, SendPort replyTo)) {
+ _callback = onMessage;
+ }
+
+ void close() {
+ _callback = null;
+ _globalState.currentContext.unregister(_id);
+ }
+
+ SendPort toSendPort() {
+ return new _NativeJsSendPort(this, _globalState.currentContext.id);
+ }
+}
+
+/** Wait until all ports in a message are resolved. */
+_waitForPendingPorts(var message, void callback()) {
+ final finder = new _PendingSendPortFinder();
+ finder.traverse(message);
+ Futures.wait(finder.ports).then((_) => callback());
+}
+
+
+/** Visitor that finds all unresolved [SendPort]s in a message. */
+class _PendingSendPortFinder extends _MessageTraverser {
+ List<Future<SendPort>> ports;
+ _PendingSendPortFinder() : super(), ports = [] {
+ _visited = new _JsVisitedMap();
+ }
+
+ visitPrimitive(x) {}
+
+ visitList(List list) {
+ final seen = _visited[list];
+ if (seen !== null) return;
+ _visited[list] = true;
+ // TODO(sigmund): replace with the following: (bug #1660)
+ // list.forEach(_dispatch);
+ list.forEach((e) => _dispatch(e));
+ }
+
+ visitMap(Map map) {
+ final seen = _visited[map];
+ if (seen !== null) return;
+
+ _visited[map] = true;
+ // TODO(sigmund): replace with the following: (bug #1660)
+ // map.getValues().forEach(_dispatch);
+ map.getValues().forEach((e) => _dispatch(e));
+ }
+
+ visitSendPort(SendPort port) {
+ if (port is _BufferingSendPort && port._port == null) {
+ ports.add(port._futurePort);
+ }
+ }
+}
+
+/********************************************************
+ Inserted from lib/isolate/dart2js/messages.dart
+ ********************************************************/
+
+// Defines message visitors, serialization, and deserialization.
+
+/** Serialize [message] (or simulate serialization). */
+_serializeMessage(message) {
+ if (_globalState.needSerialization) {
+ return new _JsSerializer().traverse(message);
+ } else {
+ return new _JsCopier().traverse(message);
+ }
+}
+
+/** Deserialize [message] (or simulate deserialization). */
+_deserializeMessage(message) {
+ if (_globalState.needSerialization) {
+ return new _JsDeserializer().deserialize(message);
+ } else {
+ // Nothing more to do.
+ return message;
+ }
+}
+
+class _JsSerializer extends _Serializer {
+
+ _JsSerializer() : super() { _visited = new _JsVisitedMap(); }
+
+ visitSendPort(SendPort x) {
+ if (x is _NativeJsSendPort) return visitNativeJsSendPort(x);
+ if (x is _WorkerSendPort) return visitWorkerSendPort(x);
+ if (x is _BufferingSendPort) return visitBufferingSendPort(x);
+ throw "Illegal underlying port $x";
+ }
+
+ visitNativeJsSendPort(_NativeJsSendPort port) {
+ return ['sendport', _globalState.currentManagerId,
+ port._isolateId, port._receivePort._id];
+ }
+
+ visitWorkerSendPort(_WorkerSendPort port) {
+ return ['sendport', port._workerId, port._isolateId, port._receivePortId];
+ }
+
+ visitBufferingSendPort(_BufferingSendPort port) {
+ if (port._port != null) {
+ return visitSendPort(port._port);
+ } else {
+ // TODO(floitsch): Use real exception (which one?).
+ throw
+ "internal error: must call _waitForPendingPorts to ensure all"
+ " ports are resolved at this point.";
+ }
+ }
+
+}
+
+
+class _JsCopier extends _Copier {
+
+ _JsCopier() : super() { _visited = new _JsVisitedMap(); }
+
+ visitSendPort(SendPort x) {
+ if (x is _NativeJsSendPort) return visitNativeJsSendPort(x);
+ if (x is _WorkerSendPort) return visitWorkerSendPort(x);
+ if (x is _BufferingSendPort) return visitBufferingSendPort(x);
+ throw "Illegal underlying port $p";
+ }
+
+ SendPort visitNativeJsSendPort(_NativeJsSendPort port) {
+ return new _NativeJsSendPort(port._receivePort, port._isolateId);
+ }
+
+ SendPort visitWorkerSendPort(_WorkerSendPort port) {
+ return new _WorkerSendPort(
+ port._workerId, port._isolateId, port._receivePortId);
+ }
+
+ SendPort visitBufferingSendPort(_BufferingSendPort port) {
+ if (port._port != null) {
+ return visitSendPort(port._port);
+ } else {
+ // TODO(floitsch): Use real exception (which one?).
+ throw
+ "internal error: must call _waitForPendingPorts to ensure all"
+ " ports are resolved at this point.";
+ }
+ }
+
+}
+
+class _JsDeserializer extends _Deserializer {
+
+ SendPort deserializeSendPort(List x) {
+ int managerId = x[1];
+ int isolateId = x[2];
+ int receivePortId = x[3];
+ // If two isolates are in the same manager, we use NativeJsSendPorts to
+ // deliver messages directly without using postMessage.
+ if (managerId == _globalState.currentManagerId) {
+ var isolate = _globalState.isolates[isolateId];
+ if (isolate == null) return null; // Isolate has been closed.
+ var receivePort = isolate.lookup(receivePortId);
+ return new _NativeJsSendPort(receivePort, isolateId);
+ } else {
+ return new _WorkerSendPort(managerId, isolateId, receivePortId);
+ }
+ }
+
+}
+
+class _JsVisitedMap implements _MessageTraverserVisitedMap {
+ List tagged;
+
+ /** Retrieves any information stored in the native object [object]. */
+ operator[](var object) {
+ return _getAttachedInfo(object);
+ }
+
+ /** Injects some information into the native [object]. */
+ void operator[]=(var object, var info) {
+ tagged.add(object);
+ _setAttachedInfo(object, info);
+ }
+
+ /** Get ready to rumble. */
+ void reset() {
+ assert(tagged == null);
+ tagged = new List();
+ }
+
+ /** Remove all information injected in the native objects. */
+ cleanup() {
+ for (int i = 0, length = tagged.length; i < length; i++) {
+ _clearAttachedInfo(tagged[i]);
+ }
+ tagged = null;
+ }
+
+ _clearAttachedInfo(var o) native
+ "o['__MessageTraverser__attached_info__'] = (void 0);";
+
+ _setAttachedInfo(var o, var info) native
+ "o['__MessageTraverser__attached_info__'] = info;";
+
+ _getAttachedInfo(var o) native
+ "return o['__MessageTraverser__attached_info__'];";
+}
+
+// only visible for testing purposes
+// TODO(sigmund): remove once we can disable privacy for testing (bug #1882)
+class TestingOnly {
+ static copy(x) {
+ return new _JsCopier().traverse(x);
+ }
+
+ // only visible for testing purposes
+ static serialize(x) {
+ _Serializer serializer = new _JsSerializer();
+ _Deserializer deserializer = new _JsDeserializer();
+ return deserializer.deserialize(serializer.traverse(x));
+ }
+}
+
+/********************************************************
+ Inserted from lib/isolate/dart2js/timer_provider.dart
+ ********************************************************/
+
+// We don't want to import the DOM library just because of window.setTimeout,
+// so we reconstruct the Window class here. The only conflict that could happen
+// with the other DOMWindow class would be because of subclasses.
+// Currently, none of the two Dart classes have subclasses.
+typedef void _TimeoutHandler();
+
+class _Window native "@*DOMWindow" {
+ int setTimeout(_TimeoutHandler handler, int timeout) native;
+ int setInterval(_TimeoutHandler handler, int timeout) native;
+}
+
+_Window get _window() =>
+ JS('bool', 'typeof window != "undefined"') ? JS('_Window', 'window') : null;
+
+class _Timer implements Timer {
+ final bool _once;
+ int _handle;
+
+ _Timer(int milliSeconds, void callback(Timer timer))
+ : _once = true {
+ _handle = _window.setTimeout(() => callback(this), milliSeconds);
+ }
+
+ _Timer.repeating(int milliSeconds, void callback(Timer timer))
+ : _once = false {
+ _handle = _window.setInterval(() => callback(this), milliSeconds);
+ }
+
+ void cancel() {
+ if (_once) {
+ _window.clearTimeout(_handle);
+ } else {
+ _window.clearInterval(_handle);
+ }
+ }
+}
+
+Timer _timerFactory(int millis, void callback(Timer timer), bool repeating) =>
+ repeating ? new _Timer.repeating(millis, callback)
+ : new _Timer(millis, callback);
« no previous file with comments | « lib/_internal/libraries.dart ('k') | lib/compiler/implementation/library_map.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698