OLD | NEW |
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 /** | 5 /// This library adapts ES6 generators to implement Dart's async/await. |
6 * This library adapts ES6 generators to implement Dart's async/await. | 6 /// It's designed to interact with Dart's Future/Stream and follow Dart |
7 * | 7 /// async/await semantics. |
8 * It's designed to interact with Dart's Future/Stream and follow Dart | 8 /// See https://github.com/dart-lang/dev_compiler/issues/245 for ideas on |
9 * async/await semantics. | 9 /// reconciling Dart's Future and ES6 Promise. |
10 * | 10 /// Inspired by `co`: https://github.com/tj/co/blob/master/index.js, which is a |
11 * See https://github.com/dart-lang/dev_compiler/issues/245 for ideas on | 11 /// stepping stone for proposed ES7 async/await, and uses ES6 Promises. |
12 * reconciling Dart's Future and ES6 Promise. | 12 part of dart._runtime; |
13 * | |
14 * Inspired by `co`: https://github.com/tj/co/blob/master/index.js, which is a | |
15 * stepping stone for proposed ES7 async/await, and uses ES6 Promises. | |
16 */ | |
17 dart_library.library('dart/_generators', null, /* Imports */[ | |
18 ], /* Lazy Imports */[ | |
19 'dart/_operations', | |
20 'dart/_js_helper', | |
21 'dart/core', | |
22 'dart/collection', | |
23 'dart/async' | |
24 ], function(exports, _operations, _js_helper, core, collection, async) { | |
25 'use strict'; | |
26 | 13 |
27 const _jsIterator = Symbol('_jsIterator'); | 14 final _jsIterator = JS('', 'Symbol("_jsIterator")'); |
28 const _current = Symbol('_current'); | 15 final _current = JS('', 'Symbol("_current")'); |
29 | 16 |
30 function syncStar(gen, E, ...args) { | 17 syncStar(gen, E, @rest args) => JS('', '''(() => { |
31 const SyncIterable_E = _js_helper.SyncIterable$(E); | 18 // TODO(ochafik). |
32 return new SyncIterable_E(gen, args); | 19 const SyncIterable_E = ${genericTypeConstructor(SyncIterable)}($E); |
| 20 return new SyncIterable_E($gen, $args); |
| 21 })()'''); |
| 22 |
| 23 @JSExportName('async') |
| 24 async_(gen, T, @rest args) => JS('', '''(() => { |
| 25 let iter; |
| 26 function onValue(res) { |
| 27 if (res === void 0) res = null; |
| 28 return next(iter.next(res)); |
33 } | 29 } |
34 exports.syncStar = syncStar; | 30 function onError(err) { |
| 31 // If the awaited Future throws, we want to convert this to an exception |
| 32 // thrown from the `yield` point, as if it was thrown there. |
| 33 // |
| 34 // If the exception is not caught inside `gen`, it will emerge here, which |
| 35 // will send it to anyone listening on this async function's Future<T>. |
| 36 // |
| 37 // In essence, we are giving the code inside the generator a chance to |
| 38 // use try-catch-finally. |
| 39 return next(iter.throw(err)); |
| 40 } |
| 41 function next(ret) { |
| 42 if (ret.done) return ret.value; |
| 43 // Checks if the awaited value is a Future. |
| 44 let future = ret.value; |
| 45 if (!$instanceOf(future, ${genericTypeConstructor(Future)})) { |
| 46 future = $Future.value(future); |
| 47 } |
| 48 // Chain the Future so `await` receives the Future's value. |
| 49 return future.then(onValue, {onError: onError}); |
| 50 } |
| 51 return ${genericTypeConstructor(Future)}(T).new(function() { |
| 52 iter = $gen(...$args)[Symbol.iterator](); |
| 53 return onValue(); |
| 54 }); |
| 55 })()'''); |
35 | 56 |
36 function async_(gen, T, ...args) { | 57 // Implementation inspired by _AsyncStarStreamController in |
37 let iter; | 58 // dart-lang/sdk's runtime/lib/core_patch.dart |
38 function onValue(res) { | 59 // |
39 if (res === void 0) res = null; | 60 // Given input like: |
40 return next(iter.next(res)); | 61 // |
41 } | 62 // foo() async* { |
42 function onError(err) { | 63 // yield 1; |
43 // If the awaited Future throws, we want to convert this to an exception | 64 // yield* bar(); |
44 // thrown from the `yield` point, as if it was thrown there. | 65 // print(await baz()); |
45 // | 66 // } |
46 // If the exception is not caught inside `gen`, it will emerge here, which | 67 // |
47 // will send it to anyone listening on this async function's Future<T>. | 68 // This generates as: |
48 // | 69 // |
49 // In essence, we are giving the code inside the generator a chance to | 70 // function foo() { |
50 // use try-catch-finally. | 71 // return dart.asyncStar(function*(stream) { |
51 return next(iter.throw(err)); | 72 // if (stream.add(1)) return; |
52 } | 73 // yield; |
53 function next(ret) { | 74 // if (stream.addStream(bar()) return; |
54 if (ret.done) return ret.value; | 75 // yield; |
55 // Checks if the awaited value is a Future. | 76 // print(yield baz()); |
56 let future = ret.value; | 77 // }); |
57 if (!_operations.instanceOf(future, async.Future$)) { | 78 // } |
58 future = async.Future.value(future); | 79 final _AsyncStarStreamController = JS('', ''' |
59 } | |
60 // Chain the Future so `await` receives the Future's value. | |
61 return future.then(onValue, {onError: onError}); | |
62 } | |
63 return async.Future$(T).new(function() { | |
64 iter = gen(...args)[Symbol.iterator](); | |
65 return onValue(); | |
66 }); | |
67 } | |
68 exports.async = async_; | |
69 | |
70 // Implementation inspired by _AsyncStarStreamController in | |
71 // dart-lang/sdk's runtime/lib/core_patch.dart | |
72 // | |
73 // Given input like: | |
74 // | |
75 // foo() async* { | |
76 // yield 1; | |
77 // yield* bar(); | |
78 // print(await baz()); | |
79 // } | |
80 // | |
81 // This generates as: | |
82 // | |
83 // function foo() { | |
84 // return dart.asyncStar(function*(stream) { | |
85 // if (stream.add(1)) return; | |
86 // yield; | |
87 // if (stream.addStream(bar()) return; | |
88 // yield; | |
89 // print(yield baz()); | |
90 // }); | |
91 // } | |
92 class _AsyncStarStreamController { | 80 class _AsyncStarStreamController { |
93 constructor(generator, T, args) { | 81 constructor(generator, T, args) { |
94 this.isAdding = false; | 82 this.isAdding = false; |
95 this.isWaiting = false; | 83 this.isWaiting = false; |
96 this.isScheduled = false; | 84 this.isScheduled = false; |
97 this.isSuspendedAtYield = false; | 85 this.isSuspendedAtYield = false; |
98 this.canceler = null; | 86 this.canceler = null; |
99 this.iterator = generator(this, ...args)[Symbol.iterator](); | 87 this.iterator = generator(this, ...args)[Symbol.iterator](); |
100 this.controller = async.StreamController$(T).new({ | 88 this.controller = ${genericTypeConstructor(StreamController)}(T).new({ |
101 onListen: () => this.scheduleGenerator(), | 89 onListen: () => this.scheduleGenerator(), |
102 onResume: () => this.onResume(), | 90 onResume: () => this.onResume(), |
103 onCancel: () => this.onCancel() | 91 onCancel: () => this.onCancel() |
104 }); | 92 }); |
105 } | 93 } |
106 | 94 |
107 onResume() { | 95 onResume() { |
108 if (this.isSuspendedAtYield) { | 96 if (this.isSuspendedAtYield) { |
109 this.scheduleGenerator(); | 97 this.scheduleGenerator(); |
110 } | 98 } |
111 } | 99 } |
112 | 100 |
113 onCancel() { | 101 onCancel() { |
114 if (this.controller.isClosed) { | 102 if (this.controller.isClosed) { |
115 return null; | 103 return null; |
116 } | 104 } |
117 if (this.canceler == null) { | 105 if (this.canceler == null) { |
118 this.canceler = async.Completer.new(); | 106 this.canceler = $Completer.new(); |
119 this.scheduleGenerator(); | 107 this.scheduleGenerator(); |
120 } | 108 } |
121 return this.canceler.future; | 109 return this.canceler.future; |
122 } | 110 } |
123 | 111 |
124 close() { | 112 close() { |
125 if (this.canceler != null && !this.canceler.isCompleted) { | 113 if (this.canceler != null && !this.canceler.isCompleted) { |
126 // If the stream has been cancelled, complete the cancellation future | 114 // If the stream has been cancelled, complete the cancellation future |
127 // with the error. | 115 // with the error. |
128 this.canceler.complete(); | 116 this.canceler.complete(); |
129 } | 117 } |
130 this.controller.close(); | 118 this.controller.close(); |
131 } | 119 } |
132 | 120 |
133 scheduleGenerator() { | 121 scheduleGenerator() { |
134 // TODO(jmesserly): is this paused check in the right place? Assuming the | 122 // TODO(jmesserly): is this paused check in the right place? Assuming the |
135 // async* Stream yields, then is paused (by other code), the body will | 123 // async* Stream yields, then is paused (by other code), the body will |
136 // already be scheduled. This will cause at least one more iteration to | 124 // already be scheduled. This will cause at least one more iteration to |
137 // run (adding another data item to the Stream) before actually pausing. | 125 // run (adding another data item to the Stream) before actually pausing. |
138 // It could be fixed by moving the `isPaused` check inside `runBody`. | 126 // It could be fixed by moving the `isPaused` check inside `runBody`. |
139 if (this.isScheduled || this.controller.isPaused || | 127 if (this.isScheduled || this.controller.isPaused || |
140 this.isAdding || this.isWaiting) { | 128 this.isAdding || this.isWaiting) { |
141 return; | 129 return; |
142 } | 130 } |
143 this.isScheduled = true; | 131 this.isScheduled = true; |
144 async.scheduleMicrotask(() => this.runBody()); | 132 $scheduleMicrotask(() => this.runBody()); |
145 } | 133 } |
146 | 134 |
147 runBody(opt_awaitValue) { | 135 runBody(opt_awaitValue) { |
148 this.isScheduled = false; | 136 this.isScheduled = false; |
149 this.isSuspendedAtYield = false; | 137 this.isSuspendedAtYield = false; |
150 this.isWaiting = false; | 138 this.isWaiting = false; |
151 let iter; | 139 let iter; |
152 try { | 140 try { |
153 iter = this.iterator.next(opt_awaitValue); | 141 iter = this.iterator.next(opt_awaitValue); |
154 } catch (e) { | 142 } catch (e) { |
155 this.addError(e, _operations.stackTrace(e)); | 143 this.addError(e, $stackTrace(e)); |
156 this.close(); | 144 this.close(); |
157 return; | 145 return; |
158 } | 146 } |
159 if (iter.done) { | 147 if (iter.done) { |
160 this.close(); | 148 this.close(); |
161 return; | 149 return; |
162 } | 150 } |
163 | 151 |
164 // If we're suspended at a yield/yield*, we're done for now. | 152 // If we're suspended at a yield/yield*, we're done for now. |
165 if (this.isSuspendedAtYield || this.isAdding) return; | 153 if (this.isSuspendedAtYield || this.isAdding) return; |
166 | 154 |
167 // Handle `await`: if we get a value passed to `yield` it means we are | 155 // Handle `await`: if we get a value passed to `yield` it means we are |
168 // waiting on this Future. Make sure to prevent scheduling, and pass the | 156 // waiting on this Future. Make sure to prevent scheduling, and pass the |
169 // value back as the result of the `yield`. | 157 // value back as the result of the `yield`. |
170 // | 158 // |
171 // TODO(jmesserly): is the timing here correct? The assumption here is | 159 // TODO(jmesserly): is the timing here correct? The assumption here is |
172 // that we should schedule `await` in `async*` the same as in `async`. | 160 // that we should schedule `await` in `async*` the same as in `async`. |
173 this.isWaiting = true; | 161 this.isWaiting = true; |
174 let future = iter.value; | 162 let future = iter.value; |
175 if (!_operations.instanceOf(future, async.Future$)) { | 163 if (!$instanceOf(future, ${genericTypeConstructor(Future)})) { |
176 future = async.Future.value(future); | 164 future = $Future.value(future); |
177 } | 165 } |
178 return future.then((x) => this.runBody(x), | 166 return future.then((x) => this.runBody(x), |
179 { onError: (e, s) => this.throwError(e, s) }); | 167 { onError: (e, s) => this.throwError(e, s) }); |
180 } | 168 } |
181 | 169 |
182 // Adds element to stream, returns true if the caller should terminate | 170 // Adds element to stream, returns true if the caller should terminate |
183 // execution of the generator. | 171 // execution of the generator. |
184 add(event) { | 172 add(event) { |
185 // If stream is cancelled, tell caller to exit the async generator. | 173 // If stream is cancelled, tell caller to exit the async generator. |
186 if (!this.controller.hasListener) return true; | 174 if (!this.controller.hasListener) return true; |
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
218 if ((this.canceler != null) && !this.canceler.isCompleted) { | 206 if ((this.canceler != null) && !this.canceler.isCompleted) { |
219 // If the stream has been cancelled, complete the cancellation future | 207 // If the stream has been cancelled, complete the cancellation future |
220 // with the error. | 208 // with the error. |
221 this.canceler.completeError(error, stackTrace); | 209 this.canceler.completeError(error, stackTrace); |
222 return; | 210 return; |
223 } | 211 } |
224 if (!this.controller.hasListener) return; | 212 if (!this.controller.hasListener) return; |
225 this.controller.addError(error, stackTrace); | 213 this.controller.addError(error, stackTrace); |
226 } | 214 } |
227 } | 215 } |
| 216 '''); |
228 | 217 |
229 /** Returns a Stream of T implemented by an async* function. */ | 218 /// Returns a Stream of T implemented by an async* function. */ |
230 function asyncStar(gen, T, ...args) { | 219 /// |
231 return new _AsyncStarStreamController(gen, T, args).controller.stream; | 220 asyncStar(gen, T, @rest args) => JS('', '''(() => { |
232 } | 221 return new _AsyncStarStreamController($gen, $T, $args).controller.stream; |
233 exports.asyncStar = asyncStar; | 222 })()'''); |
234 }); | |
OLD | NEW |