1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use crate::{
builtins::{
iterable::{create_iter_result_object, IteratorRecord, IteratorResult},
promise::{if_abrupt_reject_promise, PromiseCapability},
BuiltInBuilder, IntrinsicObject, Promise,
},
context::intrinsics::Intrinsics,
native_function::NativeFunction,
object::{FunctionObjectBuilder, JsObject, ObjectData},
realm::Realm,
string::utf16,
Context, JsArgs, JsResult, JsValue,
};
use boa_gc::{Finalize, Trace};
use boa_profiler::Profiler;
/// `%AsyncFromSyncIteratorPrototype%` object.
///
/// More information:
/// - [ECMA reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-properties-of-async-from-sync-iterator-instances
#[derive(Clone, Debug, Finalize, Trace)]
pub struct AsyncFromSyncIterator {
// The [[SyncIteratorRecord]] internal slot.
sync_iterator_record: IteratorRecord,
}
impl IntrinsicObject for AsyncFromSyncIterator {
fn init(realm: &Realm) {
let _timer = Profiler::global().start_event("AsyncFromSyncIteratorPrototype", "init");
BuiltInBuilder::with_intrinsic::<Self>(realm)
.prototype(
realm
.intrinsics()
.objects()
.iterator_prototypes()
.async_iterator(),
)
.static_method(Self::next, "next", 1)
.static_method(Self::r#return, "return", 1)
.static_method(Self::throw, "throw", 1)
.build();
}
fn get(intrinsics: &Intrinsics) -> JsObject {
intrinsics
.objects()
.iterator_prototypes()
.async_from_sync_iterator()
}
}
impl AsyncFromSyncIterator {
/// `CreateAsyncFromSyncIterator ( syncIteratorRecord )`
///
/// More information:
/// - [ECMA reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-createasyncfromsynciterator
pub(crate) fn create(
sync_iterator_record: IteratorRecord,
context: &mut Context<'_>,
) -> IteratorRecord {
// 1. Let asyncIterator be OrdinaryObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »).
// 2. Set asyncIterator.[[SyncIteratorRecord]] to syncIteratorRecord.
let async_iterator = JsObject::from_proto_and_data_with_shared_shape(
context.root_shape(),
context
.intrinsics()
.objects()
.iterator_prototypes()
.async_from_sync_iterator(),
ObjectData::async_from_sync_iterator(Self {
sync_iterator_record,
}),
);
// 3. Let nextMethod be ! Get(asyncIterator, "next").
let next_method = async_iterator
.get(utf16!("next"), context)
.expect("async from sync iterator prototype must have next method");
// 4. Let iteratorRecord be the Iterator Record { [[Iterator]]: asyncIterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
// 5. Return iteratorRecord.
IteratorRecord::new(async_iterator, next_method)
}
/// `%AsyncFromSyncIteratorPrototype%.next ( [ value ] )`
///
/// More information:
/// - [ECMA reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-%asyncfromsynciteratorprototype%.next
fn next(this: &JsValue, args: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
// 1. Let O be the this value.
// 2. Assert: O is an Object that has a [[SyncIteratorRecord]] internal slot.
// 4. Let syncIteratorRecord be O.[[SyncIteratorRecord]].
let sync_iterator_record = this
.as_object()
.expect("async from sync iterator prototype must be object")
.borrow()
.as_async_from_sync_iterator()
.expect("async from sync iterator prototype must be object")
.sync_iterator_record
.clone();
// 3. Let promiseCapability be ! NewPromiseCapability(%Promise%).
let promise_capability = PromiseCapability::new(
&context.intrinsics().constructors().promise().constructor(),
context,
)
.expect("cannot fail with promise constructor");
// 5. If value is present, then
// a. Let result be Completion(IteratorNext(syncIteratorRecord, value)).
// 6. Else,
// a. Let result be Completion(IteratorNext(syncIteratorRecord)).
let iterator = sync_iterator_record.iterator().clone();
let next = sync_iterator_record.next_method();
let result = next
.call(
&iterator.into(),
args.get(0).map_or(&[], std::slice::from_ref),
context,
)
.and_then(IteratorResult::from_value);
// 7. IfAbruptRejectPromise(result, promiseCapability).
if_abrupt_reject_promise!(result, promise_capability, context);
// 8. Return AsyncFromSyncIteratorContinuation(result, promiseCapability).
Self::continuation(&result, &promise_capability, context)
}
/// `%AsyncFromSyncIteratorPrototype%.return ( [ value ] )`
///
/// More information:
/// - [ECMA reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-%asyncfromsynciteratorprototype%.return
fn r#return(this: &JsValue, args: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
// 1. Let O be the this value.
// 2. Assert: O is an Object that has a [[SyncIteratorRecord]] internal slot.
// 4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
let sync_iterator = this
.as_object()
.expect("async from sync iterator prototype must be object")
.borrow()
.as_async_from_sync_iterator()
.expect("async from sync iterator prototype must be object")
.sync_iterator_record
.iterator()
.clone();
// 3. Let promiseCapability be ! NewPromiseCapability(%Promise%).
let promise_capability = PromiseCapability::new(
&context.intrinsics().constructors().promise().constructor(),
context,
)
.expect("cannot fail with promise constructor");
// 5. Let return be Completion(GetMethod(syncIterator, "return")).
let r#return = sync_iterator.get_method(utf16!("return"), context);
// 6. IfAbruptRejectPromise(return, promiseCapability).
if_abrupt_reject_promise!(r#return, promise_capability, context);
let result = match (r#return, args.get(0)) {
// 7. If return is undefined, then
(None, _) => {
// a. Let iterResult be CreateIterResultObject(value, true).
let iter_result =
create_iter_result_object(args.get_or_undefined(0).clone(), true, context);
// b. Perform ! Call(promiseCapability.[[Resolve]], undefined, « iterResult »).
promise_capability
.resolve()
.call(&JsValue::Undefined, &[iter_result], context)
.expect("cannot fail according to spec");
// c. Return promiseCapability.[[Promise]].
return Ok(promise_capability.promise().clone().into());
}
// 8. If value is present, then
(Some(r#return), Some(value)) => {
// a. Let result be Completion(Call(return, syncIterator, « value »)).
r#return.call(&sync_iterator.clone().into(), &[value.clone()], context)
}
// 9. Else,
(Some(r#return), None) => {
// a. Let result be Completion(Call(return, syncIterator)).
r#return.call(&sync_iterator.clone().into(), &[], context)
}
};
// 11. If Type(result) is not Object, then
// a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
let result = result.and_then(IteratorResult::from_value);
// 10. IfAbruptRejectPromise(result, promiseCapability).
if_abrupt_reject_promise!(result, promise_capability, context);
// 12. Return AsyncFromSyncIteratorContinuation(result, promiseCapability).
Self::continuation(&result, &promise_capability, context)
}
/// `%AsyncFromSyncIteratorPrototype%.throw ( [ value ] )`
///
/// More information:
/// - [ECMA reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-%asyncfromsynciteratorprototype%.throw
fn throw(this: &JsValue, args: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
// 1. Let O be the this value.
// 2. Assert: O is an Object that has a [[SyncIteratorRecord]] internal slot.
// 4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
let sync_iterator = this
.as_object()
.expect("async from sync iterator prototype must be object")
.borrow()
.as_async_from_sync_iterator()
.expect("async from sync iterator prototype must be object")
.sync_iterator_record
.iterator()
.clone();
// 3. Let promiseCapability be ! NewPromiseCapability(%Promise%).
let promise_capability = PromiseCapability::new(
&context.intrinsics().constructors().promise().constructor(),
context,
)
.expect("cannot fail with promise constructor");
// 5. Let throw be Completion(GetMethod(syncIterator, "throw")).
let throw = sync_iterator.get_method(utf16!("throw"), context);
// 6. IfAbruptRejectPromise(throw, promiseCapability).
if_abrupt_reject_promise!(throw, promise_capability, context);
let result = match (throw, args.get(0)) {
// 7. If throw is undefined, then
(None, _) => {
// a. Perform ! Call(promiseCapability.[[Reject]], undefined, « value »).
promise_capability
.reject()
.call(
&JsValue::Undefined,
&[args.get_or_undefined(0).clone()],
context,
)
.expect("cannot fail according to spec");
// b. Return promiseCapability.[[Promise]].
return Ok(promise_capability.promise().clone().into());
}
// 8. If value is present, then
(Some(throw), Some(value)) => {
// a. Let result be Completion(Call(throw, syncIterator, « value »)).
throw.call(&sync_iterator.clone().into(), &[value.clone()], context)
}
// 9. Else,
(Some(throw), None) => {
// a. Let result be Completion(Call(throw, syncIterator)).
throw.call(&sync_iterator.clone().into(), &[], context)
}
};
// 11. If Type(result) is not Object, then
// a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
let result = result.and_then(IteratorResult::from_value);
// 10. IfAbruptRejectPromise(result, promiseCapability).
if_abrupt_reject_promise!(result, promise_capability, context);
// 12. Return AsyncFromSyncIteratorContinuation(result, promiseCapability).
Self::continuation(&result, &promise_capability, context)
}
/// `AsyncFromSyncIteratorContinuation ( result, promiseCapability )`
///
/// More information:
/// - [ECMA reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-asyncfromsynciteratorcontinuation
fn continuation(
result: &IteratorResult,
promise_capability: &PromiseCapability,
context: &mut Context<'_>,
) -> JsResult<JsValue> {
// 1. NOTE: Because promiseCapability is derived from the intrinsic %Promise%,
// the calls to promiseCapability.[[Reject]] entailed by the
// use IfAbruptRejectPromise below are guaranteed not to throw.
// 2. Let done be Completion(IteratorComplete(result)).
let done = result.complete(context);
// 3. IfAbruptRejectPromise(done, promiseCapability).
if_abrupt_reject_promise!(done, promise_capability, context);
// 4. Let value be Completion(IteratorValue(result)).
let value = result.value(context);
// 5. IfAbruptRejectPromise(value, promiseCapability).
if_abrupt_reject_promise!(value, promise_capability, context);
// 6. Let valueWrapper be Completion(PromiseResolve(%Promise%, value)).
let value_wrapper = Promise::promise_resolve(
&context.intrinsics().constructors().promise().constructor(),
value,
context,
);
// 7. IfAbruptRejectPromise(valueWrapper, promiseCapability).
if_abrupt_reject_promise!(value_wrapper, promise_capability, context);
// 8. Let unwrap be a new Abstract Closure with parameters (value)
// that captures done and performs the following steps when called:
// 9. Let onFulfilled be CreateBuiltinFunction(unwrap, 1, "", « »).
let on_fulfilled = FunctionObjectBuilder::new(
context,
NativeFunction::from_copy_closure(move |_this, args, context| {
// a. Return CreateIterResultObject(value, done).
Ok(create_iter_result_object(
args.get_or_undefined(0).clone(),
done,
context,
))
}),
)
.name("")
.length(1)
.build();
// 10. NOTE: onFulfilled is used when processing the "value" property of an
// IteratorResult object in order to wait for its value if it is a promise and
// re-package the result in a new "unwrapped" IteratorResult object.
// 11. Perform PerformPromiseThen(valueWrapper, onFulfilled, undefined, promiseCapability).
Promise::perform_promise_then(
&value_wrapper,
Some(on_fulfilled),
None,
Some(promise_capability.clone()),
context,
);
// 12. Return promiseCapability.[[Promise]].
Ok(promise_capability.promise().clone().into())
}
}