• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ecmascript/builtins/builtins_promise_handler.h"
17 
18 #include "ecmascript/global_env.h"
19 #include "ecmascript/interpreter/interpreter.h"
20 #include "ecmascript/jobs/micro_job_queue.h"
21 #include "ecmascript/js_array.h"
22 #include "ecmascript/js_async_function.h"
23 #include "ecmascript/js_handle.h"
24 #include "ecmascript/js_promise.h"
25 #include "ecmascript/js_tagged_value-inl.h"
26 #include "ecmascript/mem/assert_scope.h"
27 
28 namespace panda::ecmascript::builtins {
29 // es6 25.4.1.3.2 Promise Resolve Functions
Resolve(EcmaRuntimeCallInfo * argv)30 JSTaggedValue BuiltinsPromiseHandler::Resolve(EcmaRuntimeCallInfo *argv)
31 {
32     ASSERT(argv);
33     BUILTINS_API_TRACE(argv->GetThread(), PromiseHandler, Resolve);
34     JSThread *thread = argv->GetThread();
35     [[maybe_unused]] EcmaHandleScope handleScope(thread);
36     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
37     auto ecmaVm = thread->GetEcmaVM();
38     JSHandle<GlobalEnv> env = ecmaVm->GetGlobalEnv();
39 
40     // 1. Assert: F has a [[Promise]] internal slot whose value is an Object.
41     JSHandle<JSPromiseReactionsFunction> resolve = JSHandle<JSPromiseReactionsFunction>::Cast(GetConstructor(argv));
42     ASSERT_PRINT(resolve->GetPromise().IsECMAObject(), "Resolve: promise must be js object");
43 
44     // 2. Let promise be the value of F's [[Promise]] internal slot.
45     // 3. Let alreadyResolved be the value of F's [[AlreadyResolved]] internal slot.
46     // 4. If alreadyResolved.[[value]] is true, return undefined.
47     // 5. Set alreadyResolved.[[value]] to true.
48     JSHandle<JSPromise> resolvePromise(thread, resolve->GetPromise());
49     JSHandle<PromiseRecord> alreadyResolved(thread, resolve->GetAlreadyResolved());
50     if (alreadyResolved->GetValue().IsTrue()) {
51         return JSTaggedValue::Undefined();
52     }
53     alreadyResolved->SetValue(thread, JSTaggedValue::True());
54 
55     // 6. If SameValue(resolution, promise) is true, then
56     //     a. Let selfResolutionError be a newly created TypeError object.
57     //     b. Return RejectPromise(promise, selfResolutionError).
58     JSHandle<JSTaggedValue> resolution = BuiltinsBase::GetCallArg(argv, 0);
59     if (JSTaggedValue::SameValue(resolution.GetTaggedValue(), resolvePromise.GetTaggedValue())) {
60         JSHandle<JSObject> resolutionError =
61             factory->GetJSError(ErrorType::TYPE_ERROR, "Resolve: The promise and resolution cannot be the same.");
62         JSPromise::RejectPromise(thread, resolvePromise, JSHandle<JSTaggedValue>::Cast(resolutionError));
63         return JSTaggedValue::Undefined();
64     }
65     // 7. If Type(resolution) is not Object, then
66     //     a. Return FulfillPromise(promise, resolution).
67     if (!resolution.GetTaggedValue().IsECMAObject()) {
68         JSPromise::FulfillPromise(thread, resolvePromise, resolution);
69         return JSTaggedValue::Undefined();
70     }
71     // 8. Let then be Get(resolution, "then").
72     // 9. If then is an abrupt completion, then
73     //     a. Return RejectPromise(promise, then.[[value]]).
74     JSHandle<JSTaggedValue> thenKey(thread->GlobalConstants()->GetHandledPromiseThenString());
75     JSHandle<JSTaggedValue> thenValue = JSObject::GetProperty(thread, resolution, thenKey).GetValue();
76     if (thread->HasPendingException()) {
77         if (!thenValue->IsJSError()) {
78             thenValue = JSHandle<JSTaggedValue>(thread, thread->GetException());
79         }
80         thread->ClearException();
81         return JSPromise::RejectPromise(thread, resolvePromise, thenValue);
82     }
83     // 10. Let thenAction be then.[[value]].
84     // 11. If IsCallable(thenAction) is false, then
85     //     a. Return FulfillPromise(promise, resolution).
86     if (!thenValue->IsCallable()) {
87         JSPromise::FulfillPromise(thread, resolvePromise, resolution);
88         return JSTaggedValue::Undefined();
89     }
90     // 12. Perform EnqueueJob ("PromiseJobs", PromiseResolveThenableJob, «promise, resolution, thenAction»)
91     JSHandle<TaggedArray> arguments = factory->NewTaggedArray(3);  // 3: 3 means three args stored in array
92     arguments->Set(thread, 0, resolvePromise);
93     arguments->Set(thread, 1, resolution);
94     arguments->Set(thread, 2, thenValue);  // 2: 2 means index of array is 2
95 
96     JSHandle<JSFunction> promiseResolveThenableJob(env->GetPromiseResolveThenableJob());
97     JSHandle<job::MicroJobQueue> job = thread->GetCurrentEcmaContext()->GetMicroJobQueue();
98     job::MicroJobQueue::EnqueueJob(thread, job, job::QueueType::QUEUE_PROMISE, promiseResolveThenableJob, arguments);
99 
100     // 13. Return undefined.
101     return JSTaggedValue::Undefined();
102 }
103 
104 // es6 25.4.1.3.1 Promise Reject Functions
Reject(EcmaRuntimeCallInfo * argv)105 JSTaggedValue BuiltinsPromiseHandler::Reject(EcmaRuntimeCallInfo *argv)
106 {
107     ASSERT(argv);
108     BUILTINS_API_TRACE(argv->GetThread(), PromiseHandler, Reject);
109     JSThread *thread = argv->GetThread();
110     [[maybe_unused]] EcmaHandleScope handleScope(thread);
111 
112     // 1. Assert: F has a [[Promise]] internal slot whose value is an Object.
113     JSHandle<JSPromiseReactionsFunction> reject = JSHandle<JSPromiseReactionsFunction>::Cast(GetConstructor(argv));
114     ASSERT_PRINT(reject->GetPromise().IsECMAObject(), "Reject: promise must be js object");
115 
116     // 2. Let promise be the value of F's [[Promise]] internal slot.
117     // 3. Let alreadyResolved be the value of F's [[AlreadyResolved]] internal slot.
118     // 4. If alreadyResolved.[[value]] is true, return undefined.
119     // 5. Set alreadyResolved.[[value]] to true.
120     JSHandle<JSPromise> rejectPromise(thread, reject->GetPromise());
121     JSHandle<PromiseRecord> alreadyResolved(thread, reject->GetAlreadyResolved());
122     if (alreadyResolved->GetValue().IsTrue()) {
123         return JSTaggedValue::Undefined();
124     }
125     alreadyResolved->SetValue(thread, JSTaggedValue::True());
126 
127     // 6. Return RejectPromise(promise, reason).
128     JSHandle<JSTaggedValue> reason = GetCallArg(argv, 0);
129     JSHandle<JSTaggedValue> result(thread, JSPromise::RejectPromise(thread, rejectPromise, reason));
130     return result.GetTaggedValue();
131 }
132 
133 // es6 25.4.1.5.1 GetCapabilitiesExecutor Functions
Executor(EcmaRuntimeCallInfo * argv)134 JSTaggedValue BuiltinsPromiseHandler::Executor(EcmaRuntimeCallInfo *argv)
135 {
136     ASSERT(argv);
137     BUILTINS_API_TRACE(argv->GetThread(), PromiseHandler, Executor);
138     JSThread *thread = argv->GetThread();
139     [[maybe_unused]] EcmaHandleScope handleScope(thread);
140 
141     // 1. Assert: F has a [[Capability]] internal slot whose value is a PromiseCapability Record.
142     JSHandle<JSPromiseExecutorFunction> executor = JSHandle<JSPromiseExecutorFunction>::Cast(GetConstructor(argv));
143     ASSERT_PRINT(executor->GetCapability().IsRecord(),
144                  "Executor: F has a [[Capability]] internal slot whose value is a PromiseCapability Record.");
145 
146     // 2. Let promiseCapability be the value of F's [[Capability]] internal slot.
147     // 3. If promiseCapability.[[Resolve]] is not undefined, throw a TypeError exception.
148     JSHandle<PromiseCapability> promiseCapability(thread, executor->GetCapability());
149     if (!promiseCapability->GetResolve().IsUndefined()) {
150         THROW_TYPE_ERROR_AND_RETURN(thread, "Executor: resolve should be undefine!", JSTaggedValue::Undefined());
151     }
152     // 4. If promiseCapability.[[Reject]] is not undefined, throw a TypeError exception.
153     if (!promiseCapability->GetReject().IsUndefined()) {
154         THROW_TYPE_ERROR_AND_RETURN(thread, "Executor: reject should be undefine!", JSTaggedValue::Undefined());
155     }
156     // 5. Set promiseCapability.[[Resolve]] to resolve.
157     // 6. Set promiseCapability.[[Reject]] to reject.
158     JSHandle<JSTaggedValue> resolve = GetCallArg(argv, 0);
159     JSHandle<JSTaggedValue> reject = GetCallArg(argv, 1);
160     promiseCapability->SetResolve(thread, resolve);
161     promiseCapability->SetReject(thread, reject);
162     // 7. Return undefined.
163     return JSTaggedValue::Undefined();
164 }
165 
166 // es6 25.4.4.1.2 Promise.all Resolve Element Functions
ResolveElementFunction(EcmaRuntimeCallInfo * argv)167 JSTaggedValue BuiltinsPromiseHandler::ResolveElementFunction(EcmaRuntimeCallInfo *argv)
168 {
169     ASSERT(argv);
170     BUILTINS_API_TRACE(argv->GetThread(), PromiseHandler, ResolveElementFunction);
171     JSThread *thread = argv->GetThread();
172     [[maybe_unused]] EcmaHandleScope handleScope(thread);
173     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
174     JSHandle<JSPromiseAllResolveElementFunction> func =
175         JSHandle<JSPromiseAllResolveElementFunction>::Cast(GetConstructor(argv));
176     // 1. Let alreadyCalled be the value of F's [[AlreadyCalled]] internal slot.
177     JSHandle<PromiseRecord> alreadyCalled =
178         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, func->GetAlreadyCalled()));
179     // 2. If alreadyCalled.[[value]] is true, return undefined.
180     if (alreadyCalled->GetValue().IsTrue()) {
181         return JSTaggedValue::Undefined();
182     }
183     // 3. Set alreadyCalled.[[value]] to true.
184     alreadyCalled->SetValue(thread, JSTaggedValue::True());
185     // 4. Let index be the value of F's [[Index]] internal slot.
186     JSHandle<JSTaggedValue> index(thread, func->GetIndex());
187     // 5. Let values be the value of F's [[Values]] internal slot.
188     JSHandle<PromiseRecord> values = JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, func->GetValues()));
189     // 6. Let promiseCapability be the value of F's [[Capabilities]] internal slot.
190     JSHandle<PromiseCapability> capa =
191         JSHandle<PromiseCapability>::Cast(JSHandle<JSTaggedValue>(thread, func->GetCapabilities()));
192     // 7. Let remainingElementsCount be the value of F's [[RemainingElements]] internal slot.
193     JSHandle<PromiseRecord> remainCnt =
194         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, func->GetRemainingElements()));
195     // 8. Set values[index] to x.
196     JSHandle<TaggedArray> arrayValues =
197         JSHandle<TaggedArray>::Cast(JSHandle<JSTaggedValue>(thread, values->GetValue()));
198     arrayValues->Set(thread, JSTaggedValue::ToUint32(thread, index), GetCallArg(argv, 0).GetTaggedValue());
199     // 9. Set remainingElementsCount.[[value]] to remainingElementsCount.[[value]] - 1.
200     remainCnt->SetValue(thread, --JSTaggedNumber(remainCnt->GetValue()));
201     // 10. If remainingElementsCount.[[value]] is 0,
202     if (remainCnt->GetValue().IsZero()) {
203         // a. Let valuesArray be CreateArrayFromList(values).
204         JSHandle<JSArray> jsArrayValues = JSArray::CreateArrayFromList(thread, arrayValues);
205         // b. Return Call(promiseCapability.[[Resolve]], undefined, «valuesArray»).
206         JSHandle<JSTaggedValue> capaResolve(thread, capa->GetResolve());
207         JSHandle<JSTaggedValue> undefined = globalConst->GetHandledUndefined();
208         EcmaRuntimeCallInfo *info =
209             EcmaInterpreter::NewRuntimeCallInfo(thread, capaResolve, undefined, undefined, 1);
210         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
211         info->SetCallArg(jsArrayValues.GetTaggedValue());
212         return JSFunction::Call(info);
213     }
214     // 11. Return undefined.
215     return JSTaggedValue::Undefined();
216 }
217 
AsyncAwaitFulfilled(EcmaRuntimeCallInfo * argv)218 JSTaggedValue BuiltinsPromiseHandler::AsyncAwaitFulfilled(EcmaRuntimeCallInfo *argv)
219 {
220     ASSERT(argv);
221     BUILTINS_API_TRACE(argv->GetThread(), PromiseHandler, AsyncAwaitFulfilled);
222     [[maybe_unused]] EcmaHandleScope handleScope(argv->GetThread());
223 
224     JSHandle<JSTaggedValue> value = GetCallArg(argv, 0);
225     JSHandle<JSAsyncAwaitStatusFunction> func(GetConstructor(argv));
226     return JSAsyncAwaitStatusFunction::AsyncFunctionAwaitFulfilled(argv->GetThread(), func, value).GetTaggedValue();
227 }
228 
AsyncAwaitRejected(EcmaRuntimeCallInfo * argv)229 JSTaggedValue BuiltinsPromiseHandler::AsyncAwaitRejected(EcmaRuntimeCallInfo *argv)
230 {
231     ASSERT(argv);
232     BUILTINS_API_TRACE(argv->GetThread(), PromiseHandler, AsyncAwaitRejected);
233     [[maybe_unused]] EcmaHandleScope handleScope(argv->GetThread());
234 
235     JSHandle<JSTaggedValue> reason = GetCallArg(argv, 0);
236     JSHandle<JSAsyncAwaitStatusFunction> func(GetConstructor(argv));
237     return JSAsyncAwaitStatusFunction::AsyncFunctionAwaitRejected(argv->GetThread(), func, reason).GetTaggedValue();
238 }
239 
valueThunkFunction(EcmaRuntimeCallInfo * argv)240 JSTaggedValue BuiltinsPromiseHandler::valueThunkFunction(EcmaRuntimeCallInfo *argv)
241 {
242     BUILTINS_API_TRACE(argv->GetThread(), PromiseHandler, valueThunkFunction);
243     JSHandle<JSPromiseValueThunkOrThrowerFunction> valueThunk =
244         JSHandle<JSPromiseValueThunkOrThrowerFunction>::Cast(GetConstructor(argv));
245     return valueThunk->GetResult();
246 }
247 
throwerFunction(EcmaRuntimeCallInfo * argv)248 JSTaggedValue BuiltinsPromiseHandler::throwerFunction(EcmaRuntimeCallInfo *argv)
249 {
250     JSThread *thread = argv->GetThread();
251     BUILTINS_API_TRACE(thread, PromiseHandler, throwerFunction);
252     JSHandle<JSPromiseValueThunkOrThrowerFunction> thrower =
253         JSHandle<JSPromiseValueThunkOrThrowerFunction>::Cast(GetConstructor(argv));
254     JSTaggedValue undefined = thread->GlobalConstants()->GetUndefined();
255     THROW_NEW_ERROR_AND_RETURN_VALUE(thread, thrower->GetResult(), undefined);
256 }
257 
ThenFinally(EcmaRuntimeCallInfo * argv)258 JSTaggedValue BuiltinsPromiseHandler::ThenFinally(EcmaRuntimeCallInfo *argv)
259 {
260     // 1. Let F be the active function object.
261     JSThread *thread = argv->GetThread();
262     BUILTINS_API_TRACE(thread, PromiseHandler, ThenFinally);
263     auto ecmaVm = thread->GetEcmaVM();
264     ObjectFactory *factory = ecmaVm->GetFactory();
265     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
266     JSHandle<JSPromiseFinallyFunction> thenFinally(GetConstructor(argv));
267     JSHandle<JSTaggedValue> value = BuiltinsBase::GetCallArg(argv, 0);
268     // 2. Let onFinally be F.[[OnFinally]].
269     // 3. Assert: IsCallable(onFinally) is true.
270     JSHandle<JSTaggedValue> onFinally(thread, thenFinally->GetOnFinally());
271     ASSERT_PRINT(onFinally->IsCallable(), "onFinally is not callable");
272     // 4. Let result be ? Call(onFinally, undefined).
273     JSHandle<JSTaggedValue> undefined = globalConst->GetHandledUndefined();
274     EcmaRuntimeCallInfo *taggedInfo =
275         EcmaInterpreter::NewRuntimeCallInfo(thread, onFinally, undefined, undefined, 0);
276     JSTaggedValue result = JSFunction::Call(taggedInfo);
277     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
278     JSHandle<JSTaggedValue> resultHandle(thread, result);
279     // 5. Let C be F.[[Constructor]].
280     // 6. Assert: IsConstructor(C) is true.
281     JSHandle<JSTaggedValue> thenFinallyConstructor(thread, thenFinally->GetConstructor());
282     ASSERT_PRINT(thenFinallyConstructor->IsConstructor(), "thenFinallyConstructor is not constructor");
283     // 7. Let promise be ? PromiseResolve(C, result).
284     JSHandle<JSTaggedValue> promiseHandle =
285         BuiltinsPromiseHandler::PromiseResolve(thread, thenFinallyConstructor, resultHandle);
286     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
287     // 8. Let valueThunk be equivalent to a function that returns value.
288     JSHandle<JSPromiseValueThunkOrThrowerFunction> valueThunk =
289         factory->NewJSPromiseValueThunkFunction();
290     valueThunk->SetResult(thread, value);
291     JSHandle<JSTaggedValue> thenKey(globalConst->GetHandledPromiseThenString());
292     EcmaRuntimeCallInfo *invokeInfo =
293         EcmaInterpreter::NewRuntimeCallInfo(thread, undefined, promiseHandle, undefined, 1);
294     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
295     invokeInfo->SetCallArg(valueThunk.GetTaggedValue());
296     // 9. Return ? Invoke(promise, "then", « valueThunk »).
297     return JSFunction::Invoke(invokeInfo, thenKey);
298 }
299 
CatchFinally(EcmaRuntimeCallInfo * argv)300 JSTaggedValue BuiltinsPromiseHandler::CatchFinally(EcmaRuntimeCallInfo *argv)
301 {
302     // 1. Let F be the active function object.
303     JSThread *thread = argv->GetThread();
304     BUILTINS_API_TRACE(thread, PromiseHandler, CatchFinally);
305     auto ecmaVm = thread->GetEcmaVM();
306     ObjectFactory *factory = ecmaVm->GetFactory();
307     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
308     JSHandle<JSPromiseFinallyFunction> catchFinally(GetConstructor(argv));
309     // 2. Let onFinally be F.[[OnFinally]].
310     // 3. Assert: IsCallable(onFinally) is true.
311     JSHandle<JSTaggedValue> onFinally(thread, catchFinally->GetOnFinally());
312     ASSERT_PRINT(onFinally->IsCallable(), "thenOnFinally is not callable");
313     // 4. Let result be ? Call(onFinally, undefined).
314     JSHandle<JSTaggedValue> undefined = globalConst->GetHandledUndefined();
315     EcmaRuntimeCallInfo *info =
316         EcmaInterpreter::NewRuntimeCallInfo(thread, onFinally, undefined, undefined, 0);
317     JSTaggedValue result = JSFunction::Call(info);
318     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
319     JSHandle<JSTaggedValue> resultHandle(thread, result);
320     // 5. Let C be F.[[Constructor]].
321     // 6. Assert: IsConstructor(C) is true.
322     JSHandle<JSTaggedValue> catchFinallyConstructor(thread, catchFinally->GetConstructor());
323     ASSERT_PRINT(catchFinallyConstructor->IsConstructor(), "catchFinallyConstructor is not constructor");
324     // 7. Let promise be ? PromiseResolve(C, result).
325     JSHandle<JSTaggedValue> promiseHandle =
326         BuiltinsPromiseHandler::PromiseResolve(thread, catchFinallyConstructor, resultHandle);
327     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
328     // 8. Let thrower be equivalent to a function that throws reason.
329     JSHandle<JSTaggedValue> reason = BuiltinsBase::GetCallArg(argv, 0);
330     JSHandle<JSTaggedValue> thenKey(globalConst->GetHandledPromiseThenString());
331     JSHandle<JSPromiseValueThunkOrThrowerFunction> thrower =
332         factory->NewJSPromiseThrowerFunction();
333     thrower->SetResult(thread, reason);
334     EcmaRuntimeCallInfo *invokeInfo =
335         EcmaInterpreter::NewRuntimeCallInfo(thread, undefined, promiseHandle, undefined, 1);
336     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
337     invokeInfo->SetCallArg(thrower.GetTaggedValue());
338     // 9. Return ? Invoke(promise, "then", « thrower »).
339     return JSFunction::Invoke(invokeInfo, thenKey);
340 }
341 
PromiseResolve(JSThread * thread,const JSHandle<JSTaggedValue> & constructor,const JSHandle<JSTaggedValue> & xValue)342 JSHandle<JSTaggedValue> BuiltinsPromiseHandler::PromiseResolve(JSThread *thread,
343                                                                const JSHandle<JSTaggedValue> &constructor,
344                                                                const JSHandle<JSTaggedValue> &xValue)
345 {
346     BUILTINS_API_TRACE(thread, PromiseHandler, PromiseResolve);
347     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
348     // 1. Assert: Type(C) is Object.
349     ASSERT_PRINT(constructor->IsECMAObject(), "PromiseResolve : is not callable");
350     // 2. If IsPromise(x) is true, then
351     if (xValue->IsJSPromise()) {
352         // a. Let xConstructor be ? Get(x, "constructor").
353         JSHandle<JSTaggedValue> ctorKey(globalConst->GetHandledConstructorString());
354         JSHandle<JSTaggedValue> ctorValue = JSObject::GetProperty(thread, xValue, ctorKey).GetValue();
355         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, ctorValue);
356         // b. If SameValue(xConstructor, C) is true, return x.
357         if (JSTaggedValue::SameValue(ctorValue, constructor)) {
358             return xValue;
359         }
360     }
361     // 3. Let promiseCapability be ? NewPromiseCapability(C).
362     // 4. ReturnIfAbrupt(promiseCapability)
363     JSHandle<PromiseCapability> promiseCapability = JSPromise::NewPromiseCapability(thread, constructor);
364     RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSTaggedValue, thread);
365     JSHandle<JSTaggedValue> promiseCapaHandle = JSHandle<JSTaggedValue>::Cast(promiseCapability);
366     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, promiseCapaHandle);
367     // 6. Let resolveResult be Call(promiseCapability.[[Resolve]], undefined, «x»).
368     // 7. ReturnIfAbrupt(resolveResult).
369     JSHandle<JSTaggedValue> resolve(thread, promiseCapability->GetResolve());
370     JSHandle<JSTaggedValue> undefined(globalConst->GetHandledUndefined());
371     EcmaRuntimeCallInfo *info =
372         EcmaInterpreter::NewRuntimeCallInfo(thread, resolve, undefined, undefined, 1);
373     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, promiseCapaHandle);
374     info->SetCallArg(xValue.GetTaggedValue());
375     JSTaggedValue resolveResult = JSFunction::Call(info);
376     JSHandle<JSTaggedValue> resolveResultHandle(thread, resolveResult);
377     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, resolveResultHandle);
378     // 8. Return promiseCapability.[[Promise]].
379     JSHandle<JSTaggedValue> promise(thread, promiseCapability->GetPromise());
380     return promise;
381 }
382 
AllSettledResolveElementFunction(EcmaRuntimeCallInfo * argv)383 JSTaggedValue BuiltinsPromiseHandler::AllSettledResolveElementFunction(EcmaRuntimeCallInfo *argv)
384 {
385     // 1. Let F be the active function object.
386     JSThread *thread = argv->GetThread();
387     BUILTINS_API_TRACE(thread, PromiseHandler, AllSettledResolveElementFunction);
388     JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
389     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
390     JSHandle<JSPromiseAllSettledElementFunction> resolveElement =
391         JSHandle<JSPromiseAllSettledElementFunction>::Cast((GetConstructor(argv)));
392     // 2. Let alreadyCalled be F.[[AlreadyCalled]].
393     JSHandle<PromiseRecord> alreadyCalled =
394         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, resolveElement->GetAlreadyCalled()));
395     // 3. If alreadyCalled.[[Value]] is true, return undefined.
396     if (alreadyCalled->GetValue().IsTrue()) {
397         return JSTaggedValue::Undefined();
398     }
399     // 4. Set alreadyCalled.[[Value]] to true.
400     alreadyCalled->SetValue(thread, JSTaggedValue::True());
401     // 5. Let index be F.[[Index]].
402     uint32_t index = resolveElement->GetIndex();
403     // 6. Let values be F.[[Values]].
404     JSHandle<PromiseRecord> values =
405         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, resolveElement->GetValues()));
406     // 7. Let promiseCapability be F.[[Capability]].
407     JSHandle<PromiseCapability> capa =
408         JSHandle<PromiseCapability>::Cast(JSHandle<JSTaggedValue>(thread, resolveElement->GetCapability()));
409     // 8. Let remainingElementsCount be F.[[RemainingElements]].
410     JSHandle<PromiseRecord> remainCnt =
411         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, resolveElement->GetRemainingElements()));
412     // 9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
413     JSHandle<JSTaggedValue> proto = env->GetObjectFunctionPrototype();
414     JSHandle<JSObject> obj = thread->GetEcmaVM()->GetFactory()->OrdinaryNewJSObjectCreate(proto);
415     // 10. Perform ! CreateDataPropertyOrThrow(obj, "status", "fulfilled").
416     JSHandle<JSTaggedValue> statusKey = globalConst->GetHandledPromiseStatusString();
417     JSHandle<JSTaggedValue> fulfilledKey = globalConst->GetHandledPromiseFulfilledString();
418     JSObject::CreateDataPropertyOrThrow(thread, obj, statusKey, fulfilledKey);
419     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
420     // 11. Perform ! CreateDataPropertyOrThrow(obj, "value", x).
421     JSHandle<JSTaggedValue> valueKey = globalConst->GetHandledValueString();
422     JSHandle<JSTaggedValue> xValue = GetCallArg(argv, 0);
423     JSObject::CreateDataPropertyOrThrow(thread, obj, valueKey, xValue);
424     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
425     // 12. Set values[index] to obj.
426     JSHandle<TaggedArray> arrayValues =
427         JSHandle<TaggedArray>::Cast(JSHandle<JSTaggedValue>(thread, values->GetValue()));
428     arrayValues->Set(thread, index, obj.GetTaggedValue());
429     // 13. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
430     remainCnt->SetValue(thread, --JSTaggedNumber(remainCnt->GetValue()));
431     // 14. If remainingElementsCount.[[Value]] is 0, then
432     if (remainCnt->GetValue().IsZero()) {
433         // a. Let valuesArray be CreateArrayFromList(values).
434         JSHandle<JSArray> jsArrayValues = JSArray::CreateArrayFromList(thread, arrayValues);
435         // b. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
436         JSHandle<JSTaggedValue> capaResolve(thread, capa->GetResolve());
437         JSHandle<JSTaggedValue> undefined(globalConst->GetHandledUndefined());
438         EcmaRuntimeCallInfo *info =
439             EcmaInterpreter::NewRuntimeCallInfo(thread, capaResolve, undefined, undefined, 1);
440         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
441         info->SetCallArg(jsArrayValues.GetTaggedValue());
442         return JSFunction::Call(info);
443     }
444     // 15. Return undefined.
445     return JSTaggedValue::Undefined();
446 }
447 
AllSettledRejectElementFunction(EcmaRuntimeCallInfo * argv)448 JSTaggedValue BuiltinsPromiseHandler::AllSettledRejectElementFunction(EcmaRuntimeCallInfo *argv)
449 {
450     // 1. Let F be the active function object.
451     JSThread *thread = argv->GetThread();
452     BUILTINS_API_TRACE(thread, PromiseHandler, AllSettledRejectElementFunction);
453     JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
454     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
455     JSHandle<JSPromiseAllSettledElementFunction> rejectElement =
456         JSHandle<JSPromiseAllSettledElementFunction>::Cast((GetConstructor(argv)));
457     // 2. Let alreadyCalled be F.[[AlreadyCalled]].
458     JSHandle<PromiseRecord> alreadyCalled =
459         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetAlreadyCalled()));
460     // 3. If alreadyCalled.[[Value]] is true, return undefined.
461     if (alreadyCalled->GetValue().IsTrue()) {
462         return JSTaggedValue::Undefined();
463     }
464     // 4. Set alreadyCalled.[[Value]] to true.
465     alreadyCalled->SetValue(thread, JSTaggedValue::True());
466     // 5. Let index be F.[[Index]].
467     uint32_t index = rejectElement->GetIndex();
468     // 6. Let values be F.[[Values]].
469     JSHandle<PromiseRecord> values =
470         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetValues()));
471     // 7. Let promiseCapability be F.[[Capability]].
472     JSHandle<PromiseCapability> capa =
473         JSHandle<PromiseCapability>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetCapability()));
474     // 8. Let remainingElementsCount be F.[[RemainingElements]].
475     JSHandle<PromiseRecord> remainCnt =
476         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetRemainingElements()));
477     // 9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
478     JSHandle<JSTaggedValue> proto = env->GetObjectFunctionPrototype();
479     JSHandle<JSObject> obj = thread->GetEcmaVM()->GetFactory()->OrdinaryNewJSObjectCreate(proto);
480     // 10. Perform ! CreateDataPropertyOrThrow(obj, "status", "rejected").
481     JSHandle<JSTaggedValue> statusKey = globalConst->GetHandledPromiseStatusString();
482     JSHandle<JSTaggedValue> rejectedKey = globalConst->GetHandledPromiseRejectedString();
483     JSObject::CreateDataPropertyOrThrow(thread, obj, statusKey, rejectedKey);
484     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
485     // 11. Perform ! CreateDataPropertyOrThrow(obj, "reason", x).
486     JSHandle<JSTaggedValue> xReason = GetCallArg(argv, 0);
487     JSHandle<JSTaggedValue> reasonKey = globalConst->GetHandledPromiseReasonString();
488     JSObject::CreateDataPropertyOrThrow(thread, obj, reasonKey, xReason);
489     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
490     // 12. Set values[index] to obj.
491     JSHandle<TaggedArray> arrayValues =
492         JSHandle<TaggedArray>::Cast(JSHandle<JSTaggedValue>(thread, values->GetValue()));
493     arrayValues->Set(thread, index, obj.GetTaggedValue());
494     // 13. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
495     remainCnt->SetValue(thread, --JSTaggedNumber(remainCnt->GetValue()));
496     // 14. If remainingElementsCount.[[Value]] is 0, then
497     if (remainCnt->GetValue().IsZero()) {
498         // a. Let valuesArray be CreateArrayFromList(values).
499         JSHandle<JSArray> jsArrayValues = JSArray::CreateArrayFromList(thread, arrayValues);
500         // b. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
501         JSHandle<JSTaggedValue> capaResolve(thread, capa->GetResolve());
502         JSHandle<JSTaggedValue> undefined(globalConst->GetHandledUndefined());
503         EcmaRuntimeCallInfo *info =
504             EcmaInterpreter::NewRuntimeCallInfo(thread, capaResolve, undefined, undefined, 1);
505         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
506         info->SetCallArg(jsArrayValues.GetTaggedValue());
507         return JSFunction::Call(info);
508     }
509     // 15. Return undefined.
510     return JSTaggedValue::Undefined();
511 }
512 
AnyRejectElementFunction(EcmaRuntimeCallInfo * argv)513 JSTaggedValue BuiltinsPromiseHandler::AnyRejectElementFunction(EcmaRuntimeCallInfo *argv)
514 {
515     // 1. Let F be the active function object.
516     JSThread *thread = argv->GetThread();
517     BUILTINS_API_TRACE(thread, PromiseHandler, AnyRejectElementFunction);
518     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
519     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
520     JSHandle<JSPromiseAnyRejectElementFunction> rejectElement =
521         JSHandle<JSPromiseAnyRejectElementFunction>::Cast((GetConstructor(argv)));
522     // 2. If F.[[AlreadyCalled]] is true, return undefined.
523     JSTaggedValue alreadyCalled = rejectElement->GetAlreadyCalled();
524     if (alreadyCalled.IsTrue()) {
525         return JSTaggedValue::Undefined();
526     }
527     // 3. Set F.[[AlreadyCalled]] to true.
528     rejectElement->SetAlreadyCalled(thread, JSTaggedValue::True());
529     // 4. Let index be F.[[Index]].
530     uint32_t index = rejectElement->GetIndex();
531     // 5. Let errors be F.[[Errors]].
532     JSHandle<PromiseRecord> errors =
533         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetErrors()));
534     // 6. Let promiseCapability be F.[[Capability]].
535     JSHandle<PromiseCapability> capa =
536         JSHandle<PromiseCapability>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetCapability()));
537     // 7. Let remainingElementsCount be F.[[RemainingElements]].
538     JSHandle<PromiseRecord> remainCnt =
539         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetRemainingElements()));
540     // 8. Set errors[index] to x.
541     JSHandle<JSTaggedValue> xValue = GetCallArg(argv, 0);
542     JSHandle<TaggedArray> errorsArray =
543         JSHandle<TaggedArray>::Cast(JSHandle<JSTaggedValue>(thread, errors->GetValue()));
544     errorsArray->Set(thread, index, xValue.GetTaggedValue());
545     // 9. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
546     remainCnt->SetValue(thread, --JSTaggedNumber(remainCnt->GetValue()));
547     // 10. If remainingElementsCount.[[Value]] is 0, then
548     if (remainCnt->GetValue().IsZero()) {
549         // a. Let error be a newly created AggregateError object.
550         JSHandle<JSObject> error = factory->NewJSAggregateError();
551         // b. Perform ! DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true,
552         //    [[Enumerable]]: false, [[Writable]]: true, [[Value]]: ! CreateArrayFromList(errors) }).
553         JSHandle<JSTaggedValue> errorsKey(thread, globalConst->GetErrorsString());
554         JSHandle<JSTaggedValue> errorsValue(JSArray::CreateArrayFromList(thread, errorsArray));
555         PropertyDescriptor msgDesc(thread, errorsValue, true, false, true);
556         JSHandle<JSTaggedValue> errorTagged = JSHandle<JSTaggedValue>::Cast(error);
557         JSTaggedValue::DefinePropertyOrThrow(thread, errorTagged, errorsKey, msgDesc);
558         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
559         // c. Return ? Call(promiseCapability.[[Reject]], undefined, « error »).
560         JSHandle<JSTaggedValue> capaReject(thread, capa->GetReject());
561         JSHandle<JSTaggedValue> undefined(globalConst->GetHandledUndefined());
562         EcmaRuntimeCallInfo *info =
563             EcmaInterpreter::NewRuntimeCallInfo(thread, capaReject, undefined, undefined, 1);
564         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
565         info->SetCallArg(error.GetTaggedValue());
566         return JSFunction::Call(info);
567     }
568     // 11. Return undefined.
569     return JSTaggedValue::Undefined();
570 }
571 }  // namespace panda::ecmascript::builtins
572