summaryrefslogtreecommitdiff
path: root/js/src/vm/AsyncIteration.h
blob: d3deb90b1a1f86a5ab9717155c51c784ef128ced (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef vm_AsyncIteration_h
#define vm_AsyncIteration_h

#include "jscntxt.h"
#include "jsobj.h"

#include "builtin/Promise.h"
#include "vm/GeneratorObject.h"

namespace js {

// Async generator consists of 2 functions, |wrapped| and |unwrapped|.
// |unwrapped| is a generator function compiled from async generator script,
// |await| behaves just like |yield| there.  |unwrapped| isn't exposed to user
// script.
// |wrapped| is a native function that is the value of async generator.

JSObject*
WrapAsyncGeneratorWithProto(JSContext* cx, HandleFunction unwrapped, HandleObject proto);

JSObject*
WrapAsyncGenerator(JSContext* cx, HandleFunction unwrapped);

bool
IsWrappedAsyncGenerator(JSFunction* fun);

JSFunction*
GetWrappedAsyncGenerator(JSFunction* unwrapped);

JSFunction*
GetUnwrappedAsyncGenerator(JSFunction* wrapped);

MOZ_MUST_USE bool
AsyncGeneratorAwaitedFulfilled(JSContext* cx, Handle<AsyncGeneratorObject*> asyncGenObj,
                               HandleValue value);
MOZ_MUST_USE bool
AsyncGeneratorAwaitedRejected(JSContext* cx, Handle<AsyncGeneratorObject*> asyncGenObj,
                              HandleValue reason);
MOZ_MUST_USE bool
AsyncGeneratorYieldReturnAwaitedFulfilled(JSContext* cx,
                                          Handle<AsyncGeneratorObject*> asyncGenObj,
                                          HandleValue value);
MOZ_MUST_USE bool
AsyncGeneratorYieldReturnAwaitedRejected(JSContext* cx,
                                         Handle<AsyncGeneratorObject*> asyncGenObj,
                                         HandleValue reason);

class AsyncGeneratorObject;

class AsyncGeneratorRequest : public NativeObject
{
  private:
    enum AsyncGeneratorRequestSlots {
        Slot_CompletionKind = 0,
        Slot_CompletionValue,
        Slot_Promise,
        Slots,
    };

    void init(CompletionKind completionKind, const Value& completionValue, PromiseObject* promise) {
        setFixedSlot(Slot_CompletionKind,
                     Int32Value(static_cast<int32_t>(completionKind)));
        setFixedSlot(Slot_CompletionValue, completionValue);
        setFixedSlot(Slot_Promise, ObjectValue(*promise));
    }

    void clearData() {
        setFixedSlot(Slot_CompletionValue, NullValue());
        setFixedSlot(Slot_Promise, NullValue());
    }

    friend AsyncGeneratorObject;

  public:
    static const Class class_;

    static AsyncGeneratorRequest* create(JSContext* cx, CompletionKind completionKind,
                                         HandleValue completionValue,
                                         Handle<PromiseObject*> promise);

    CompletionKind completionKind() const {
        return static_cast<CompletionKind>(getFixedSlot(Slot_CompletionKind).toInt32());
    }
    JS::Value completionValue() const {
        return getFixedSlot(Slot_CompletionValue);
    }
    PromiseObject* promise() const {
        return &getFixedSlot(Slot_Promise).toObject().as<PromiseObject>();
    }
};

class AsyncGeneratorObject : public NativeObject
{
  private:
    enum AsyncGeneratorObjectSlots {
        Slot_State = 0,
        Slot_Generator,
        Slot_QueueOrRequest,
        Slot_CachedRequest,
        Slots
    };

    enum State {
        State_SuspendedStart,
        State_SuspendedYield,
        State_Executing,
        // State_AwaitingYieldReturn corresponds to the case that
        // AsyncGenerator#return is called while State_Executing,
        // just like the case that AsyncGenerator#return is called
        // while State_Completed.
        State_AwaitingYieldReturn,
        State_AwaitingReturn,
        State_Completed
    };

    State state() const {
        return static_cast<State>(getFixedSlot(Slot_State).toInt32());
    }
    void setState(State state_) {
        setFixedSlot(Slot_State, Int32Value(state_));
    }

    void setGenerator(const Value& value) {
        setFixedSlot(Slot_Generator, value);
    }

    // Queue is implemented in 2 ways.  If only one request is queued ever,
    // request is stored directly to the slot.  Once 2 requests are queued, an
    // array is created and requests are pushed into it, and the array is
    // stored to the slot.

    bool isSingleQueue() const {
        return getFixedSlot(Slot_QueueOrRequest).isNull() ||
               getFixedSlot(Slot_QueueOrRequest).toObject().is<AsyncGeneratorRequest>();
    }
    bool isSingleQueueEmpty() const {
        return getFixedSlot(Slot_QueueOrRequest).isNull();
    }
    void setSingleQueueRequest(AsyncGeneratorRequest* request) {
        setFixedSlot(Slot_QueueOrRequest, ObjectValue(*request));
    }
    void clearSingleQueueRequest() {
        setFixedSlot(Slot_QueueOrRequest, NullValue());
    }
    AsyncGeneratorRequest* singleQueueRequest() const {
        return &getFixedSlot(Slot_QueueOrRequest).toObject().as<AsyncGeneratorRequest>();
    }

    ArrayObject* queue() const {
        return &getFixedSlot(Slot_QueueOrRequest).toObject().as<ArrayObject>();
    }
    void setQueue(JSObject* queue_) {
        setFixedSlot(Slot_QueueOrRequest, ObjectValue(*queue_));
    }

  public:
    static const Class class_;

    static AsyncGeneratorObject*
    create(JSContext* cx, HandleFunction asyncGen, HandleValue generatorVal);

    bool isSuspendedStart() const {
        return state() == State_SuspendedStart;
    }
    bool isSuspendedYield() const {
        return state() == State_SuspendedYield;
    }
    bool isExecuting() const {
        return state() == State_Executing;
    }
    bool isAwaitingYieldReturn() const {
        return state() == State_AwaitingYieldReturn;
    }
    bool isAwaitingReturn() const {
        return state() == State_AwaitingReturn;
    }
    bool isCompleted() const {
        return state() == State_Completed;
    }

    void setSuspendedStart() {
        setState(State_SuspendedStart);
    }
    void setSuspendedYield() {
        setState(State_SuspendedYield);
    }
    void setExecuting() {
        setState(State_Executing);
    }
    void setAwaitingYieldReturn() {
        setState(State_AwaitingYieldReturn);
    }
    void setAwaitingReturn() {
        setState(State_AwaitingReturn);
    }
    void setCompleted() {
        setState(State_Completed);
    }

    JS::Value generatorVal() const {
        return getFixedSlot(Slot_Generator);
    }
    GeneratorObject* generatorObj() const {
        return &getFixedSlot(Slot_Generator).toObject().as<GeneratorObject>();
    }

    static MOZ_MUST_USE bool
    enqueueRequest(JSContext* cx, Handle<AsyncGeneratorObject*> asyncGenObj,
                   Handle<AsyncGeneratorRequest*> request);

    static AsyncGeneratorRequest*
    dequeueRequest(JSContext* cx, Handle<AsyncGeneratorObject*> asyncGenObj);

    static AsyncGeneratorRequest*
    peekRequest(JSContext* cx, Handle<AsyncGeneratorObject*> asyncGenObj);

    bool isQueueEmpty() const {
        if (isSingleQueue())
            return isSingleQueueEmpty();
        return queue()->length() == 0;
    }

    // This function does either of the following:
    //   * return a cached request object with the slots updated
    //   * create a new request object with the slots set
    static AsyncGeneratorRequest* createRequest(JSContext* cx,
                                                Handle<AsyncGeneratorObject*> asyncGenObj,
                                                CompletionKind completionKind,
                                                HandleValue completionValue,
                                                Handle<PromiseObject*> promise);

    // Stores the given request to the generator's cache after clearing its data
    // slots.  The cached request will be reused in the subsequent createRequest
    // call.
    void cacheRequest(AsyncGeneratorRequest* request) {
        if (hasCachedRequest())
            return;

        request->clearData();
        setFixedSlot(Slot_CachedRequest, ObjectValue(*request));
    }

  private:
    bool hasCachedRequest() const {
        return getFixedSlot(Slot_CachedRequest).isObject();
    }

    AsyncGeneratorRequest* takeCachedRequest() {
        auto request = &getFixedSlot(Slot_CachedRequest).toObject().as<AsyncGeneratorRequest>();
        clearCachedRequest();
        return request;
    }

    void clearCachedRequest() {
        setFixedSlot(Slot_CachedRequest, NullValue());
    }
};

JSObject*
CreateAsyncFromSyncIterator(JSContext* cx, HandleObject iter);

class AsyncFromSyncIteratorObject : public NativeObject
{
  private:
    enum AsyncFromSyncIteratorObjectSlots {
        Slot_Iterator = 0,
        Slots
    };

    void setIterator(HandleObject iterator_) {
        setFixedSlot(Slot_Iterator, ObjectValue(*iterator_));
    }

  public:
    static const Class class_;

    static JSObject*
    create(JSContext* cx, HandleObject iter);

    JSObject* iterator() const {
        return &getFixedSlot(Slot_Iterator).toObject();
    }
};

MOZ_MUST_USE bool
AsyncGeneratorResume(JSContext* cx, Handle<AsyncGeneratorObject*> asyncGenObj,
                     CompletionKind completionKind, HandleValue argument);

} // namespace js

#endif /* vm_AsyncIteration_h */