Debian Codegraph @

js/src/vm/AsyncIteration.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef vm_AsyncIteration_h
8 #define vm_AsyncIteration_h
9
10 #include "builtin/Promise.h" // js::PromiseHandler
11 #include "builtin/SelfHostingDefines.h"
12 #include "js/Class.h"
13 #include "vm/GeneratorObject.h"
14 #include "vm/JSObject.h"
15 #include "vm/List.h"
16 #include "vm/PromiseObject.h"
17
18 // [SMDOC] Async generators
19 //
20 // # Start
21 //
22 // When an async generator is called, it synchronously runs until the
23 // JSOp::InitialYield and then suspends, just like a sync generator, and returns
24 // an async generator object (js::AsyncGeneratorObject).
25 //
26 //
27 // # Request queue
28 //
29 // When next/return/throw is called on the async generator object,
30 // js::AsyncGeneratorEnqueue performs the following:
31 // * Create a new AsyncGeneratorRequest and enqueue it in the generator
32 // object's request queue.
33 // * Resume the generator with the oldest request, if the generator is
34 // suspended (see "Resume" section below)
35 // * Return the promise for the request
36 //
37 // This is done in js::AsyncGeneratorEnqueue, which corresponds to
38 // AsyncGeneratorEnqueue in the spec,
39 // and js::AsyncGeneratorResumeNext corresponds to the following:
40 // * AsyncGeneratorResolve
41 // * AsyncGeneratorReject
42 // * AsyncGeneratorResumeNext
43 //
44 // The returned promise is resolved when the resumption for the request
45 // completes with yield/throw/return, in js::AsyncGeneratorResolve and
46 // js::AsyncGeneratorReject.
47 // They correspond to AsyncGeneratorResolve and AsyncGeneratorReject in the
48 // spec.
49 //
50 //
51 // # Await
52 //
53 // Async generator's `await` is implemented differently than async function's
54 // `await`.
55 //
56 // The bytecode is the following:
57 // (ignoring CanSkipAwait; see the comment in AsyncFunction.h for more details)
58 //
59 // ```
60 // (operand here) # VALUE
61 // GetAliasedVar ".generator" # VALUE .generator
62 // Await 0 # RVAL GENERATOR RESUMEKIND
63 //
64 // AfterYield # RVAL GENERATOR RESUMEKIND
65 // CheckResumeKind # RVAL
66 // ```
67 //
68 // Async generators don't use JSOp::AsyncAwait, and that part is handled
69 // in js::AsyncGeneratorResume, and js::AsyncGeneratorAwait called there.
70 //
71 // Both JSOp::Await and JSOp::Yield behave in the exactly same way,
72 // and js::AsyncGeneratorResume checks the last opcode and branches for
73 // await/yield/return cases.
74 //
75 //
76 // # Reaction jobs and resume after await
77 //
78 // This is almost same as for async functions (see AsyncFunction.h).
79 //
80 // The reaction record for the job is marked as "this is for async generator"
81 // (see js::AsyncGeneratorAwait), and handled specially in
82 // js::PromiseReactionJob, which calls js::AsyncGeneratorPromiseReactionJob.
83 //
84 //
85 // # Yield
86 //
87 // `yield` is implemented with the following bytecode sequence:
88 // (Ignoring CanSkipAwait for simplicity)
89 //
90 // ```
91 // (operand here) # VALUE
92 // GetAliasedVar ".generator" # VALUE .generator
93 // Await 1 # RVAL GENERATOR RESUMEKIND
94 // AfterYield # RVAL GENERATOR RESUMEKIND
95 // CheckResumeKind # RVAL
96 //
97 // GetAliasedVar ".generator" # RVAL .generator
98 // Yield 2 # RVAL2 GENERATOR RESUMEKIND
99 //
100 // AfterYield # RVAL2 GENERATOR RESUMEKIND
101 // CheckResumeKind # RVAL2
102 // ```
103 //
104 // The 1st part (JSOp::Await + JSOp::CheckResumeKind) performs an implicit
105 // `await`, as specified in AsyncGeneratorYield step 5.
106 //
107 // AsyncGeneratorYield ( value )
108 // https://tc39.es/ecma262/#sec-asyncgeneratoryield
109 //
110 // 5. Set value to ? Await(value).
111 //
112 // The 2nd part (JSOp::Yield) suspends execution and yields the result of
113 // `await`, as specified in AsyncGeneratorYield steps 1-4, 6-7, 9-10.
114 //
115 // AsyncGeneratorYield ( value )
116 // https://tc39.es/ecma262/#sec-asyncgeneratoryield
117 //
118 // 1. Let genContext be the running execution context.
119 // 2. Assert: genContext is the execution context of a generator.
120 // 3. Let generator be the value of the Generator component of genContext.
121 // 4. Assert: GetGeneratorKind() is async.
122 // ..
123 // 6. Set generator.[[AsyncGeneratorState]] to suspendedYield.
124 // 7. Remove genContext from the execution context stack and restore the
125 // execution context that is at the top of the execution context stack as
126 // the running execution context.
127 // 8. ...
128 // 9. Return ! AsyncGeneratorResolve(generator, value, false).
129 // 10. NOTE: This returns to the evaluation of the operation that had most
130 // previously resumed evaluation of genContext.
131 //
132 // The last part (JSOp::CheckResumeKind) checks the resumption type and
133 // resumes/throws/returns the execution, as specified in AsyncGeneratorYield
134 // step 8.
135 //
136 // 8. Set the code evaluation state of genContext such that when evaluation is
137 // resumed with a Completion resumptionValue the following steps will be
138 // performed:
139 // a. If resumptionValue.[[Type]] is not return, return
140 // Completion(resumptionValue).
141 // b. Let awaited be Await(resumptionValue.[[Value]]).
142 // c. If awaited.[[Type]] is throw, return Completion(awaited).
143 // d. Assert: awaited.[[Type]] is normal.
144 // e. Return Completion { [[Type]]: return, [[Value]]: awaited.[[Value]],
145 // [[Target]]: empty }.
146 // f. NOTE: When one of the above steps returns, it returns to the
147 // evaluation of the YieldExpression production that originally called
148 // this abstract operation.
149 //
150 // Resumption with `AsyncGenerator.prototype.return` is handled differently.
151 // See "Resumption with return" section below.
152 //
153 //
154 // # Return
155 //
156 // `return` with operand is implemented with the following bytecode sequence:
157 // (Ignoring CanSkipAwait for simplicity)
158 //
159 // ```
160 // (operand here) # VALUE
161 // GetAliasedVar ".generator" # VALUE .generator
162 // Await 0 # RVAL GENERATOR RESUMEKIND
163 // AfterYield # RVAL GENERATOR RESUMEKIND
164 // CheckResumeKind # RVAL
165 //
166 // SetRval #
167 // GetAliasedVar ".generator" # .generator
168 // FinalYieldRval #
169 // ```
170 //
171 // The 1st part (JSOp::Await + JSOp::CheckResumeKind) performs implicit
172 // `await`, as specified in ReturnStatement's Evaluation step 3.
173 //
174 // ReturnStatement: return Expression;
175 // https://tc39.es/ecma262/#sec-return-statement-runtime-semantics-evaluation
176 //
177 // 3. If ! GetGeneratorKind() is async, set exprValue to ? Await(exprValue).
178 //
179 // And the 2nd part corresponds to AsyncGeneratorStart steps 5.a-e, 5.g.
180 //
181 // AsyncGeneratorStart ( generator, generatorBody )
182 // https://tc39.es/ecma262/#sec-asyncgeneratorstart
183 //
184 // 5. Set the code evaluation state of genContext such that when evaluation
185 // is resumed for that execution context the following steps will be
186 // performed:
187 // a. Let result be the result of evaluating generatorBody.
188 // b. Assert: If we return here, the async generator either threw an
189 // exception or performed either an implicit or explicit return.
190 // c. Remove genContext from the execution context stack and restore the
191 // execution context that is at the top of the execution context stack
192 // as the running execution context.
193 // d. Set generator.[[AsyncGeneratorState]] to completed.
194 // e. If result is a normal completion, let resultValue be undefined.
195 // ...
196 // g. Return ! AsyncGeneratorResolve(generator, resultValue, true).
197 //
198 // `return` without operand or implicit return is implicit with the following
199 // bytecode sequence:
200 //
201 // ```
202 // Undefined # undefined
203 // SetRval #
204 // GetAliasedVar ".generator" # .generator
205 // FinalYieldRval #
206 // ```
207 //
208 // This is also AsyncGeneratorStart steps 5.a-e, 5.g.
209 //
210 //
211 // # Throw
212 //
213 // Unlike async function, async generator doesn't use implicit try-catch,
214 // but the throw completion is handled by js::AsyncGeneratorResume,
215 // and js::AsyncGeneratorThrown is called there.
216 //
217 // 5. ...
218 // f. Else,
219 // i. Let resultValue be result.[[Value]].
220 // ii. If result.[[Type]] is not return, then
221 // 1. Return ! AsyncGeneratorReject(generator, resultValue).
222 //
223 //
224 // # Resumption with return
225 //
226 // Resumption with return completion is handled in js::AsyncGeneratorResumeNext.
227 //
228 // If the generator is suspended, it doesn't immediately resume the generator
229 // script itself, but handles implicit `await` it in
230 // js::AsyncGeneratorResumeNext.
231 // (See PromiseHandlerAsyncGeneratorYieldReturnAwaitedFulfilled and
232 // PromiseHandlerAsyncGeneratorYieldReturnAwaitedRejected), and resumes the
233 // generator with the result of await.
234 // And the return completion is finally handled in JSOp::CheckResumeKind
235 // after JSOp::Yield.
236 //
237 // This corresponds to AsyncGeneratorYield step 8.
238 //
239 // AsyncGeneratorYield ( value )
240 // https://tc39.es/ecma262/#sec-asyncgeneratoryield
241 //
242 // 8. Set the code evaluation state of genContext such that when evaluation
243 // is resumed with a Completion resumptionValue the following steps will
244 // be performed:
245 // ..
246 // b. Let awaited be Await(resumptionValue.[[Value]]).
247 // c. If awaited.[[Type]] is throw, return Completion(awaited).
248 // d. Assert: awaited.[[Type]] is normal.
249 // e. Return Completion { [[Type]]: return, [[Value]]: awaited.[[Value]],
250 // [[Target]]: empty }.
251 //
252 // If the generator is already completed, it awaits on the return value,
253 // (See PromiseHandlerAsyncGeneratorResumeNextReturnFulfilled and
254 // PromiseHandlerAsyncGeneratorResumeNextReturnRejected), and resolves the
255 // request's promise with the value.
256 //
257 // It corresponds to AsyncGeneratorResumeNext step 10.b.i.
258 //
259 // AsyncGeneratorResumeNext ( generator )
260 // https://tc39.es/ecma262/#sec-asyncgeneratorresumenext
261 //
262 // 10. If completion is an abrupt completion, then
263 // ..
264 // b. If state is completed, then
265 // i. If completion.[[Type]] is return, then
266 // 1. Set generator.[[AsyncGeneratorState]] to awaiting-return.
267 // 2. Let promise be ? PromiseResolve(%Promise%, completion.[[Value]]).
268 // 3. Let stepsFulfilled be the algorithm steps defined in
269 // AsyncGeneratorResumeNext Return Processor Fulfilled Functions.
270 // 4. Let onFulfilled be ! CreateBuiltinFunction(stepsFulfilled, «
271 // [[Generator]] »).
272 // 5. Set onFulfilled.[[Generator]] to generator.
273 // 6. Let stepsRejected be the algorithm steps defined in
274 // AsyncGeneratorResumeNext Return Processor Rejected Functions.
275 // 7. Let onRejected be ! CreateBuiltinFunction(stepsRejected, «
276 // [[Generator]] »).
277 // 8. Set onRejected.[[Generator]] to generator.
278 // 9. Perform ! PerformPromiseThen(promise, onFulfilled, onRejected).
279 // 10. Return undefined.
280 //
281
282 namespace js {
283
284 class AsyncGeneratorObject;
285 enum class CompletionKind : uint8_t;
286
287 extern const JSClass AsyncGeneratorFunctionClass;
288
289 [[nodiscard]] bool AsyncGeneratorPromiseReactionJob(
290 JSContext* cx, PromiseHandler handler,
291 Handle<AsyncGeneratorObject*> generator, HandleValue argument);
292
293 bool AsyncGeneratorNext(JSContext* cx, unsigned argc, Value* vp);
294 bool AsyncGeneratorReturn(JSContext* cx, unsigned argc, Value* vp);
295 bool AsyncGeneratorThrow(JSContext* cx, unsigned argc, Value* vp);
296
297 // AsyncGeneratorRequest record in the spec.
298 // Stores the info from AsyncGenerator#{next,return,throw}.
299 //
300 // This object is reused across multiple requests as an optimization, and
301 // stored in the Slot_CachedRequest slot.
302 class AsyncGeneratorRequest : public NativeObject {
303 private:
304 enum AsyncGeneratorRequestSlots {
305 // Int32 value with CompletionKind.
306 // Normal: next
307 // Return: return
308 // Throw: throw
309 Slot_CompletionKind = 0,
310
311 // The value passed to AsyncGenerator#{next,return,throw}.
312 Slot_CompletionValue,
313
314 // The promise returned by AsyncGenerator#{next,return,throw}.
315 Slot_Promise,
316
317 Slots,
318 };
319
320 void init(CompletionKind completionKind, const Value& completionValue,
321 PromiseObject* promise) {
322 setFixedSlot(Slot_CompletionKind,
323 Int32Value(static_cast<int32_t>(completionKind)));
324 setFixedSlot(Slot_CompletionValue, completionValue);
325 setFixedSlot(Slot_Promise, ObjectValue(*promise));
326 }
327
328 // Clear the request data for reuse.
329 void clearData() {
330 setFixedSlot(Slot_CompletionValue, NullValue());
331 setFixedSlot(Slot_Promise, NullValue());
332 }
333
334 friend AsyncGeneratorObject;
335
336 public:
337 static const JSClass class_;
338
339 static AsyncGeneratorRequest* create(JSContext* cx,
340 CompletionKind completionKind,
341 HandleValue completionValue,
342 Handle<PromiseObject*> promise);
343
344 CompletionKind completionKind() const {
345 return static_cast<CompletionKind>(
346 getFixedSlot(Slot_CompletionKind).toInt32());
347 }
348 JS::Value completionValue() const {
349 return getFixedSlot(Slot_CompletionValue);
350 }
351 PromiseObject* promise() const {
352 return &getFixedSlot(Slot_Promise).toObject().as<PromiseObject>();
353 }
354 };
355
356 class AsyncGeneratorObject : public AbstractGeneratorObject {
357 private:
358 enum AsyncGeneratorObjectSlots {
359 // Int32 value containing one of the |State| fields from below.
360 Slot_State = AbstractGeneratorObject::RESERVED_SLOTS,
361
362 // * null value if this async generator has no requests
363 // * AsyncGeneratorRequest if this async generator has only one request
364 // * list object if this async generator has 2 or more requests
365 Slot_QueueOrRequest,
366
367 // Cached AsyncGeneratorRequest for later use.
368 // undefined if there's no cache.
369 Slot_CachedRequest,
370
371 Slots
372 };
373
374 public:
375 enum State {
376 // "suspendedStart" in the spec.
377 // Suspended after invocation.
378 State_SuspendedStart,
379
380 // "suspendedYield" in the spec
381 // Suspended with `yield` expression.
382 State_SuspendedYield,
383
384 // "executing" in the spec.
385 // Resumed from initial suspend or yield, and either running the script
386 // or awaiting for `await` expression.
387 State_Executing,
388
389 // Part of "executing" in the spec.
390 // Awaiting on the value passed by AsyncGenerator#return which is called
391 // while executing.
392 State_AwaitingYieldReturn,
393
394 // "awaiting-return" in the spec.
395 // Awaiting on the value passed by AsyncGenerator#return which is called
396 // after completed.
397 State_AwaitingReturn,
398
399 // "completed" in the spec.
400 // The generator is completed.
401 State_Completed
402 };
403
404 State state() const {
405 return static_cast<State>(getFixedSlot(Slot_State).toInt32());
406 }
407 void setState(State state_) { setFixedSlot(Slot_State, Int32Value(state_)); }
408
409 private:
410 // Queue is implemented in 2 ways. If only one request is queued ever,
411 // request is stored directly to the slot. Once 2 requests are queued, a
412 // list is created and requests are appended into it, and the list is
413 // stored to the slot.
414
415 bool isSingleQueue() const {
416 return getFixedSlot(Slot_QueueOrRequest).isNull() ||
417 getFixedSlot(Slot_QueueOrRequest)
418 .toObject()
419 .is<AsyncGeneratorRequest>();
420 }
421 bool isSingleQueueEmpty() const {
422 return getFixedSlot(Slot_QueueOrRequest).isNull();
423 }
424 void setSingleQueueRequest(AsyncGeneratorRequest* request) {
425 setFixedSlot(Slot_QueueOrRequest, ObjectValue(*request));
426 }
427 void clearSingleQueueRequest() {
428 setFixedSlot(Slot_QueueOrRequest, NullValue());
429 }
430 AsyncGeneratorRequest* singleQueueRequest() const {
431 return &getFixedSlot(Slot_QueueOrRequest)
432 .toObject()
433 .as<AsyncGeneratorRequest>();
434 }
435
436 ListObject* queue() const {
437 return &getFixedSlot(Slot_QueueOrRequest).toObject().as<ListObject>();
438 }
439 void setQueue(ListObject* queue_) {
440 setFixedSlot(Slot_QueueOrRequest, ObjectValue(*queue_));
441 }
442
443 public:
444 static const JSClass class_;
445 static const JSClassOps classOps_;
446
447 static AsyncGeneratorObject* create(JSContext* cx, HandleFunction asyncGen);
448
449 bool isSuspendedStart() const { return state() == State_SuspendedStart; }
450 bool isSuspendedYield() const { return state() == State_SuspendedYield; }
451 bool isExecuting() const { return state() == State_Executing; }
452 bool isAwaitingYieldReturn() const {
453 return state() == State_AwaitingYieldReturn;
454 }
455 bool isAwaitingReturn() const { return state() == State_AwaitingReturn; }
456 bool isCompleted() const { return state() == State_Completed; }
457
458 void setSuspendedStart() { setState(State_SuspendedStart); }
459 void setSuspendedYield() { setState(State_SuspendedYield); }
460 void setExecuting() { setState(State_Executing); }
461 void setAwaitingYieldReturn() { setState(State_AwaitingYieldReturn); }
462 void setAwaitingReturn() { setState(State_AwaitingReturn); }
463 void setCompleted() { setState(State_Completed); }
464
465 [[nodiscard]] static bool enqueueRequest(
466 JSContext* cx, Handle<AsyncGeneratorObject*> generator,
467 Handle<AsyncGeneratorRequest*> request);
468
469 static AsyncGeneratorRequest* dequeueRequest(
470 JSContext* cx, Handle<AsyncGeneratorObject*> generator);
471
472 static AsyncGeneratorRequest* peekRequest(
473 Handle<AsyncGeneratorObject*> generator);
474
475 bool isQueueEmpty() const {
476 if (isSingleQueue()) {
477 return isSingleQueueEmpty();
478 }
479 return queue()->getDenseInitializedLength() == 0;
480 }
481
482 // This function does either of the following:
483 // * return a cached request object with the slots updated
484 // * create a new request object with the slots set
485 static AsyncGeneratorRequest* createRequest(
486 JSContext* cx, Handle<AsyncGeneratorObject*> generator,
487 CompletionKind completionKind, HandleValue completionValue,
488 Handle<PromiseObject*> promise);
489
490 // Stores the given request to the generator's cache after clearing its data
491 // slots. The cached request will be reused in the subsequent createRequest
492 // call.
493 void cacheRequest(AsyncGeneratorRequest* request) {
494 if (hasCachedRequest()) {
495 return;
496 }
497
498 request->clearData();
499 setFixedSlot(Slot_CachedRequest, ObjectValue(*request));
500 }
501
502 private:
503 bool hasCachedRequest() const {
504 return getFixedSlot(Slot_CachedRequest).isObject();
505 }
506
507 AsyncGeneratorRequest* takeCachedRequest() {
508 auto request = &getFixedSlot(Slot_CachedRequest)
509 .toObject()
510 .as<AsyncGeneratorRequest>();
511 clearCachedRequest();
512 return request;
513 }
514
515 void clearCachedRequest() { setFixedSlot(Slot_CachedRequest, NullValue()); }
516 };
517
518 JSObject* CreateAsyncFromSyncIterator(JSContext* cx, HandleObject iter,
519 HandleValue nextMethod);
520
521 class AsyncFromSyncIteratorObject : public NativeObject {
522 private:
523 enum AsyncFromSyncIteratorObjectSlots {
524 // Object that implements the sync iterator protocol.
525 Slot_Iterator = 0,
526
527 // The `next` property of the iterator object.
528 Slot_NextMethod = 1,
529
530 Slots
531 };
532
533 void init(JSObject* iterator, const Value& nextMethod) {
534 setFixedSlot(Slot_Iterator, ObjectValue(*iterator));
535 setFixedSlot(Slot_NextMethod, nextMethod);
536 }
537
538 public:
539 static const JSClass class_;
540
541 static JSObject* create(JSContext* cx, HandleObject iter,
542 HandleValue nextMethod);
543
544 JSObject* iterator() const { return &getFixedSlot(Slot_Iterator).toObject(); }
545
546 const Value& nextMethod() const { return getFixedSlot(Slot_NextMethod); }
547 };
548
549 class AsyncIteratorObject : public NativeObject {
550 public:
551 static const JSClass class_;
552 static const JSClass protoClass_;
553 };
554
555 // Iterator Helpers proposal
556 class AsyncIteratorHelperObject : public NativeObject {
557 public:
558 static const JSClass class_;
559
560 enum { GeneratorSlot, SlotCount };
561
562 static_assert(GeneratorSlot == ASYNC_ITERATOR_HELPER_GENERATOR_SLOT,
563 "GeneratorSlot must match self-hosting define for generator "
564 "object slot.");
565 };
566
567 AsyncIteratorHelperObject* NewAsyncIteratorHelper(JSContext* cx);
568
569 } // namespace js
570
571 #endif /* vm_AsyncIteration_h */