• 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->GetEcmaVM()->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     [[maybe_unused]] EcmaHandleScope handleScope(argv->GetThread());
222 
223     JSHandle<JSTaggedValue> value = GetCallArg(argv, 0);
224     JSHandle<JSAsyncAwaitStatusFunction> func(GetConstructor(argv));
225     return JSAsyncAwaitStatusFunction::AsyncFunctionAwaitFulfilled(argv->GetThread(), func, value).GetTaggedValue();
226 }
227 
AsyncAwaitRejected(EcmaRuntimeCallInfo * argv)228 JSTaggedValue BuiltinsPromiseHandler::AsyncAwaitRejected(EcmaRuntimeCallInfo *argv)
229 {
230     ASSERT(argv);
231     [[maybe_unused]] EcmaHandleScope handleScope(argv->GetThread());
232 
233     JSHandle<JSTaggedValue> reason = GetCallArg(argv, 0);
234     JSHandle<JSAsyncAwaitStatusFunction> func(GetConstructor(argv));
235     return JSAsyncAwaitStatusFunction::AsyncFunctionAwaitRejected(argv->GetThread(), func, reason).GetTaggedValue();
236 }
237 
valueThunkFunction(EcmaRuntimeCallInfo * argv)238 JSTaggedValue BuiltinsPromiseHandler::valueThunkFunction(EcmaRuntimeCallInfo *argv)
239 {
240     JSHandle<JSPromiseValueThunkOrThrowerFunction> valueThunk =
241         JSHandle<JSPromiseValueThunkOrThrowerFunction>::Cast(GetConstructor(argv));
242     return valueThunk->GetResult();
243 }
244 
throwerFunction(EcmaRuntimeCallInfo * argv)245 JSTaggedValue BuiltinsPromiseHandler::throwerFunction(EcmaRuntimeCallInfo *argv)
246 {
247     JSThread *thread = argv->GetThread();
248     JSHandle<JSPromiseValueThunkOrThrowerFunction> thrower =
249         JSHandle<JSPromiseValueThunkOrThrowerFunction>::Cast(GetConstructor(argv));
250     JSTaggedValue undefined = thread->GlobalConstants()->GetUndefined();
251     THROW_NEW_ERROR_AND_RETURN_VALUE(thread, thrower->GetResult(), undefined);
252 }
253 
ThenFinally(EcmaRuntimeCallInfo * argv)254 JSTaggedValue BuiltinsPromiseHandler::ThenFinally(EcmaRuntimeCallInfo *argv)
255 {
256     // 1. Let F be the active function object.
257     JSThread *thread = argv->GetThread();
258     auto ecmaVm = thread->GetEcmaVM();
259     ObjectFactory *factory = ecmaVm->GetFactory();
260     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
261     JSHandle<JSPromiseFinallyFunction> thenFinally(GetConstructor(argv));
262     JSHandle<JSTaggedValue> value = BuiltinsBase::GetCallArg(argv, 0);
263     // 2. Let onFinally be F.[[OnFinally]].
264     // 3. Assert: IsCallable(onFinally) is true.
265     JSHandle<JSTaggedValue> onFinally(thread, thenFinally->GetOnFinally());
266     ASSERT_PRINT(onFinally->IsCallable(), "onFinally is not callable");
267     // 4. Let result be ? Call(onFinally, undefined).
268     JSHandle<JSTaggedValue> undefined = globalConst->GetHandledUndefined();
269     EcmaRuntimeCallInfo *taggedInfo =
270         EcmaInterpreter::NewRuntimeCallInfo(thread, onFinally, undefined, undefined, 0);
271     JSTaggedValue result = JSFunction::Call(taggedInfo);
272     JSHandle<JSTaggedValue> resultHandle(thread, result);
273     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
274     // 5. Let C be F.[[Constructor]].
275     // 6. Assert: IsConstructor(C) is true.
276     JSHandle<JSTaggedValue> thenFinallyConstructor(thread, thenFinally->GetConstructor());
277     ASSERT_PRINT(thenFinallyConstructor->IsConstructor(), "thenFinallyConstructor is not constructor");
278     // 7. Let promise be ? PromiseResolve(C, result).
279     JSHandle<JSTaggedValue> promiseHandle =
280         BuiltinsPromiseHandler::PromiseResolve(thread, thenFinallyConstructor, resultHandle);
281     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
282     // 8. Let valueThunk be equivalent to a function that returns value.
283     JSHandle<JSPromiseValueThunkOrThrowerFunction> valueThunk =
284         factory->NewJSPromiseValueThunkFunction();
285     valueThunk->SetResult(thread, value);
286     JSHandle<JSTaggedValue> thenKey(globalConst->GetHandledPromiseThenString());
287     EcmaRuntimeCallInfo *invokeInfo =
288         EcmaInterpreter::NewRuntimeCallInfo(thread, undefined, promiseHandle, undefined, 1);
289     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
290     invokeInfo->SetCallArg(valueThunk.GetTaggedValue());
291     // 9. Return ? Invoke(promise, "then", « valueThunk »).
292     return JSFunction::Invoke(invokeInfo, thenKey);
293 }
294 
CatchFinally(EcmaRuntimeCallInfo * argv)295 JSTaggedValue BuiltinsPromiseHandler::CatchFinally(EcmaRuntimeCallInfo *argv)
296 {
297     // 1. Let F be the active function object.
298     JSThread *thread = argv->GetThread();
299     auto ecmaVm = thread->GetEcmaVM();
300     ObjectFactory *factory = ecmaVm->GetFactory();
301     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
302     JSHandle<JSPromiseFinallyFunction> catchFinally(GetConstructor(argv));
303     // 2. Let onFinally be F.[[OnFinally]].
304     // 3. Assert: IsCallable(onFinally) is true.
305     JSHandle<JSTaggedValue> onFinally(thread, catchFinally->GetOnFinally());
306     ASSERT_PRINT(onFinally->IsCallable(), "thenOnFinally is not callable");
307     // 4. Let result be ? Call(onFinally, undefined).
308     JSHandle<JSTaggedValue> undefined = globalConst->GetHandledUndefined();
309     EcmaRuntimeCallInfo *info =
310         EcmaInterpreter::NewRuntimeCallInfo(thread, onFinally, undefined, undefined, 0);
311     JSTaggedValue result = JSFunction::Call(info);
312     JSHandle<JSTaggedValue> resultHandle(thread, result);
313     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
314     // 5. Let C be F.[[Constructor]].
315     // 6. Assert: IsConstructor(C) is true.
316     JSHandle<JSTaggedValue> catchFinallyConstructor(thread, catchFinally->GetConstructor());
317     ASSERT_PRINT(catchFinallyConstructor->IsConstructor(), "catchFinallyConstructor is not constructor");
318     // 7. Let promise be ? PromiseResolve(C, result).
319     JSHandle<JSTaggedValue> promiseHandle =
320         BuiltinsPromiseHandler::PromiseResolve(thread, catchFinallyConstructor, resultHandle);
321     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
322     // 8. Let thrower be equivalent to a function that throws reason.
323     JSHandle<JSTaggedValue> reason = BuiltinsBase::GetCallArg(argv, 0);
324     JSHandle<JSTaggedValue> thenKey(globalConst->GetHandledPromiseThenString());
325     JSHandle<JSPromiseValueThunkOrThrowerFunction> thrower =
326         factory->NewJSPromiseThrowerFunction();
327     thrower->SetResult(thread, reason);
328     EcmaRuntimeCallInfo *invokeInfo =
329         EcmaInterpreter::NewRuntimeCallInfo(thread, undefined, promiseHandle, undefined, 1);
330     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
331     invokeInfo->SetCallArg(thrower.GetTaggedValue());
332     // 9. Return ? Invoke(promise, "then", « thrower »).
333     return JSFunction::Invoke(invokeInfo, thenKey);
334 }
335 
PromiseResolve(JSThread * thread,const JSHandle<JSTaggedValue> & constructor,const JSHandle<JSTaggedValue> & xValue)336 JSHandle<JSTaggedValue> BuiltinsPromiseHandler::PromiseResolve(JSThread *thread,
337                                                                const JSHandle<JSTaggedValue> &constructor,
338                                                                const JSHandle<JSTaggedValue> &xValue)
339 {
340     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
341     // 1. Assert: Type(C) is Object.
342     ASSERT_PRINT(constructor->IsECMAObject(), "PromiseResolve : is not callable");
343     // 2. If IsPromise(x) is true, then
344     if (xValue->IsJSPromise()) {
345         // a. Let xConstructor be ? Get(x, "constructor").
346         JSHandle<JSTaggedValue> ctorKey(globalConst->GetHandledConstructorString());
347         JSHandle<JSTaggedValue> ctorValue = JSObject::GetProperty(thread, xValue, ctorKey).GetValue();
348         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, ctorValue);
349         // b. If SameValue(xConstructor, C) is true, return x.
350         if (JSTaggedValue::SameValue(ctorValue, constructor)) {
351             return xValue;
352         }
353     }
354     // 3. Let promiseCapability be ? NewPromiseCapability(C).
355     // 4. ReturnIfAbrupt(promiseCapability)
356     JSHandle<PromiseCapability> promiseCapability = JSPromise::NewPromiseCapability(thread, constructor);
357     JSHandle<JSTaggedValue> promiseCapaHandle = JSHandle<JSTaggedValue>::Cast(promiseCapability);
358     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, promiseCapaHandle);
359     // 6. Let resolveResult be Call(promiseCapability.[[Resolve]], undefined, «x»).
360     // 7. ReturnIfAbrupt(resolveResult).
361     JSHandle<JSTaggedValue> resolve(thread, promiseCapability->GetResolve());
362     JSHandle<JSTaggedValue> undefined(globalConst->GetHandledUndefined());
363     EcmaRuntimeCallInfo *info =
364         EcmaInterpreter::NewRuntimeCallInfo(thread, resolve, undefined, undefined, 1);
365     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, promiseCapaHandle);
366     info->SetCallArg(xValue.GetTaggedValue());
367     JSTaggedValue resolveResult = JSFunction::Call(info);
368     JSHandle<JSTaggedValue> resolveResultHandle(thread, resolveResult);
369     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, resolveResultHandle);
370     // 8. Return promiseCapability.[[Promise]].
371     JSHandle<JSTaggedValue> promise(thread, promiseCapability->GetPromise());
372     return promise;
373 }
374 
AllSettledResolveElementFunction(EcmaRuntimeCallInfo * argv)375 JSTaggedValue BuiltinsPromiseHandler::AllSettledResolveElementFunction(EcmaRuntimeCallInfo *argv)
376 {
377     // 1. Let F be the active function object.
378     JSThread *thread = argv->GetThread();
379     JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
380     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
381     JSHandle<JSPromiseAllSettledElementFunction> resolveElement =
382         JSHandle<JSPromiseAllSettledElementFunction>::Cast((GetConstructor(argv)));
383     // 2. Let alreadyCalled be F.[[AlreadyCalled]].
384     JSHandle<PromiseRecord> alreadyCalled =
385         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, resolveElement->GetAlreadyCalled()));
386     // 3. If alreadyCalled.[[Value]] is true, return undefined.
387     if (alreadyCalled->GetValue().IsTrue()) {
388         return JSTaggedValue::Undefined();
389     }
390     // 4. Set alreadyCalled.[[Value]] to true.
391     alreadyCalled->SetValue(thread, JSTaggedValue::True());
392     // 5. Let index be F.[[Index]].
393     uint32_t index = resolveElement->GetIndex();
394     // 6. Let values be F.[[Values]].
395     JSHandle<PromiseRecord> values =
396         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, resolveElement->GetValues()));
397     // 7. Let promiseCapability be F.[[Capability]].
398     JSHandle<PromiseCapability> capa =
399         JSHandle<PromiseCapability>::Cast(JSHandle<JSTaggedValue>(thread, resolveElement->GetCapability()));
400     // 8. Let remainingElementsCount be F.[[RemainingElements]].
401     JSHandle<PromiseRecord> remainCnt =
402         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, resolveElement->GetRemainingElements()));
403     // 9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
404     JSHandle<JSTaggedValue> proto = env->GetObjectFunctionPrototype();
405     JSHandle<JSObject> obj = thread->GetEcmaVM()->GetFactory()->OrdinaryNewJSObjectCreate(proto);
406     // 10. Perform ! CreateDataPropertyOrThrow(obj, "status", "fulfilled").
407     JSHandle<JSTaggedValue> statusKey = globalConst->GetHandledPromiseStatusString();
408     JSHandle<JSTaggedValue> fulfilledKey = globalConst->GetHandledPromiseFulfilledString();
409     JSObject::CreateDataPropertyOrThrow(thread, obj, statusKey, fulfilledKey);
410     // 11. Perform ! CreateDataPropertyOrThrow(obj, "value", x).
411     JSHandle<JSTaggedValue> valueKey = globalConst->GetHandledValueString();
412     JSHandle<JSTaggedValue> xValue = GetCallArg(argv, 0);
413     JSObject::CreateDataPropertyOrThrow(thread, obj, valueKey, xValue);
414     // 12. Set values[index] to obj.
415     JSHandle<TaggedArray> arrayValues =
416         JSHandle<TaggedArray>::Cast(JSHandle<JSTaggedValue>(thread, values->GetValue()));
417     arrayValues->Set(thread, index, obj.GetTaggedValue());
418     // 13. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
419     remainCnt->SetValue(thread, --JSTaggedNumber(remainCnt->GetValue()));
420     // 14. If remainingElementsCount.[[Value]] is 0, then
421     if (remainCnt->GetValue().IsZero()) {
422         // a. Let valuesArray be CreateArrayFromList(values).
423         JSHandle<JSArray> jsArrayValues = JSArray::CreateArrayFromList(thread, arrayValues);
424         // b. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
425         JSHandle<JSTaggedValue> capaResolve(thread, capa->GetResolve());
426         JSHandle<JSTaggedValue> undefined(globalConst->GetHandledUndefined());
427         EcmaRuntimeCallInfo *info =
428             EcmaInterpreter::NewRuntimeCallInfo(thread, capaResolve, undefined, undefined, 1);
429         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
430         info->SetCallArg(jsArrayValues.GetTaggedValue());
431         return JSFunction::Call(info);
432     }
433     // 15. Return undefined.
434     return JSTaggedValue::Undefined();
435 }
436 
AllSettledRejectElementFunction(EcmaRuntimeCallInfo * argv)437 JSTaggedValue BuiltinsPromiseHandler::AllSettledRejectElementFunction(EcmaRuntimeCallInfo *argv)
438 {
439     // 1. Let F be the active function object.
440     JSThread *thread = argv->GetThread();
441     JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
442     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
443     JSHandle<JSPromiseAllSettledElementFunction> rejectElement =
444         JSHandle<JSPromiseAllSettledElementFunction>::Cast((GetConstructor(argv)));
445     // 2. Let alreadyCalled be F.[[AlreadyCalled]].
446     JSHandle<PromiseRecord> alreadyCalled =
447         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetAlreadyCalled()));
448     // 3. If alreadyCalled.[[Value]] is true, return undefined.
449     if (alreadyCalled->GetValue().IsTrue()) {
450         return JSTaggedValue::Undefined();
451     }
452     // 4. Set alreadyCalled.[[Value]] to true.
453     alreadyCalled->SetValue(thread, JSTaggedValue::True());
454     // 5. Let index be F.[[Index]].
455     uint32_t index = rejectElement->GetIndex();
456     // 6. Let values be F.[[Values]].
457     JSHandle<PromiseRecord> values =
458         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetValues()));
459     // 7. Let promiseCapability be F.[[Capability]].
460     [[maybe_unused]] JSHandle<PromiseCapability> capa =
461         JSHandle<PromiseCapability>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetCapability()));
462     // 8. Let remainingElementsCount be F.[[RemainingElements]].
463     [[maybe_unused]] JSHandle<PromiseRecord> remainCnt =
464         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetRemainingElements()));
465     // 9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
466     JSHandle<JSTaggedValue> proto = env->GetObjectFunctionPrototype();
467     JSHandle<JSObject> obj = thread->GetEcmaVM()->GetFactory()->OrdinaryNewJSObjectCreate(proto);
468     // 10. Perform ! CreateDataPropertyOrThrow(obj, "status", "rejected").
469     JSHandle<JSTaggedValue> statusKey = globalConst->GetHandledPromiseStatusString();
470     JSHandle<JSTaggedValue> rejectedKey = globalConst->GetHandledPromiseRejectedString();
471     JSObject::CreateDataPropertyOrThrow(thread, obj, statusKey, rejectedKey);
472     // 11. Perform ! CreateDataPropertyOrThrow(obj, "reason", x).
473     JSHandle<JSTaggedValue> xReason = GetCallArg(argv, 0);
474     JSHandle<JSTaggedValue> reasonKey = globalConst->GetHandledPromiseReasonString();
475     JSObject::CreateDataPropertyOrThrow(thread, obj, reasonKey, xReason);
476     // 12. Set values[index] to obj.
477     JSHandle<TaggedArray> arrayValues =
478         JSHandle<TaggedArray>::Cast(JSHandle<JSTaggedValue>(thread, values->GetValue()));
479     arrayValues->Set(thread, index, obj.GetTaggedValue());
480     // 13. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
481     remainCnt->SetValue(thread, --JSTaggedNumber(remainCnt->GetValue()));
482     // 14. If remainingElementsCount.[[Value]] is 0, then
483     if (remainCnt->GetValue().IsZero()) {
484         // a. Let valuesArray be CreateArrayFromList(values).
485         JSHandle<JSArray> jsArrayValues = JSArray::CreateArrayFromList(thread, arrayValues);
486         // b. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
487         JSHandle<JSTaggedValue> capaResolve(thread, capa->GetResolve());
488         JSHandle<JSTaggedValue> undefined(globalConst->GetHandledUndefined());
489         EcmaRuntimeCallInfo *info =
490             EcmaInterpreter::NewRuntimeCallInfo(thread, capaResolve, undefined, undefined, 1);
491         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
492         info->SetCallArg(jsArrayValues.GetTaggedValue());
493         return JSFunction::Call(info);
494     }
495     // 15. Return undefined.
496     return JSTaggedValue::Undefined();
497 }
498 
AnyRejectElementFunction(EcmaRuntimeCallInfo * argv)499 JSTaggedValue BuiltinsPromiseHandler::AnyRejectElementFunction(EcmaRuntimeCallInfo *argv)
500 {
501     // 1. Let F be the active function object.
502     JSThread *thread = argv->GetThread();
503     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
504     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
505     JSHandle<JSPromiseAnyRejectElementFunction> rejectElement =
506         JSHandle<JSPromiseAnyRejectElementFunction>::Cast((GetConstructor(argv)));
507     // 2. If F.[[AlreadyCalled]] is true, return undefined.
508     JSTaggedValue alreadyCalled = rejectElement->GetAlreadyCalled();
509     if (alreadyCalled.IsTrue()) {
510         return JSTaggedValue::Undefined();
511     }
512     // 3. Set F.[[AlreadyCalled]] to true.
513     rejectElement->SetAlreadyCalled(thread, JSTaggedValue::True());
514     // 4. Let index be F.[[Index]].
515     uint32_t index = rejectElement->GetIndex();
516     // 5. Let errors be F.[[Errors]].
517     [[maybe_unused]] JSHandle<PromiseRecord> errors =
518         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetErrors()));
519     // 6. Let promiseCapability be F.[[Capability]].
520     [[maybe_unused]] JSHandle<PromiseCapability> capa =
521         JSHandle<PromiseCapability>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetCapability()));
522     // 7. Let remainingElementsCount be F.[[RemainingElements]].
523     JSHandle<PromiseRecord> remainCnt =
524         JSHandle<PromiseRecord>::Cast(JSHandle<JSTaggedValue>(thread, rejectElement->GetRemainingElements()));
525     // 8. Set errors[index] to x.
526     JSHandle<JSTaggedValue> xValue = GetCallArg(argv, 0);
527     JSHandle<TaggedArray> errorsArray =
528         JSHandle<TaggedArray>::Cast(JSHandle<JSTaggedValue>(thread, errors->GetValue()));
529     errorsArray->Set(thread, index, xValue.GetTaggedValue());
530     // 9. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
531     remainCnt->SetValue(thread, --JSTaggedNumber(remainCnt->GetValue()));
532     // 10. If remainingElementsCount.[[Value]] is 0, then
533     if (remainCnt->GetValue().IsZero()) {
534         // a. Let error be a newly created AggregateError object.
535         JSHandle<JSObject> error = factory->NewJSAggregateError();
536         // b. Perform ! DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true,
537         //    [[Enumerable]]: false, [[Writable]]: true, [[Value]]: ! CreateArrayFromList(errors) }).
538         JSHandle<JSTaggedValue> errorsKey(thread, globalConst->GetErrorsString());
539         JSHandle<JSTaggedValue> errorsValue(JSArray::CreateArrayFromList(thread, errorsArray));
540         PropertyDescriptor msgDesc(thread, errorsValue, true, false, true);
541         JSHandle<JSTaggedValue> errorTagged = JSHandle<JSTaggedValue>::Cast(error);
542         JSTaggedValue::DefinePropertyOrThrow(thread, errorTagged, errorsKey, msgDesc);
543         // c. Return ? Call(promiseCapability.[[Reject]], undefined, « error »).
544         JSHandle<JSTaggedValue> capaReject(thread, capa->GetReject());
545         JSHandle<JSTaggedValue> undefined(globalConst->GetHandledUndefined());
546         EcmaRuntimeCallInfo *info =
547             EcmaInterpreter::NewRuntimeCallInfo(thread, capaReject, undefined, undefined, 1);
548         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
549         info->SetCallArg(error.GetTaggedValue());
550         return JSFunction::Call(info);
551     }
552     // 11. Return undefined.
553     return JSTaggedValue::Undefined();
554 }
555 }  // namespace panda::ecmascript::builtins
556