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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
|
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --harmony-async-iteration --allow-natives-syntax
let testFailed = false;
let testFailure;
function assertThrowsAsync(run, errorType, message) {
var actual;
var hadValue = false;
var hadError = false;
var promise = run();
if (typeof promise !== "object" || typeof promise.then !== "function") {
throw new MjsUnitAssertionError(
"Expected " + run.toString() +
" to return a Promise, but it returned " + PrettyPrint(promise));
}
promise.then(function(value) { hadValue = true; actual = value; },
function(error) { hadError = true; actual = error; });
assertFalse(hadValue || hadError);
%RunMicrotasks();
if (!hadError) {
throw new MjsUnitAssertionError(
"Expected " + run + "() to throw " + errorType.name +
", but did not throw.");
}
if (!(actual instanceof errorType))
throw new MjsUnitAssertionError(
"Expected " + run + "() to throw " + errorType.name +
", but threw '" + actual + "'");
if (message !== void 0 && actual.message !== message)
throw new MjsUnitAssertionError(
"Expected " + run + "() to throw '" + message + "', but threw '" +
actual.message + "'");
};
function resolveLater(value) {
return new Promise(function(resolve) {
Promise.resolve().then(function() {
resolve(value);
});
});
}
function rejectLater(value) {
return new Promise(function(resolve, reject) {
Promise.resolve().then(function() {
reject(value);
});
});
}
const kNext = 1;
const kThrow = 2;
const kReturn = 4;
const kNextThrows = kNext | 8;
const kReturnThrows = kReturn | 16;
const kThrowNormal = kThrow | 32;
const kNextUnchanged = kNext | 64;
const kReturnUnchanged = kReturn | 128;
const kThrowUnchanged = kThrow | 256;
function sync(array, features, log) {
// `log` is a required parameter
if (log === void 0) %AbortJS("`log` is undefined");
let i = 0;
let methods = {
next(sent) {
let done = i >= array.length;
let value = array[i];
log.push({ method: "next", sent, value, done });
if ((features & kNextThrows) === kNextThrows) throw sent;
if ((features & kNextUnchanged) === kNextUnchanged) return sent;
i++;
return { value, done };
},
throw(sent) {
let done = i >= array.length;
log.push({ method: "throw", sent, done });
if ((features & kThrowNormal) === kThrowNormal)
return { value: sent, done };
if ((features & kThrowUnchanged) === kThrowUnchanged) return sent;
throw sent;
},
return(sent) {
let done = true;
log.push({ method: "return", sent, done });
if ((features & kReturnThrows) === kReturnThrows) throw sent;
if ((features & kReturnUnchanged) === kReturnUnchanged) return sent;
return { value: sent, done };
}
};
return {
[Symbol.iterator]() { return this; },
next: (features & kNext) ? methods.next : undefined,
throw: (features & kThrow) ? methods.throw : undefined,
return: (features & kReturn) ? methods.return : undefined
};
}
class MyError extends Error {};
(async function AsyncFromSyncWithGenerator() {
function* gen() {
yield "sync value";
try {
yield new Promise(function(resolve) {
resolve("async value");
});
} catch (error) {
throw error;
}
assertUnreachable("generator is closed");
}
let iter = %CreateAsyncFromSyncIterator(gen());
// [Async-from-Sync Iterator] wraps sync iterator values in a Promise
let promise = iter.next();
assertInstanceof(promise, Promise);
let iter_result = await promise;
assertEquals({ value: "sync value", done: false }, iter_result);
// [Async-from-Sync Iterator] will wait for resolution of Promise values
promise = iter.next();
assertInstanceof(promise, Promise);
iter_result = await promise;
assertEquals({ value: "async value", done: false }, iter_result);
// [Async-from-Sync Iterator].throw delegates to .throw() method of sync
// iterator.
promise = iter.throw(new MyError("Error#1"));
assertInstanceof(promise, Promise);
try {
await promise;
assertUnreachable("promise should be rejected");
} catch (e) {
// If assertUnreachable failed, rethrow
if (e instanceof MjsUnitAssertionError) throw e;
assertInstanceof(e, MyError);
assertEquals("Error#1", e.message);
}
// Generator is closed, subsequent calls to .next() will not resume.
promise = iter.next("floof");
iter_result = await promise;
assertEquals({ value: undefined, done: true }, iter_result);
promise = iter.return("generator closed");
assertInstanceof(promise, Promise);
iter_result = await promise;
assertEquals({ value: "generator closed", done: true }, iter_result);
// .next(), .return() and .throw() delegate to sync iterator methods, without
// keeping track of the state of the generator.
promise = iter.next("unused");
assertInstanceof(promise, Promise);
iter_result = await promise;
assertEquals({ value: undefined, done: true }, iter_result);
promise = iter.throw(new MyError("Error#2"));
assertInstanceof(promise, Promise);
try {
await promise;
assertUnreachable("promise should be rejected");
} catch (e) {
// If assertUnreachable failed, rethrow
if (e instanceof MjsUnitAssertionError) throw e;
assertInstanceof(e, MyError);
assertEquals("Error#2", e.message);
}
promise = iter.return("return-after-completed");
assertInstanceof(promise, Promise);
iter_result = await promise;
assertEquals({ value: "return-after-completed", done: true }, iter_result);
})().catch(function(error) {
testFailed = true;
testFailure = error;
});
%RunMicrotasks();
if (testFailed) {
throw testFailure;
}
(async function AsyncFromSyncOrderOfOperations() {
let log = [];
iter = %CreateAsyncFromSyncIterator(sync(["sync-value"], 0, log));
try {
await iter.next();
assertUnreachable("Iterator.next() method is not optional");
} catch (e) {
assertInstanceof(e, TypeError);
assertEquals([], log);
}
log = [];
iter = %CreateAsyncFromSyncIterator(sync(["sync-value"], kNext, log));
assertEquals({ value: "sync-value", done: false }, await iter.next("a"));
assertEquals([
{
method: "next",
sent: "a",
value: "sync-value",
done: false
}
], log);
log = [];
let asyncValue = resolveLater("async-value");
iter = %CreateAsyncFromSyncIterator(sync([asyncValue], kNext, log));
assertEquals({ value: "async-value", done: false }, await iter.next("b"));
assertEquals([
{
method: "next",
sent: "b",
value: asyncValue,
done: false
}
], log);
// If [sync_iterator].next() produces a rejected Promise or an exception is
// thrown, Promise is rejected with thrown/rejected value.
log = [];
asyncValue = rejectLater("Boo!");
iter = %CreateAsyncFromSyncIterator(sync([asyncValue], kNext, log));
try {
await iter.next('c');
assertUnreachable('Expected `iter.next(\'c\') to throw, but did not throw');
} catch (e) {
assertEquals("Boo!", e);
assertEquals([
{
method: 'next',
sent: 'c',
value: asyncValue,
done: false
}
], log);
}
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'], kNextThrows, log));
try {
await iter.next('Boo!');
assertUnreachable('Expected `iter.next(\'c\') to throw, but did not throw');
} catch (e) {
assertEquals("Boo!", e);
assertEquals([
{
method: 'next',
sent: 'Boo!',
value: 'sync-value',
done: false
}
], log);
}
// [Async-from-Sync Iterator].next() will be rejected with a TypeError if
// Type([sync_iterator].next()) is not Object.
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'], kNextUnchanged,
log));
try {
await iter.next('not-a-JSReceiver');
assertUnreachable('Expected `iter.next(\'not-a-JSReceiver\')` to ' +
'throw, but did not throw')
} catch (e) {
assertEquals(e.constructor, TypeError);
}
assertEquals([
{
method: 'next',
sent: 'not-a-JSReceiver',
value: 'sync-value',
done: false
}
], log);
// If [sync_iterator] does not have a .return() method, return a Promise
// resolved with the value `{ value: <<sent value>>, done: true }`.
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-return'], kNext, log));
assertEquals({
value: 'd',
done: true
}, await iter.return('d'));
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({
value: 'sync-return',
done: false
}, await iter.next('e'));
assertEquals([
{
method: 'next',
sent: 'e',
value: 'sync-return',
done: false
}
], log);
// If [sync_iterator] does have a .return() method, return a Promise
// fulfilled with the iterator result of [sync_iterator].return().
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-return'],
kNext|kReturn, log));
assertEquals({
value: 'f',
done: true
}, await iter.return('f'));
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({
value: 'sync-return',
done: false
}, await iter.next('g'));
assertEquals([
{
method: 'return',
sent: 'f',
done: true
},
{
method: 'next',
sent: 'g',
value: 'sync-return',
done: false
}
], log);
// If [sync_iterator].return() produces a rejected Promise or an exception is
// thrown, Promise is rejected with thrown/rejected value.
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'], kNext|kReturnThrows,
log));
try {
await iter.return('Boo!!');
assertUnreachable('Expected `iter.return(\'Boo!!\')` to throw, but did ' +
'not throw');
} catch (e) {
assertEquals("Boo!!", e);
}
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({ value: 'sync-value', done: false }, await iter.next('h'));
assertEquals([
{
method: 'return',
sent: 'Boo!!',
done: true
},
{
method: 'next',
sent: 'h',
value: 'sync-value',
done: false
}
], log);
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'], kNext|kReturn, log));
let rejection = Promise.reject('Boo!!');
try {
await iter.return(rejection);
assertUnreachable('Expected `iter.return(Promise.reject(\'Boo!!\'))` to ' +
'throw, but did not throw');
} catch (e) {
assertEquals('Boo!!', e);
}
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({ value: 'sync-value', done: false }, await iter.next('i'));
assertEquals([
{
method: 'return',
sent: rejection,
done: true
},
{
method: 'next',
sent: 'i',
value: 'sync-value',
done: false
}
], log);
// [Async-from-Sync Iterator].return() will be rejected with a TypeError if
// Type([sync_iterator].return()) is not Object.
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'],
kNext|kReturnUnchanged, log));
try {
await iter.return('not-a-JSReceiver');
assertUnreachable('Expected `iter.return(\'not-a-JSReceiver\')` to ' +
'throw, but did not throw')
} catch (e) {
assertEquals(e.constructor, TypeError);
}
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({ value: 'sync-value', done: false }, await iter.next('j'));
assertEquals([
{
method: 'return',
sent: 'not-a-JSReceiver',
done: true
},
{
method: 'next',
sent: 'j',
value: 'sync-value',
done: false
}
], log);
// If [sync_iterator] does not have a .throw method, return a Promise rejected
// with the sent value.
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'], kNext, log));
try {
await iter.throw('Boo!!');
assertUnreachable('Expected iter.throw(\'Boo!!\') to throw, but did not ' +
'throw');
} catch (e) {
assertEquals('Boo!!', e);
}
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({ value: 'sync-value', done: false }, await iter.next('k'));
assertEquals([
{
method: 'next',
sent: 'k',
value: 'sync-value',
done: false
}
], log);
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'], kNext|kThrow, log));
try {
await iter.throw('Boo!!');
assertUnreachable('Expected iter.throw(\'Boo!!\') to throw, but did not ' +
'throw');
} catch (e) {
assertEquals('Boo!!', e);
}
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({ value: 'sync-value', done: false }, await iter.next('l'));
assertEquals([
{
method: 'throw',
sent: 'Boo!!',
done: false
},
{
method: 'next',
sent: 'l',
value: 'sync-value',
done: false
}
], log);
// If [sync_iterator].throw() returns a resolved Promise or a Completion
// with [[Type]] "normal" or "return", return a resolved Promise
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'], kNext|kThrowNormal,
log));
assertEquals({
value: 'Boo!!',
done: false
}, await iter.throw('Boo!!'));
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({ value: 'sync-value', done: false }, await iter.next('m'));
assertEquals([
{
method: 'throw',
sent: 'Boo!!',
done: false
},
{
method: 'next',
sent: 'm',
value: 'sync-value',
done: false
}
], log);
// [Async-from-Sync Iterator].throw() will be rejected with a TypeError if
// Type([sync_iterator].throw()) is not Object.
log = [];
iter = %CreateAsyncFromSyncIterator(sync(['sync-value'],
kNext|kThrowUnchanged, log));
try {
await iter.throw('not-a-JSReceiver');
assertUnreachable('Expected `iter.throw(\'not-a-JSReceiver\')` to ' +
'throw, but did not throw')
} catch (e) {
assertEquals(e.constructor, TypeError);
}
// [Async-from-Sync Iterator] merely delegates, and does not keep track of
// whether [sync_iterator] is completed or not.
assertEquals({ value: 'sync-value', done: false }, await iter.next('n'));
assertEquals([
{
method: 'throw',
sent: 'not-a-JSReceiver',
done: false
},
{
method: 'next',
sent: 'n',
value: 'sync-value',
done: false
}
], log);
// Let nextValue be IteratorValue(nextResult).
// IfAbruptRejectPromise(nextValue, promiseCapability).)
iter = %CreateAsyncFromSyncIterator({
next() { return { get value() { throw "BadValue!" }, done: false }; }
});
try {
await iter.next();
assertUnreachable('Expected `iter.next()` to throw, but did not throw');
} catch (e) {
assertEquals('BadValue!', e);
}
// Let nextDone be IteratorComplete(nextResult).
// IfAbruptRejectPromise(nextDone, promiseCapability).
iter = %CreateAsyncFromSyncIterator({
next() { return { value: undefined, get done() { throw "BadValue!" } }; }
});
try {
await iter.next();
assertUnreachable('Expected `iter.next()` to throw, but did not throw');
} catch (e) {
assertEquals('BadValue!', e);
}
// IfAbruptRejectPromise(returnResult, promiseCapability).
// Let returnValue be IteratorValue(returnResult).
iter = %CreateAsyncFromSyncIterator({
return() { return { get value() { throw "BadValue!" }, done: false }; }
});
try {
await iter.return();
assertUnreachable('Expected `iter.return()` to throw, but did not throw');
} catch (e) {
assertEquals('BadValue!', e);
}
// IfAbruptRejectPromise(returnValue, promiseCapability).
// Let returnDone be IteratorComplete(returnResult).
iter = %CreateAsyncFromSyncIterator({
return() { return { value: undefined, get done() { throw "BadValue!" } }; }
});
try {
await iter.return();
assertUnreachable('Expected `iter.return()` to throw, but did not throw');
} catch (e) {
assertEquals('BadValue!', e);
}
// IfAbruptRejectPromise(throwResult, promiseCapability).
// Let throwValue be IteratorValue(throwResult).
iter = %CreateAsyncFromSyncIterator({
throw() { return { get value() { throw "BadValue!" }, done: false }; }
});
try {
await iter.throw();
assertUnreachable('Expected `iter.throw()` to throw, but did not throw');
} catch (e) {
assertEquals('BadValue!', e);
}
// IfAbruptRejectPromise(throwValue, promiseCapability).
// Let throwDone be IteratorComplete(throwResult).
iter = %CreateAsyncFromSyncIterator({
throw() { return { value: undefined, get done() { throw "BadValue!" } }; }
});
try {
await iter.throw();
assertUnreachable('Expected `iter.throw()` to throw, but did not throw');
} catch (e) {
assertEquals('BadValue!', e);
}
})().catch(function(error) {
testFailed = true;
testFailure = error;
});
%RunMicrotasks();
if (testFailed) {
throw testFailure;
}
(function ExtractedAsyncFromSyncIteratorMethods() {
// Async-from-Sync iterator methods can be extracted via function.caller.
// TODO(caitp): test extracted `throw` method using yield* in async generator.
let extractor = [0, 1, 2, 3, 4,5,6,7,8,9];
let extractedNext;
let extractedReturn;
extractor[Symbol.iterator] = function() {
let it = [][Symbol.iterator].call(extractor);
let origNext = it.next, origThrow = it.throw, origReturn = it.return;
function extractNext() {
extractedNext = extractNext.caller;
return origNext;
}
function extractReturn() {
extractedReturn = extractReturn.caller;
return origReturn;
}
Object.defineProperties(it, {
"next": { get: extractNext, configurable: true },
"return": { get: extractReturn, configurable: true }
});
return it;
};
async function f() {
let i;
let it = extractor[Symbol.iterator]();
for await (let x of it) break;
for await (let x of it) return "x";
}
// Cycle through `f` to extract iterator methods
f().catch(function() { %AbortJS("No error should have occurred"); });
%RunMicrotasks();
assertEquals(typeof extractedNext, "function");
assertThrowsAsync(() => extractedNext.call(undefined), TypeError);
assertThrowsAsync(() => extractedNext.call(1), TypeError);
assertEquals(typeof extractedReturn, "function");
assertThrowsAsync(() => extractedReturn.call(undefined), TypeError);
assertThrowsAsync(() => extractedReturn.call(1), TypeError);
})();
|