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/internal_call_params.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-inl.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> undefine = globalConst->GetHandledUndefined();
208 InternalCallParams *arguments = thread->GetInternalCallParams();
209 arguments->MakeArgv(jsArrayValues);
210 return JSFunction::Call(thread, capaResolve, undefine, 1, arguments->GetArgv());
211 }
212 // 11. Return undefined.
213 return JSTaggedValue::Undefined();
214 }
215
AsyncAwaitFulfilled(EcmaRuntimeCallInfo * argv)216 JSTaggedValue BuiltinsPromiseHandler::AsyncAwaitFulfilled(EcmaRuntimeCallInfo *argv)
217 {
218 ASSERT(argv);
219 [[maybe_unused]] EcmaHandleScope handleScope(argv->GetThread());
220
221 JSHandle<JSTaggedValue> value = GetCallArg(argv, 0);
222 JSHandle<JSAsyncAwaitStatusFunction> func(GetConstructor(argv));
223 return JSAsyncAwaitStatusFunction::AsyncFunctionAwaitFulfilled(argv->GetThread(), func, value).GetTaggedValue();
224 }
225
AsyncAwaitRejected(EcmaRuntimeCallInfo * argv)226 JSTaggedValue BuiltinsPromiseHandler::AsyncAwaitRejected(EcmaRuntimeCallInfo *argv)
227 {
228 ASSERT(argv);
229 [[maybe_unused]] EcmaHandleScope handleScope(argv->GetThread());
230
231 JSHandle<JSTaggedValue> reason = GetCallArg(argv, 0);
232 JSHandle<JSAsyncAwaitStatusFunction> func(GetConstructor(argv));
233 return JSAsyncAwaitStatusFunction::AsyncFunctionAwaitRejected(argv->GetThread(), func, reason).GetTaggedValue();
234 }
235 } // namespace panda::ecmascript::builtins
236