• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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.h"
17 
18 #include "ecmascript/base/error_type.h"
19 #include "ecmascript/base/number_helper.h"
20 #include "ecmascript/builtins/builtins_ark_tools.h"
21 #include "ecmascript/builtins/builtins_array.h"
22 #include "ecmascript/builtins/builtins_arraybuffer.h"
23 #include "ecmascript/builtins/builtins_async_from_sync_iterator.h"
24 #include "ecmascript/builtins/builtins_async_function.h"
25 #include "ecmascript/builtins/builtins_async_iterator.h"
26 #include "ecmascript/builtins/builtins_async_generator.h"
27 #include "ecmascript/builtins/builtins_atomics.h"
28 #include "ecmascript/builtins/builtins_bigint.h"
29 #include "ecmascript/builtins/builtins_boolean.h"
30 #include "ecmascript/builtins/builtins_cjs_module.h"
31 #include "ecmascript/builtins/builtins_cjs_require.h"
32 #include "ecmascript/builtins/builtins_cjs_exports.h"
33 #include "ecmascript/builtins/builtins_dataview.h"
34 #include "ecmascript/builtins/builtins_date.h"
35 #include "ecmascript/builtins/builtins_errors.h"
36 #include "ecmascript/builtins/builtins_finalization_registry.h"
37 #include "ecmascript/builtins/builtins_function.h"
38 #include "ecmascript/builtins/builtins_generator.h"
39 #include "ecmascript/builtins/builtins_global.h"
40 #include "ecmascript/builtins/builtins_iterator.h"
41 #include "ecmascript/builtins/builtins_json.h"
42 #include "ecmascript/builtins/builtins_map.h"
43 #include "ecmascript/builtins/builtins_math.h"
44 #include "ecmascript/builtins/builtins_number.h"
45 #include "ecmascript/builtins/builtins_object.h"
46 #include "ecmascript/builtins/builtins_promise.h"
47 #include "ecmascript/builtins/builtins_promise_handler.h"
48 #include "ecmascript/builtins/builtins_promise_job.h"
49 #include "ecmascript/builtins/builtins_proxy.h"
50 #include "ecmascript/builtins/builtins_reflect.h"
51 #include "ecmascript/builtins/builtins_regexp.h"
52 #include "ecmascript/builtins/builtins_set.h"
53 #include "ecmascript/builtins/builtins_sharedarraybuffer.h"
54 #include "ecmascript/builtins/builtins_string.h"
55 #include "ecmascript/builtins/builtins_string_iterator.h"
56 #include "ecmascript/builtins/builtins_symbol.h"
57 #include "ecmascript/builtins/builtins_typedarray.h"
58 #include "ecmascript/builtins/builtins_weak_map.h"
59 #include "ecmascript/builtins/builtins_weak_ref.h"
60 #include "ecmascript/builtins/builtins_weak_set.h"
61 #include "ecmascript/containers/containers_private.h"
62 #include "ecmascript/ecma_runtime_call_info.h"
63 #include "ecmascript/js_array.h"
64 #include "ecmascript/js_arraybuffer.h"
65 #include "ecmascript/js_array_iterator.h"
66 #include "ecmascript/js_async_function.h"
67 #include "ecmascript/js_async_generator_object.h"
68 #include "ecmascript/js_dataview.h"
69 #include "ecmascript/js_for_in_iterator.h"
70 #include "ecmascript/js_finalization_registry.h"
71 #include "ecmascript/js_function.h"
72 #include "ecmascript/js_handle.h"
73 #include "ecmascript/js_hclass.h"
74 #include "ecmascript/js_map.h"
75 #include "ecmascript/js_map_iterator.h"
76 #include "ecmascript/js_primitive_ref.h"
77 #include "ecmascript/js_promise.h"
78 #include "ecmascript/js_regexp.h"
79 #include "ecmascript/js_regexp_iterator.h"
80 #include "ecmascript/js_runtime_options.h"
81 #include "ecmascript/js_set.h"
82 #include "ecmascript/js_set_iterator.h"
83 #include "ecmascript/js_string_iterator.h"
84 #include "ecmascript/js_async_from_sync_iterator.h"
85 #include "ecmascript/js_tagged_value.h"
86 #include "ecmascript/js_typed_array.h"
87 #include "ecmascript/js_weak_container.h"
88 #include "ecmascript/js_weak_ref.h"
89 #include "ecmascript/mem/mem.h"
90 #include "ecmascript/module/js_module_namespace.h"
91 #include "ecmascript/require/js_cjs_module.h"
92 #include "ecmascript/require/js_cjs_module_cache.h"
93 #include "ecmascript/require/js_cjs_require.h"
94 #include "ecmascript/require/js_cjs_exports.h"
95 #include "ecmascript/napi/include/jsnapi.h"
96 #include "ecmascript/object_factory.h"
97 #ifdef ARK_SUPPORT_INTL
98 #include "ecmascript/builtins/builtins_collator.h"
99 #include "ecmascript/builtins/builtins_date_time_format.h"
100 #include "ecmascript/builtins/builtins_displaynames.h"
101 #include "ecmascript/builtins/builtins_intl.h"
102 #include "ecmascript/builtins/builtins_list_format.h"
103 #include "ecmascript/builtins/builtins_locale.h"
104 #include "ecmascript/builtins/builtins_number_format.h"
105 #include "ecmascript/builtins/builtins_plural_rules.h"
106 #include "ecmascript/builtins/builtins_relative_time_format.h"
107 #include "ecmascript/js_collator.h"
108 #include "ecmascript/js_date_time_format.h"
109 #include "ecmascript/js_displaynames.h"
110 #include "ecmascript/js_list_format.h"
111 #include "ecmascript/js_locale.h"
112 #include "ecmascript/js_number_format.h"
113 #include "ecmascript/js_plural_rules.h"
114 #include "ecmascript/js_relative_time_format.h"
115 #endif
116 
117 #include "ohos/init_data.h"
118 
119 namespace panda::ecmascript {
120 using Number = builtins::BuiltinsNumber;
121 using BuiltinsBigInt = builtins::BuiltinsBigInt;
122 using Object = builtins::BuiltinsObject;
123 using Date = builtins::BuiltinsDate;
124 using Symbol = builtins::BuiltinsSymbol;
125 using Boolean = builtins::BuiltinsBoolean;
126 using BuiltinsLazyCallback = builtins::BuiltinsLazyCallback;
127 using BuiltinsMap = builtins::BuiltinsMap;
128 using BuiltinsSet = builtins::BuiltinsSet;
129 using BuiltinsWeakMap = builtins::BuiltinsWeakMap;
130 using BuiltinsWeakSet = builtins::BuiltinsWeakSet;
131 using BuiltinsWeakRef = builtins::BuiltinsWeakRef;
132 using BuiltinsFinalizationRegistry = builtins::BuiltinsFinalizationRegistry;
133 using BuiltinsArray = builtins::BuiltinsArray;
134 using BuiltinsTypedArray = builtins::BuiltinsTypedArray;
135 using BuiltinsIterator = builtins::BuiltinsIterator;
136 
137 using Error = builtins::BuiltinsError;
138 using RangeError = builtins::BuiltinsRangeError;
139 using ReferenceError = builtins::BuiltinsReferenceError;
140 using TypeError = builtins::BuiltinsTypeError;
141 using AggregateError = builtins::BuiltinsAggregateError;
142 using URIError = builtins::BuiltinsURIError;
143 using SyntaxError = builtins::BuiltinsSyntaxError;
144 using EvalError = builtins::BuiltinsEvalError;
145 using OOMError = builtins::BuiltinsOOMError;
146 using ErrorType = base::ErrorType;
147 using RandomGenerator = base::RandomGenerator;
148 using Global = builtins::BuiltinsGlobal;
149 using BuiltinsString = builtins::BuiltinsString;
150 using StringIterator = builtins::BuiltinsStringIterator;
151 using BuiltinsAsyncFromSyncIterator = builtins::BuiltinsAsyncFromSyncIterator;
152 using RegExp = builtins::BuiltinsRegExp;
153 using Function = builtins::BuiltinsFunction;
154 using Math = builtins::BuiltinsMath;
155 using Atomics = builtins::BuiltinsAtomics;
156 using ArrayBuffer = builtins::BuiltinsArrayBuffer;
157 using Json = builtins::BuiltinsJson;
158 using Proxy = builtins::BuiltinsProxy;
159 using Reflect = builtins::BuiltinsReflect;
160 using AsyncFunction = builtins::BuiltinsAsyncFunction;
161 using GeneratorObject = builtins::BuiltinsGenerator;
162 using Promise = builtins::BuiltinsPromise;
163 using BuiltinsPromiseHandler = builtins::BuiltinsPromiseHandler;
164 using BuiltinsPromiseJob = builtins::BuiltinsPromiseJob;
165 using ErrorType = base::ErrorType;
166 using DataView = builtins::BuiltinsDataView;
167 #ifdef ARK_SUPPORT_INTL
168 using Intl = builtins::BuiltinsIntl;
169 using Locale = builtins::BuiltinsLocale;
170 using DateTimeFormat = builtins::BuiltinsDateTimeFormat;
171 using RelativeTimeFormat = builtins::BuiltinsRelativeTimeFormat;
172 using NumberFormat = builtins::BuiltinsNumberFormat;
173 using Collator = builtins::BuiltinsCollator;
174 using PluralRules = builtins::BuiltinsPluralRules;
175 using DisplayNames = builtins::BuiltinsDisplayNames;
176 using ListFormat = builtins::BuiltinsListFormat;
177 #endif
178 using BuiltinsCjsModule = builtins::BuiltinsCjsModule;
179 using BuiltinsCjsExports = builtins::BuiltinsCjsExports;
180 using BuiltinsCjsRequire = builtins::BuiltinsCjsRequire;
181 
182 using ContainersPrivate = containers::ContainersPrivate;
183 using SharedArrayBuffer = builtins::BuiltinsSharedArrayBuffer;
184 
185 using BuiltinsAsyncIterator = builtins::BuiltinsAsyncIterator;
186 using AsyncGeneratorObject = builtins::BuiltinsAsyncGenerator;
187 
Initialize(const JSHandle<GlobalEnv> & env,JSThread * thread,bool lazyInit,bool isRealm)188 void Builtins::Initialize(const JSHandle<GlobalEnv> &env, JSThread *thread, bool lazyInit, bool isRealm)
189 {
190     thread_ = thread;
191     vm_ = thread->GetEcmaVM();
192     factory_ = vm_->GetFactory();
193     [[maybe_unused]] EcmaHandleScope scope(thread_);
194     JSHandle<JSTaggedValue> nullHandle(thread, JSTaggedValue::Null());
195 
196     // Object.prototype[hclass]
197     JSHandle<JSHClass> objPrototypeHClass = factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, nullHandle);
198 
199     // Object.prototype
200     JSHandle<JSObject> objFuncPrototype = factory_->NewJSObject(objPrototypeHClass);
201     JSHandle<JSTaggedValue> objFuncPrototypeVal(objFuncPrototype);
202 
203     // Object.prototype_or_hclass
204     JSHandle<JSHClass> objFuncClass =
205         factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, objFuncPrototypeVal);
206     env->SetObjectFunctionClass(thread_, objFuncClass);
207 
208     // GLobalObject.prototype_or_hclass
209     JSHandle<JSHClass> globalObjFuncClass =
210         factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_GLOBAL_OBJECT, 0);
211     globalObjFuncClass->SetPrototype(thread_, objFuncPrototypeVal.GetTaggedValue());
212     globalObjFuncClass->SetIsDictionaryMode(true);
213     // Function.prototype_or_hclass
214     JSHandle<JSHClass> emptyFuncClass(
215         factory_->NewEcmaHClass(JSFunction::SIZE, JSType::JS_FUNCTION, objFuncPrototypeVal));
216 
217     // PrimitiveRef.prototype_or_hclass
218     JSHandle<JSHClass> primRefObjHClass =
219         factory_->NewEcmaHClass(JSPrimitiveRef::SIZE, JSType::JS_PRIMITIVE_REF, objFuncPrototypeVal);
220 
221     // init global object
222     JSHandle<JSObject> globalObject = factory_->NewNonMovableJSObject(globalObjFuncClass);
223     env->SetJSGlobalObject(thread_, globalObject);
224 
225     // init global patch
226     JSHandle<TaggedArray> globalPatch = factory_->EmptyArray();
227     env->SetGlobalPatch(thread, globalPatch);
228 
229     // initialize Function, forbidden change order
230     InitializeFunction(env, emptyFuncClass);
231 
232     JSHandle<JSHClass> asyncAwaitStatusFuncClass =
233         factory_->CreateFunctionClass(FunctionKind::NORMAL_FUNCTION, JSAsyncAwaitStatusFunction::SIZE,
234                                       JSType::JS_ASYNC_AWAIT_STATUS_FUNCTION, env->GetFunctionPrototype());
235     env->SetAsyncAwaitStatusFunctionClass(thread_, asyncAwaitStatusFuncClass);
236 
237     JSHandle<JSHClass> asyncGeneratorResNextRetProRstFtnClass =
238         factory_->NewEcmaHClass(JSAsyncGeneratorResNextRetProRstFtn::SIZE,
239                                   JSType::JS_ASYNC_GENERATOR_RESUME_NEXT_RETURN_PROCESSOR_RST_FTN,
240                                   env->GetFunctionPrototype());
241     asyncGeneratorResNextRetProRstFtnClass->SetCallable(true);
242     asyncGeneratorResNextRetProRstFtnClass->SetExtensible(true);
243     env->SetAsyncGeneratorResNextRetProRstFtnClass(thread_, asyncGeneratorResNextRetProRstFtnClass);
244 
245     JSHandle<JSHClass> proxyRevocFuncClass = factory_->NewEcmaHClass(
246         JSProxyRevocFunction::SIZE, JSType::JS_PROXY_REVOC_FUNCTION, env->GetFunctionPrototype());
247     proxyRevocFuncClass->SetCallable(true);
248     proxyRevocFuncClass->SetExtensible(true);
249     env->SetProxyRevocFunctionClass(thread_, proxyRevocFuncClass);
250 
251     // Object = new Function()
252     JSHandle<JSObject> objectFunction(
253         NewBuiltinConstructor(env, objFuncPrototype, Object::ObjectConstructor, "Object", FunctionLength::ONE));
254     objectFunction.GetObject<JSFunction>()->SetFunctionPrototype(thread_, objFuncClass.GetTaggedValue());
255     // initialize object method.
256     env->SetObjectFunction(thread_, objectFunction);
257     env->SetObjectFunctionPrototype(thread_, objFuncPrototype);
258 
259     JSHandle<JSHClass> FunctionClass = factory_->CreateFunctionClass(FunctionKind::BASE_CONSTRUCTOR, JSFunction::SIZE,
260                                                                      JSType::JS_FUNCTION, env->GetFunctionPrototype());
261     env->SetFunctionClassWithProto(thread_, FunctionClass);
262     FunctionClass = factory_->CreateFunctionClass(FunctionKind::NORMAL_FUNCTION, JSFunction::SIZE, JSType::JS_FUNCTION,
263                                                   env->GetFunctionPrototype());
264     env->SetFunctionClassWithoutProto(thread_, FunctionClass);
265     FunctionClass = factory_->CreateFunctionClass(FunctionKind::CLASS_CONSTRUCTOR, JSFunction::SIZE,
266                                                   JSType::JS_FUNCTION, env->GetFunctionPrototype());
267     env->SetFunctionClassWithoutName(thread_, FunctionClass);
268 
269     if (!isRealm) {
270         InitializeAllTypeError(env, objFuncClass);
271         InitializeSymbol(env, primRefObjHClass);
272         InitializeBigInt(env, primRefObjHClass);
273     } else {
274         // error and symbol need to be shared when initialize realm
275         InitializeAllTypeErrorWithRealm(env);
276         InitializeSymbolWithRealm(env, primRefObjHClass);
277         InitializeBigIntWithRealm(env);
278     }
279 
280     InitializeArray(env, objFuncPrototypeVal);
281     if (lazyInit) {
282         LazyInitializeDate(env);
283         LazyInitializeSet(env);
284         LazyInitializeMap(env);
285         LazyInitializeWeakMap(env);
286         LazyInitializeWeakSet(env);
287         LazyInitializeWeakRef(env);
288         LazyInitializeFinalizationRegistry(env);
289         LazyInitializeTypedArray(env);
290         LazyInitializeArrayBuffer(env);
291         LazyInitializeDataView(env);
292         LazyInitializeSharedArrayBuffer(env);
293     } else {
294         InitializeDate(env, objFuncClass);
295         InitializeSet(env, objFuncClass);
296         InitializeMap(env, objFuncClass);
297         InitializeWeakMap(env, objFuncClass);
298         InitializeWeakSet(env, objFuncClass);
299         InitializeWeakRef(env, objFuncClass);
300         InitializeFinalizationRegistry(env, objFuncClass);
301         InitializeTypedArray(env, objFuncClass);
302         InitializeArrayBuffer(env, objFuncClass);
303         InitializeDataView(env, objFuncClass);
304         InitializeSharedArrayBuffer(env, objFuncClass);
305     }
306     InitializeNumber(env, globalObject, primRefObjHClass);
307     InitializeObject(env, objFuncPrototype, objectFunction);
308     InitializeBoolean(env, primRefObjHClass);
309     InitializeRegExp(env);
310     InitializeString(env, primRefObjHClass);
311 
312     JSHandle<JSHClass> argumentsClass = factory_->CreateJSArguments(env);
313     env->SetArgumentsClass(thread_, argumentsClass);
314     SetArgumentsSharedAccessor(env);
315 
316     InitializeMath(env, objFuncPrototypeVal);
317     InitializeGlobalObject(env, globalObject);
318     InitializeAtomics(env, objFuncPrototypeVal);
319     InitializeJson(env, objFuncPrototypeVal);
320     InitializeIterator(env, objFuncClass);
321     InitializeAsyncIterator(env, objFuncClass);
322     InitializeAsyncFromSyncIterator(env, objFuncClass);
323     InitializeProxy(env);
324     InitializeReflect(env, objFuncPrototypeVal);
325     InitializeAsyncFunction(env, objFuncClass);
326     InitializeGenerator(env, objFuncClass);
327     InitializeAsyncGenerator(env, objFuncClass);
328     InitializeGeneratorFunction(env, objFuncClass);
329     InitializeAsyncGeneratorFunction(env, objFuncClass);
330     InitializePromise(env, objFuncClass);
331     InitializePromiseJob(env);
332 #ifdef ARK_SUPPORT_INTL
333     InitializeIntl(env, objFuncPrototypeVal);
334     if (lazyInit) {
335         LazyInitializeLocale(env);
336         LazyInitializeDateTimeFormat(env);
337         LazyInitializeNumberFormat(env);
338         LazyInitializeRelativeTimeFormat(env);
339         LazyInitializeCollator(env);
340         LazyInitializePluralRules(env);
341         LazyInitializeDisplayNames(env);
342         LazyInitializeListFormat(env);
343     } else {
344         InitializeLocale(env);
345         InitializeDateTimeFormat(env);
346         InitializeNumberFormat(env);
347         InitializeRelativeTimeFormat(env);
348         InitializeCollator(env);
349         InitializePluralRules(env);
350         InitializeDisplayNames(env);
351         InitializeListFormat(env);
352     }
353 #endif
354     InitializeModuleNamespace(env, objFuncClass);
355     InitializeCjsModule(env);
356     InitializeCjsExports(env);
357     InitializeCjsRequire(env);
358     InitializeDefaultExportOfScript(env);
359     InitializeFunctionHclassForOptimized(env);
360     JSHandle<JSHClass> generatorFuncClass =
361         factory_->CreateFunctionClass(FunctionKind::GENERATOR_FUNCTION, JSFunction::SIZE, JSType::JS_GENERATOR_FUNCTION,
362                                       env->GetGeneratorFunctionPrototype());
363     env->SetGeneratorFunctionClass(thread_, generatorFuncClass);
364 
365     JSHandle<JSHClass> asyncGenetatorFuncClass =
366         factory_->CreateFunctionClass(FunctionKind::ASYNC_GENERATOR_FUNCTION, JSFunction::SIZE,
367                                       JSType::JS_ASYNC_GENERATOR_FUNCTION, env->GetAsyncGeneratorFunctionPrototype());
368     env->SetAsyncGeneratorFunctionClass(thread_, asyncGenetatorFuncClass);
369     env->SetObjectFunctionPrototypeClass(thread_, JSTaggedValue(objFuncPrototype->GetClass()));
370     JSHandle<JSHClass> asyncFuncClass = factory_->CreateFunctionClass(
371         FunctionKind::ASYNC_FUNCTION, JSAsyncFunction::SIZE, JSType::JS_ASYNC_FUNCTION,
372         env->GetAsyncFunctionPrototype());
373     env->SetAsyncFunctionClass(thread_, asyncFuncClass);
374     thread_->ResetGuardians();
375 }
376 
InitializeFunctionHclassForOptimized(const JSHandle<GlobalEnv> & env) const377 void Builtins::InitializeFunctionHclassForOptimized(const JSHandle<GlobalEnv> &env) const
378 {
379 #define JSFUNCTION_JCLASS_LIST(V)                                                                             \
380     V(FunctionClassWithProto, FunctionKind::BASE_CONSTRUCTOR, JSFunction::SIZE, FUNCTION, Function)           \
381     V(FunctionClassWithoutProto, FunctionKind::NORMAL_FUNCTION, JSFunction::SIZE, FUNCTION, Function)         \
382     V(GeneratorFunctionClass, FunctionKind::GENERATOR_FUNCTION,                                               \
383         JSFunction::SIZE, GENERATOR_FUNCTION, GeneratorFunction)                                              \
384     V(AsyncFunctionClass, FunctionKind::ASYNC_FUNCTION, JSAsyncFunction::SIZE, ASYNC_FUNCTION, AsyncFunction) \
385     V(AsyncGeneratorFunctionClass, FunctionKind::ASYNC_GENERATOR_FUNCTION,                                    \
386         JSFunction::SIZE, ASYNC_GENERATOR_FUNCTION, AsyncGeneratorFunction)                                   \
387 
388 #define INITIALIZE_FUNCTION_HCLASS_FOR_OPTIMIZED(name, kind, size, type, prototype)         \
389     JSHandle<JSHClass> name##Optimized = factory_->CreateFunctionClass(kind, size,          \
390         JSType::JS_##type, env->Get##prototype##Prototype(), true, false);                  \
391     env->Set##name##Optimized(thread_, name##Optimized);                                    \
392     JSHandle<JSHClass> name##FastCall = factory_->CreateFunctionClass(kind, size,           \
393         JSType::JS_##type, env->Get##prototype##Prototype(), true, true);                   \
394     env->Set##name##OptimizedWithFastCall(thread_, name##FastCall);
395     JSFUNCTION_JCLASS_LIST(INITIALIZE_FUNCTION_HCLASS_FOR_OPTIMIZED)
396 #undef INITIALIZE_FUNCTION_HCLASS_FOR_OPTIMIZED
397 #undef JSFUNCTION_JCLASS_LIST
398 }
399 
SetLazyAccessor(const JSHandle<JSObject> & object,const JSHandle<JSTaggedValue> & key,const JSHandle<AccessorData> & accessor) const400 void Builtins::SetLazyAccessor(const JSHandle<JSObject> &object, const JSHandle<JSTaggedValue> &key,
401     const JSHandle<AccessorData> &accessor) const
402 {
403     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>::Cast(accessor), true, false, true);
404     JSObject::DefineOwnProperty(thread_, object, key, descriptor);
405 }
406 
InitializeForSnapshot(JSThread * thread)407 void Builtins::InitializeForSnapshot(JSThread *thread)
408 {
409     thread_ = thread;
410     vm_ = thread->GetEcmaVM();
411     factory_ = vm_->GetFactory();
412 
413     // Initialize ArkTools
414     if (vm_->GetJSOptions().EnableArkTools()) {
415         auto env = vm_->GetGlobalEnv();
416         auto globalObject = JSHandle<JSObject>::Cast(env->GetJSGlobalObject());
417         JSHandle<JSTaggedValue> arkTools(InitializeArkTools(env));
418         SetConstantObject(globalObject, "ArkTools", arkTools);
419     }
420 }
421 
InitializeGlobalObject(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & globalObject)422 void Builtins::InitializeGlobalObject(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &globalObject)
423 {
424     [[maybe_unused]] EcmaHandleScope scope(thread_);
425 
426     // Global object test
427     SetFunction(env, globalObject, "print", Global::PrintEntrypoint, 0);
428     SetFunction(env, globalObject, "markModuleCollectable", Global::MarkModuleCollectable, 0);
429 #if ECMASCRIPT_ENABLE_RUNTIME_STAT
430     SetFunction(env, globalObject, "startRuntimeStat", Global::StartRuntimeStat, 0);
431     SetFunction(env, globalObject, "stopRuntimeStat", Global::StopRuntimeStat, 0);
432 #endif
433 
434 #if ECMASCRIPT_ENABLE_OPT_CODE_PROFILER
435     SetFunction(env, globalObject, "printOptStat", Global::PrintOptStat, 0);
436 #endif
437 
438 #if ECMASCRIPT_ENABLE_FUNCTION_CALL_TIMER
439     SetFunction(env, globalObject, "printFunctionCallStat", Global::PrintFunctionCallStat, 0);
440 #endif
441 
442     if (vm_->GetJSOptions().EnableArkTools()) {
443         JSHandle<JSTaggedValue> arkTools(InitializeArkTools(env));
444         SetConstantObject(globalObject, "ArkTools", arkTools);
445     }
446 
447 #if ECMASCRIPT_ENABLE_ARK_CONTAINER
448     // Set ArkPrivate
449     JSHandle<JSTaggedValue> arkPrivate(InitializeArkPrivate(env));
450     SetConstantObject(globalObject, "ArkPrivate", arkPrivate);
451 #endif
452 
453     // Global object function
454     SetFunction(env, globalObject, "eval", Global::NotSupportEval, FunctionLength::ONE);
455     SetFunction(env, globalObject, "isFinite", Global::IsFinite, FunctionLength::ONE);
456     SetFunction(env, globalObject, "isNaN", Global::IsNaN, FunctionLength::ONE);
457     SetFunction(env, globalObject, "decodeURI", Global::DecodeURI, FunctionLength::ONE);
458     SetFunction(env, globalObject, "encodeURI", Global::EncodeURI, FunctionLength::ONE);
459     SetFunction(env, globalObject, "decodeURIComponent", Global::DecodeURIComponent, FunctionLength::ONE);
460     SetFunction(env, globalObject, "encodeURIComponent", Global::EncodeURIComponent, FunctionLength::ONE);
461 
462     // Global object property
463     SetGlobalThis(globalObject, "globalThis", JSHandle<JSTaggedValue>::Cast(globalObject));
464     SetConstant(globalObject, "Infinity", JSTaggedValue(base::POSITIVE_INFINITY));
465     SetConstant(globalObject, "NaN", JSTaggedValue(base::NAN_VALUE));
466     SetConstant(globalObject, "undefined", JSTaggedValue::Undefined());
467 }
468 
InitializeFunction(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & emptyFuncClass) const469 void Builtins::InitializeFunction(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &emptyFuncClass) const
470 {
471     [[maybe_unused]] EcmaHandleScope scope(thread_);
472     // Initialize Function.prototype
473     JSHandle<JSFunction> funcFuncPrototype = factory_->NewJSFunctionByHClass(
474         reinterpret_cast<void *>(Function::FunctionPrototypeInvokeSelf),
475         emptyFuncClass);
476     // ecma 19.2.3 The value of the name property of the Function prototype object is the empty String.
477     JSHandle<JSTaggedValue> emptyString(thread_->GlobalConstants()->GetHandledEmptyString());
478     JSHandle<JSTaggedValue> undefinedString(thread_, JSTaggedValue::Undefined());
479     JSFunction::SetFunctionName(thread_, JSHandle<JSFunctionBase>(funcFuncPrototype), emptyString, undefinedString);
480     // ecma 19.2.3 The value of the length property of the Function prototype object is 0.
481     JSFunction::SetFunctionLength(thread_, funcFuncPrototype, JSTaggedValue(FunctionLength::ZERO));
482 
483     JSHandle<JSTaggedValue> funcFuncPrototypeValue(funcFuncPrototype);
484     // Function.prototype_or_hclass
485     JSHandle<JSHClass> funcFuncIntanceHClass =
486         factory_->NewEcmaHClass(JSFunction::SIZE, JSType::JS_FUNCTION, funcFuncPrototypeValue);
487     funcFuncIntanceHClass->SetConstructor(true);
488 
489     // Function = new Function() (forbidden use NewBuiltinConstructor)
490     JSHandle<JSFunction> funcFunc =
491         factory_->NewJSFunctionByHClass(reinterpret_cast<void *>(Function::FunctionConstructor),
492         funcFuncIntanceHClass, FunctionKind::BUILTIN_CONSTRUCTOR);
493 
494     auto funcFuncPrototypeObj = JSHandle<JSObject>(funcFuncPrototype);
495     InitializeCtor(env, funcFuncPrototypeObj, funcFunc, "Function", FunctionLength::ONE);
496 
497     funcFunc->SetFunctionPrototype(thread_, funcFuncIntanceHClass.GetTaggedValue());
498     env->SetFunctionFunction(thread_, funcFunc);
499     env->SetFunctionPrototype(thread_, funcFuncPrototype);
500 
501     JSHandle<JSHClass> normalFuncClass =
502         factory_->NewEcmaHClass(JSFunction::SIZE, JSType::JS_FUNCTION, env->GetFunctionPrototype());
503     env->SetNormalFunctionClass(thread_, normalFuncClass);
504 
505     JSHandle<JSHClass> jSIntlBoundFunctionClass =
506         factory_->CreateFunctionClass(FunctionKind::NORMAL_FUNCTION, JSIntlBoundFunction::SIZE,
507                                       JSType::JS_INTL_BOUND_FUNCTION, env->GetFunctionPrototype());
508     env->SetJSIntlBoundFunctionClass(thread_, jSIntlBoundFunctionClass);
509 
510     JSHandle<JSHClass> constructorFunctionClass =
511         factory_->NewEcmaHClass(JSFunction::SIZE, JSType::JS_FUNCTION, env->GetFunctionPrototype());
512     constructorFunctionClass->SetConstructor(true);
513     env->SetConstructorFunctionClass(thread_, constructorFunctionClass);
514 
515     StrictModeForbiddenAccessCallerArguments(env, funcFuncPrototypeObj);
516 
517     // Function.prototype method
518     // 19.2.3.1 Function.prototype.apply ( thisArg, argArray )
519     SetFunction(env, funcFuncPrototypeObj, "apply", Function::FunctionPrototypeApply, FunctionLength::TWO);
520     // 19.2.3.2 Function.prototype.bind ( thisArg , ...args)
521     SetFunction(env, funcFuncPrototypeObj, "bind", Function::FunctionPrototypeBind, FunctionLength::ONE);
522     // 19.2.3.3 Function.prototype.call (thisArg , ...args)
523     SetFunction(env, funcFuncPrototypeObj, "call", Function::FunctionPrototypeCall, FunctionLength::ONE);
524     // 19.2.3.5 Function.prototype.toString ( )
525     SetFunction(env, funcFuncPrototypeObj, thread_->GlobalConstants()->GetHandledToStringString(),
526                 Function::FunctionPrototypeToString, FunctionLength::ZERO);
527 }
528 
InitializeObject(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & objFuncPrototype,const JSHandle<JSObject> & objFunc)529 void Builtins::InitializeObject(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &objFuncPrototype,
530                                 const JSHandle<JSObject> &objFunc)
531 {
532     [[maybe_unused]] EcmaHandleScope scope(thread_);
533     // Object method.
534     // 19.1.2.1Object.assign ( target, ...sources )
535     SetFunction(env, objFunc, "assign", Object::Assign, FunctionLength::TWO);
536     // 19.1.2.2Object.create ( O [ , Properties ] )
537     SetFunction(env, objFunc, "create", Object::Create, FunctionLength::TWO);
538     // 19.1.2.3Object.defineProperties ( O, Properties )
539     SetFunction(env, objFunc, "defineProperties", Object::DefineProperties, FunctionLength::TWO);
540     // 19.1.2.4Object.defineProperty ( O, P, Attributes )
541     SetFunction(env, objFunc, "defineProperty", Object::DefineProperty, FunctionLength::THREE);
542     // 19.1.2.5Object.freeze ( O )
543     SetFunction(env, objFunc, "freeze", Object::Freeze, FunctionLength::ONE);
544     // 19.1.2.6Object.getOwnPropertyDescriptor ( O, P )
545     SetFunction(env, objFunc, "getOwnPropertyDescriptor", Object::GetOwnPropertyDescriptor, FunctionLength::TWO);
546     // 19.1.2.7Object.getOwnPropertyNames ( O )
547     SetFunction(env, objFunc, "getOwnPropertyNames", Object::GetOwnPropertyNames, FunctionLength::ONE);
548     // 19.1.2.8Object.getOwnPropertySymbols ( O )
549     SetFunction(env, objFunc, "getOwnPropertySymbols", Object::GetOwnPropertySymbols, FunctionLength::ONE);
550     // 19.1.2.9Object.getPrototypeOf ( O )
551     SetFunction(env, objFunc, "getPrototypeOf", Object::GetPrototypeOf, FunctionLength::ONE);
552     // 19.1.2.10Object.is ( value1, value2 )
553     SetFunction(env, objFunc, "is", Object::Is, 2);
554     // 19.1.2.11Object.isExtensible ( O )
555     SetFunction(env, objFunc, "isExtensible", Object::IsExtensible, FunctionLength::ONE);
556     // 19.1.2.12Object.isFrozen ( O )
557     SetFunction(env, objFunc, "isFrozen", Object::IsFrozen, FunctionLength::ONE);
558     // 19.1.2.13Object.isSealed ( O )
559     SetFunction(env, objFunc, "isSealed", Object::IsSealed, FunctionLength::ONE);
560     // 19.1.2.14 Object.keys(O)
561     SetFunction(env, objFunc, "keys", Object::Keys, FunctionLength::ONE);
562     // 20.1.2.22 Object.values(O)
563     SetFunction(env, objFunc, "values", Object::Values, FunctionLength::ONE);
564     // 19.1.2.15 Object.preventExtensions(O)
565     SetFunction(env, objFunc, "preventExtensions", Object::PreventExtensions, FunctionLength::ONE);
566     // 19.1.2.17 Object.seal(O)
567     SetFunction(env, objFunc, "seal", Object::Seal, FunctionLength::ONE);
568     // 19.1.2.18 Object.setPrototypeOf(O, proto)
569     SetFunction(env, objFunc, "setPrototypeOf", Object::SetPrototypeOf, FunctionLength::TWO);
570     // 20.1.2.5 Object.entries ( O )
571     SetFunction(env, objFunc, "entries", Object::Entries, FunctionLength::ONE);
572     // 20.1.2.7 Object.fromEntries ( iterable )
573     SetFunction(env, objFunc, "fromEntries", Object::FromEntries, FunctionLength::ONE);
574     // 20.1.2.13 Object.hasOwn ( O, P )
575     SetFunction(env, objFunc, "hasOwn", Object::HasOwn, FunctionLength::TWO);
576 
577     // Object.property method
578     // 19.1.3.2 Object.prototype.hasOwnProperty(V)
579     SetFunction(env, objFuncPrototype, "hasOwnProperty", Object::HasOwnProperty, FunctionLength::ONE);
580     // 19.1.3.3 Object.prototype.isPrototypeOf(V)
581     SetFunction(env, objFuncPrototype, "isPrototypeOf", Object::IsPrototypeOf, FunctionLength::ONE);
582     // 19.1.3.4 Object.prototype.propertyIsEnumerable(V)
583     SetFunction(env, objFuncPrototype, "propertyIsEnumerable", Object::PropertyIsEnumerable, FunctionLength::ONE);
584     // 19.1.3.5 Object.prototype.toLocaleString([reserved1[, reserved2]])
585     SetFunction(env, objFuncPrototype, "toLocaleString", Object::ToLocaleString, FunctionLength::ZERO);
586     // 19.1.3.6 Object.prototype.toString()
587     SetFunction(env, objFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(), Object::ToString,
588                 FunctionLength::ZERO);
589     // 19.1.3.7 Object.prototype.valueOf()
590     SetFunction(env, objFuncPrototype, thread_->GlobalConstants()->GetHandledValueOfString(), Object::ValueOf,
591                 FunctionLength::ZERO);
592 
593     SetFunction(env, objFuncPrototype, "createRealm", Object::CreateRealm, FunctionLength::ZERO);
594 
595     // B.2.2.1 Object.prototype.__proto__
596     JSHandle<JSTaggedValue> protoKey(factory_->NewFromASCII("__proto__"));
597     JSHandle<JSTaggedValue> protoGetter = CreateGetter(env, Object::ProtoGetter, "__proto__", FunctionLength::ZERO);
598     JSHandle<JSTaggedValue> protoSetter = CreateSetter(env, Object::ProtoSetter, "__proto__", FunctionLength::ONE);
599     SetAccessor(objFuncPrototype, protoKey, protoGetter, protoSetter);
600 }
601 
InitializeSymbol(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const602 void Builtins::InitializeSymbol(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
603 {
604     [[maybe_unused]] EcmaHandleScope scope(thread_);
605     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
606     // Symbol.prototype
607     JSHandle<JSObject> symbolFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
608     JSHandle<JSTaggedValue> symbolFuncPrototypeValue(symbolFuncPrototype);
609 
610     // Symbol.prototype_or_hclass
611     JSHandle<JSHClass> symbolFuncInstanceHClass =
612         factory_->NewEcmaHClass(JSPrimitiveRef::SIZE, JSType::JS_PRIMITIVE_REF, symbolFuncPrototypeValue);
613 
614     // Symbol = new Function()
615     JSHandle<JSObject> symbolFunction(
616         NewBuiltinConstructor(env, symbolFuncPrototype, Symbol::SymbolConstructor, "Symbol", FunctionLength::ZERO));
617     JSHandle<JSFunction>(symbolFunction)->SetFunctionPrototype(thread_, symbolFuncInstanceHClass.GetTaggedValue());
618 
619     // "constructor" property on the prototype
620     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
621     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>::Cast(symbolFunction), true, false, true);
622     JSObject::DefineOwnProperty(thread_, symbolFuncPrototype, constructorKey, descriptor);
623 
624     SetFunction(env, symbolFunction, "for", Symbol::For, FunctionLength::ONE);
625     SetFunction(env, symbolFunction, "keyFor", Symbol::KeyFor, FunctionLength::ONE);
626 
627     // Symbol attribute
628     JSHandle<JSTaggedValue> hasInstanceSymbol(factory_->NewWellKnownSymbolWithChar("Symbol.hasInstance"));
629     SetNoneAttributeProperty(symbolFunction, "hasInstance", hasInstanceSymbol);
630     JSHandle<JSTaggedValue> isConcatSpreadableSymbol(factory_->NewWellKnownSymbolWithChar("Symbol.isConcatSpreadable"));
631     SetNoneAttributeProperty(symbolFunction, "isConcatSpreadable", isConcatSpreadableSymbol);
632     JSHandle<JSTaggedValue> toStringTagSymbol(factory_->NewWellKnownSymbolWithChar("Symbol.toStringTag"));
633     SetNoneAttributeProperty(symbolFunction, "toStringTag", toStringTagSymbol);
634     JSHandle<JSTaggedValue> iteratorSymbol(factory_->NewPublicSymbolWithChar("Symbol.iterator"));
635     SetNoneAttributeProperty(symbolFunction, "iterator", iteratorSymbol);
636     JSHandle<JSTaggedValue> asyncIteratorSymbol(factory_->NewPublicSymbolWithChar("Symbol.asyncIterator"));
637     SetNoneAttributeProperty(symbolFunction, "asyncIterator", asyncIteratorSymbol);
638     JSHandle<JSTaggedValue> matchSymbol(factory_->NewPublicSymbolWithChar("Symbol.match"));
639     SetNoneAttributeProperty(symbolFunction, "match", matchSymbol);
640     JSHandle<JSTaggedValue> matchAllSymbol(factory_->NewPublicSymbolWithChar("Symbol.matchAll"));
641     SetNoneAttributeProperty(symbolFunction, "matchAll", matchAllSymbol);
642     JSHandle<JSTaggedValue> replaceSymbol(factory_->NewPublicSymbolWithChar("Symbol.replace"));
643     SetNoneAttributeProperty(symbolFunction, "replace", replaceSymbol);
644     JSHandle<JSTaggedValue> searchSymbol(factory_->NewPublicSymbolWithChar("Symbol.search"));
645     SetNoneAttributeProperty(symbolFunction, "search", searchSymbol);
646     JSHandle<JSTaggedValue> speciesSymbol(factory_->NewPublicSymbolWithChar("Symbol.species"));
647     SetNoneAttributeProperty(symbolFunction, "species", speciesSymbol);
648     JSHandle<JSTaggedValue> splitSymbol(factory_->NewPublicSymbolWithChar("Symbol.split"));
649     SetNoneAttributeProperty(symbolFunction, "split", splitSymbol);
650     JSHandle<JSTaggedValue> toPrimitiveSymbol(factory_->NewPublicSymbolWithChar("Symbol.toPrimitive"));
651     SetNoneAttributeProperty(symbolFunction, "toPrimitive", toPrimitiveSymbol);
652     JSHandle<JSTaggedValue> unscopablesSymbol(factory_->NewPublicSymbolWithChar("Symbol.unscopables"));
653     SetNoneAttributeProperty(symbolFunction, "unscopables", unscopablesSymbol);
654     JSHandle<JSTaggedValue> attachSymbol(factory_->NewPublicSymbolWithChar("Symbol.attach"));
655     SetNoneAttributeProperty(symbolFunction, "attach", attachSymbol);
656     JSHandle<JSTaggedValue> detachSymbol(factory_->NewPublicSymbolWithChar("Symbol.detach"));
657     SetNoneAttributeProperty(symbolFunction, "detach", detachSymbol);
658 
659     // symbol.prototype.description
660     PropertyDescriptor descriptionDesc(thread_);
661     JSHandle<JSTaggedValue> getterKey(factory_->NewFromASCII("description"));
662     JSHandle<JSTaggedValue> getter(factory_->NewJSFunction(env, reinterpret_cast<void *>(Symbol::DescriptionGetter)));
663     SetGetter(symbolFuncPrototype, getterKey, getter);
664 
665     // Setup symbol.prototype[@@toPrimitive]
666     SetFunctionAtSymbol<JSSymbol::SYMBOL_TO_PRIMITIVE_TYPE>(
667         env, symbolFuncPrototype, toPrimitiveSymbol, "[Symbol.toPrimitive]", Symbol::ToPrimitive, FunctionLength::ONE);
668     // install the Symbol.prototype methods
669     SetFunction(env, symbolFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(), Symbol::ToString,
670                 FunctionLength::ZERO);
671     SetFunction(env, symbolFuncPrototype, thread_->GlobalConstants()->GetHandledValueOfString(), Symbol::ValueOf,
672                 FunctionLength::ZERO);
673 
674     env->SetSymbolFunction(thread_, symbolFunction);
675     env->SetHasInstanceSymbol(thread_, hasInstanceSymbol);
676     env->SetIsConcatSpreadableSymbol(thread_, isConcatSpreadableSymbol);
677     env->SetToStringTagSymbol(thread_, toStringTagSymbol);
678     env->SetIteratorSymbol(thread_, iteratorSymbol);
679     env->SetAsyncIteratorSymbol(thread_, asyncIteratorSymbol);
680     env->SetMatchSymbol(thread_, matchSymbol);
681     env->SetMatchAllSymbol(thread_, matchAllSymbol);
682     env->SetReplaceSymbol(thread_, replaceSymbol);
683     env->SetSearchSymbol(thread_, searchSymbol);
684     env->SetSpeciesSymbol(thread_, speciesSymbol);
685     env->SetSplitSymbol(thread_, splitSymbol);
686     env->SetToPrimitiveSymbol(thread_, toPrimitiveSymbol);
687     env->SetUnscopablesSymbol(thread_, unscopablesSymbol);
688     env->SetAttachSymbol(thread_, attachSymbol);
689     env->SetDetachSymbol(thread_, detachSymbol);
690 
691     // Setup %SymbolPrototype%
692     SetStringTagSymbol(env, symbolFuncPrototype, "Symbol");
693 
694     JSHandle<JSTaggedValue> holeySymbol(factory_->NewPrivateNameSymbolWithChar("holey"));
695     env->SetHoleySymbol(thread_, holeySymbol.GetTaggedValue());
696     JSHandle<JSTaggedValue> elementIcSymbol(factory_->NewPrivateNameSymbolWithChar("element-ic"));
697     env->SetElementICSymbol(thread_, elementIcSymbol.GetTaggedValue());
698 
699     // ecma 19.2.3.6 Function.prototype[@@hasInstance] ( V )
700     JSHandle<JSObject> funcFuncPrototypeObj = JSHandle<JSObject>(env->GetFunctionPrototype());
701     SetFunctionAtSymbol<JSSymbol::SYMBOL_HAS_INSTANCE_TYPE>(
702         env, funcFuncPrototypeObj, env->GetHasInstanceSymbol(), "[Symbol.hasInstance]",
703         Function::FunctionPrototypeHasInstance, FunctionLength::ONE);
704 }
705 
InitializeSymbolWithRealm(const JSHandle<GlobalEnv> & realm,const JSHandle<JSHClass> & objFuncInstanceHClass)706 void Builtins::InitializeSymbolWithRealm(const JSHandle<GlobalEnv> &realm,
707                                          const JSHandle<JSHClass> &objFuncInstanceHClass)
708 {
709     [[maybe_unused]] EcmaHandleScope scope(thread_);
710     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
711     // Symbol.prototype
712     JSHandle<JSObject> symbolFuncPrototype = factory_->NewJSObjectWithInit(objFuncInstanceHClass);
713     JSHandle<JSTaggedValue> symbolFuncPrototypeValue(symbolFuncPrototype);
714 
715     // Symbol.prototype_or_hclass
716     JSHandle<JSHClass> symbolFuncInstanceHClass =
717         factory_->NewEcmaHClass(JSPrimitiveRef::SIZE, JSType::JS_PRIMITIVE_REF, symbolFuncPrototypeValue);
718 
719     // Symbol = new Function()
720     JSHandle<JSObject> symbolFunction(
721         NewBuiltinConstructor(realm, symbolFuncPrototype, Symbol::SymbolConstructor, "Symbol", FunctionLength::ZERO));
722     JSHandle<JSFunction>(symbolFunction)->SetFunctionPrototype(thread_, symbolFuncInstanceHClass.GetTaggedValue());
723 
724     // "constructor" property on the prototype
725     JSHandle<JSTaggedValue> constructorKey = thread_->GlobalConstants()->GetHandledConstructorString();
726     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>::Cast(symbolFunction), true, false, true);
727     JSObject::DefineOwnProperty(thread_, symbolFuncPrototype, constructorKey, descriptor);
728 
729     SetFunction(realm, symbolFunction, "for", Symbol::For, FunctionLength::ONE);
730     SetFunction(realm, symbolFunction, "keyFor", Symbol::KeyFor, FunctionLength::ONE);
731 
732     // Symbol attribute
733     SetNoneAttributeProperty(symbolFunction, "hasInstance", env->GetHasInstanceSymbol());
734     SetNoneAttributeProperty(symbolFunction, "isConcatSpreadable", env->GetIsConcatSpreadableSymbol());
735     SetNoneAttributeProperty(symbolFunction, "toStringTag", env->GetToStringTagSymbol());
736     SetNoneAttributeProperty(symbolFunction, "iterator", env->GetIteratorSymbol());
737     SetNoneAttributeProperty(symbolFunction, "asyncIterator", env->GetAsyncIteratorSymbol());
738     SetNoneAttributeProperty(symbolFunction, "match", env->GetMatchSymbol());
739     SetNoneAttributeProperty(symbolFunction, "matchAll", env->GetMatchAllSymbol());
740     SetNoneAttributeProperty(symbolFunction, "replace", env->GetReplaceSymbol());
741     SetNoneAttributeProperty(symbolFunction, "search", env->GetSearchSymbol());
742     SetNoneAttributeProperty(symbolFunction, "species", env->GetSpeciesSymbol());
743     SetNoneAttributeProperty(symbolFunction, "split", env->GetSplitSymbol());
744     SetNoneAttributeProperty(symbolFunction, "toPrimitive", env->GetToPrimitiveSymbol());
745     SetNoneAttributeProperty(symbolFunction, "unscopables", env->GetUnscopablesSymbol());
746     SetNoneAttributeProperty(symbolFunction, "attach", env->GetAttachSymbol());
747     SetNoneAttributeProperty(symbolFunction, "detach", env->GetDetachSymbol());
748 
749     // symbol.prototype.description
750     PropertyDescriptor descriptionDesc(thread_);
751     JSHandle<JSTaggedValue> getterKey(factory_->NewFromASCII("description"));
752     JSHandle<JSTaggedValue> getter(factory_->NewJSFunction(realm, reinterpret_cast<void *>(Symbol::DescriptionGetter)));
753     SetGetter(symbolFuncPrototype, getterKey, getter);
754 
755     // Setup symbol.prototype[@@toPrimitive]
756     SetFunctionAtSymbol<JSSymbol::SYMBOL_TO_PRIMITIVE_TYPE>(realm, symbolFuncPrototype, env->GetToPrimitiveSymbol(),
757                                                             "[Symbol.toPrimitive]", Symbol::ToPrimitive,
758                                                             FunctionLength::ONE);
759     // install the Symbol.prototype methods
760     SetFunction(realm, symbolFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(), Symbol::ToString,
761                 FunctionLength::ZERO);
762     SetFunction(realm, symbolFuncPrototype, thread_->GlobalConstants()->GetHandledValueOfString(), Symbol::ValueOf,
763                 FunctionLength::ZERO);
764 
765     realm->SetSymbolFunction(thread_, symbolFunction);
766     realm->SetHasInstanceSymbol(thread_, env->GetHasInstanceSymbol());
767     realm->SetIsConcatSpreadableSymbol(thread_, env->GetIsConcatSpreadableSymbol());
768     realm->SetToStringTagSymbol(thread_, env->GetToStringTagSymbol());
769     realm->SetIteratorSymbol(thread_, env->GetIteratorSymbol());
770     realm->SetAsyncIteratorSymbol(thread_, env->GetAsyncIteratorSymbol());
771     realm->SetMatchSymbol(thread_, env->GetMatchSymbol());
772     realm->SetMatchAllSymbol(thread_, env->GetMatchAllSymbol());
773     realm->SetReplaceSymbol(thread_, env->GetReplaceSymbol());
774     realm->SetSearchSymbol(thread_, env->GetSearchSymbol());
775     realm->SetSpeciesSymbol(thread_, env->GetSpeciesSymbol());
776     realm->SetSplitSymbol(thread_, env->GetSplitSymbol());
777     realm->SetToPrimitiveSymbol(thread_, env->GetToPrimitiveSymbol());
778     realm->SetUnscopablesSymbol(thread_, env->GetUnscopablesSymbol());
779     realm->SetAttachSymbol(thread_, env->GetAttachSymbol());
780     realm->SetDetachSymbol(thread_, env->GetDetachSymbol());
781 
782     // Setup %SymbolPrototype%
783     SetStringTagSymbol(realm, symbolFuncPrototype, "Symbol");
784 
785     JSHandle<JSTaggedValue> holeySymbol(factory_->NewPrivateNameSymbolWithChar("holey"));
786     realm->SetHoleySymbol(thread_, holeySymbol.GetTaggedValue());
787     JSHandle<JSTaggedValue> elementIcSymbol(factory_->NewPrivateNameSymbolWithChar("element-ic"));
788     realm->SetElementICSymbol(thread_, elementIcSymbol.GetTaggedValue());
789 
790     // ecma 19.2.3.6 Function.prototype[@@hasInstance] ( V )
791     JSHandle<JSObject> funcFuncPrototypeObj = JSHandle<JSObject>(realm->GetFunctionPrototype());
792     SetFunctionAtSymbol<JSSymbol::SYMBOL_HAS_INSTANCE_TYPE>(
793         realm, funcFuncPrototypeObj, realm->GetHasInstanceSymbol(), "[Symbol.hasInstance]",
794         Function::FunctionPrototypeHasInstance, FunctionLength::ONE);
795 }
796 
InitializeNumber(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & globalObject,const JSHandle<JSHClass> & primRefObjHClass)797 void Builtins::InitializeNumber(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &globalObject,
798                                 const JSHandle<JSHClass> &primRefObjHClass)
799 {
800     [[maybe_unused]] EcmaHandleScope scope(thread_);
801     // Number.prototype
802     JSHandle<JSTaggedValue> toObject(thread_, JSTaggedValue(FunctionLength::ZERO));
803     JSHandle<JSObject> numFuncPrototype =
804         JSHandle<JSObject>::Cast(factory_->NewJSPrimitiveRef(primRefObjHClass, toObject));
805     JSHandle<JSTaggedValue> numFuncPrototypeValue(numFuncPrototype);
806 
807     // Number.prototype_or_hclass
808     JSHandle<JSHClass> numFuncInstanceHClass =
809         factory_->NewEcmaHClass(JSPrimitiveRef::SIZE, JSType::JS_PRIMITIVE_REF, numFuncPrototypeValue);
810 
811     // Number = new Function()
812     JSHandle<JSObject> numFunction(
813         NewBuiltinConstructor(env, numFuncPrototype, Number::NumberConstructor, "Number", FunctionLength::ONE));
814     numFunction.GetObject<JSFunction>()->SetFunctionPrototype(thread_, numFuncInstanceHClass.GetTaggedValue());
815 
816     // Number.prototype method
817     SetFunction(env, numFuncPrototype, "toExponential", Number::ToExponential, FunctionLength::ONE);
818     SetFunction(env, numFuncPrototype, "toFixed", Number::ToFixed, FunctionLength::ONE);
819     SetFunction(env, numFuncPrototype, "toLocaleString", Number::ToLocaleString, FunctionLength::ZERO);
820     SetFunction(env, numFuncPrototype, "toPrecision", Number::ToPrecision, FunctionLength::ONE);
821     SetFunction(env, numFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(), Number::ToString,
822                 FunctionLength::ONE);
823     SetFunction(env, numFuncPrototype, thread_->GlobalConstants()->GetHandledValueOfString(), Number::ValueOf,
824                 FunctionLength::ZERO);
825 
826     // Number method
827     SetFunction(env, numFunction, "isFinite", Number::IsFinite, FunctionLength::ONE);
828     SetFunction(env, numFunction, "isInteger", Number::IsInteger, FunctionLength::ONE);
829     SetFunction(env, numFunction, "isNaN", Number::IsNaN, FunctionLength::ONE);
830     SetFunction(env, numFunction, "isSafeInteger", Number::IsSafeInteger, FunctionLength::ONE);
831     SetFuncToObjAndGlobal(env, globalObject, numFunction, "parseFloat", Number::ParseFloat, FunctionLength::ONE);
832     SetFuncToObjAndGlobal(env, globalObject, numFunction, "parseInt", Number::ParseInt, FunctionLength::TWO);
833 
834     // Number constant
835     const double epsilon = 2.220446049250313e-16;
836     const double maxSafeInteger = 9007199254740991;
837     const double maxValue = 1.7976931348623157e+308;
838     const double minValue = 5e-324;
839     const double positiveInfinity = std::numeric_limits<double>::infinity();
840     SetConstant(numFunction, "MAX_VALUE", JSTaggedValue(maxValue));
841     SetConstant(numFunction, "MIN_VALUE", JSTaggedValue(minValue));
842     SetConstant(numFunction, "NaN", JSTaggedValue(NAN));
843     SetConstant(numFunction, "NEGATIVE_INFINITY", JSTaggedValue(-positiveInfinity));
844     SetConstant(numFunction, "POSITIVE_INFINITY", JSTaggedValue(positiveInfinity));
845     SetConstant(numFunction, "MAX_SAFE_INTEGER", JSTaggedValue(maxSafeInteger));
846     SetConstant(numFunction, "MIN_SAFE_INTEGER", JSTaggedValue(-maxSafeInteger));
847     SetConstant(numFunction, "EPSILON", JSTaggedValue(epsilon));
848 
849     env->SetNumberFunction(thread_, numFunction);
850 }
InitializeBigIntWithRealm(const JSHandle<GlobalEnv> & realm) const851 void Builtins::InitializeBigIntWithRealm(const JSHandle<GlobalEnv> &realm) const
852 {
853     [[maybe_unused]] EcmaHandleScope scope(thread_);
854     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
855     realm->SetBigIntFunction(thread_, env->GetBigIntFunction());
856 
857     JSHandle<JSTaggedValue> nameString(factory_->NewFromASCII("BigInt"));
858     JSHandle<JSObject> globalObject(thread_, realm->GetGlobalObject());
859     PropertyDescriptor descriptor(thread_, env->GetBigIntFunction(), true, false, true);
860     JSObject::DefineOwnProperty(thread_, globalObject, nameString, descriptor);
861 }
862 
InitializeBigInt(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & primRefObjHClass) const863 void Builtins::InitializeBigInt(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &primRefObjHClass) const
864 {
865     [[maybe_unused]] EcmaHandleScope scope(thread_);
866     // BigInt.prototype
867     JSHandle<JSObject> bigIntFuncPrototype = factory_->NewJSObjectWithInit(primRefObjHClass);
868     JSHandle<JSTaggedValue> bigIntFuncPrototypeValue(bigIntFuncPrototype);
869 
870     // BigInt.prototype_or_hclass
871     JSHandle<JSHClass> bigIntFuncInstanceHClass =
872         factory_->NewEcmaHClass(JSPrimitiveRef::SIZE, JSType::JS_PRIMITIVE_REF, bigIntFuncPrototypeValue);
873     // BigInt = new Function()
874     JSHandle<JSObject> bigIntFunction(
875         NewBuiltinConstructor(env, bigIntFuncPrototype,
876                               BuiltinsBigInt::BigIntConstructor, "BigInt", FunctionLength::ONE));
877     JSHandle<JSFunction>(bigIntFunction)->SetFunctionPrototype(thread_, bigIntFuncInstanceHClass.GetTaggedValue());
878 
879     // BigInt.prototype method
880     SetFunction(env, bigIntFuncPrototype, "toLocaleString", BuiltinsBigInt::ToLocaleString, FunctionLength::ZERO);
881     SetFunction(env, bigIntFuncPrototype, "toString", BuiltinsBigInt::ToString, FunctionLength::ZERO);
882     SetFunction(env, bigIntFuncPrototype, "valueOf", BuiltinsBigInt::ValueOf, FunctionLength::ZERO);
883 
884     // BigInt method
885     SetFunction(env, bigIntFunction, "asUintN", BuiltinsBigInt::AsUintN, FunctionLength::TWO);
886     SetFunction(env, bigIntFunction, "asIntN", BuiltinsBigInt::AsIntN, FunctionLength::TWO);
887 
888     // @@ToStringTag
889     SetStringTagSymbol(env, bigIntFuncPrototype, "BigInt");
890     env->SetBigIntFunction(thread_, bigIntFunction);
891 }
892 
InitializeDate(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const893 void Builtins::InitializeDate(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
894 {
895     [[maybe_unused]] EcmaHandleScope scope(thread_);
896     constexpr int utcLength = 7;
897     // Date.prototype
898     JSHandle<JSObject> dateFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
899     JSHandle<JSTaggedValue> dateFuncPrototypeValue(dateFuncPrototype);
900 
901     // Date.prototype_or_hclass
902     JSHandle<JSHClass> dateFuncInstanceHClass =
903         factory_->NewEcmaHClass(JSDate::SIZE, JSType::JS_DATE, dateFuncPrototypeValue);
904 
905     // Date = new Function()
906     JSHandle<JSObject> dateFunction(
907         NewBuiltinConstructor(env, dateFuncPrototype, Date::DateConstructor, "Date", FunctionLength::ONE,
908                               BUILTINS_STUB_ID(DateConstructor)));
909     JSHandle<JSFunction>(dateFunction)->SetFunctionPrototype(thread_, dateFuncInstanceHClass.GetTaggedValue());
910 
911     // Date.prototype method
912     SetFunction(env, dateFuncPrototype, "getDate", Date::GetDate, FunctionLength::ZERO);
913     SetFunction(env, dateFuncPrototype, "getDay", Date::GetDay, FunctionLength::ZERO);
914     SetFunction(env, dateFuncPrototype, "getFullYear", Date::GetFullYear, FunctionLength::ZERO);
915     SetFunction(env, dateFuncPrototype, "getHours", Date::GetHours, FunctionLength::ZERO);
916     SetFunction(env, dateFuncPrototype, "getMilliseconds", Date::GetMilliseconds, FunctionLength::ZERO);
917     SetFunction(env, dateFuncPrototype, "getMinutes", Date::GetMinutes, FunctionLength::ZERO);
918     SetFunction(env, dateFuncPrototype, "getMonth", Date::GetMonth, FunctionLength::ZERO);
919     SetFunction(env, dateFuncPrototype, "getSeconds", Date::GetSeconds, FunctionLength::ZERO);
920     SetFunction(env, dateFuncPrototype, "getTime", Date::GetTime, FunctionLength::ZERO);
921     SetFunction(env, dateFuncPrototype, "getTimezoneOffset", Date::GetTimezoneOffset, FunctionLength::ZERO);
922     SetFunction(env, dateFuncPrototype, "getUTCDate", Date::GetUTCDate, FunctionLength::ZERO);
923     SetFunction(env, dateFuncPrototype, "getUTCDay", Date::GetUTCDay, FunctionLength::ZERO);
924     SetFunction(env, dateFuncPrototype, "getUTCFullYear", Date::GetUTCFullYear, FunctionLength::ZERO);
925     SetFunction(env, dateFuncPrototype, "getUTCHours", Date::GetUTCHours, FunctionLength::ZERO);
926     SetFunction(env, dateFuncPrototype, "getUTCMilliseconds", Date::GetUTCMilliseconds, FunctionLength::ZERO);
927     SetFunction(env, dateFuncPrototype, "getUTCMinutes", Date::GetUTCMinutes, FunctionLength::ZERO);
928     SetFunction(env, dateFuncPrototype, "getUTCMonth", Date::GetUTCMonth, FunctionLength::ZERO);
929     SetFunction(env, dateFuncPrototype, "getUTCSeconds", Date::GetUTCSeconds, FunctionLength::ZERO);
930 
931     SetFunction(env, dateFuncPrototype, "setDate", Date::SetDate, FunctionLength::ONE);
932     SetFunction(env, dateFuncPrototype, "setFullYear", Date::SetFullYear, FunctionLength::THREE);
933     SetFunction(env, dateFuncPrototype, "setHours", Date::SetHours, FunctionLength::FOUR);
934     SetFunction(env, dateFuncPrototype, "setMilliseconds", Date::SetMilliseconds, FunctionLength::ONE);
935     SetFunction(env, dateFuncPrototype, "setMinutes", Date::SetMinutes, FunctionLength::THREE);
936     SetFunction(env, dateFuncPrototype, "setMonth", Date::SetMonth, FunctionLength::TWO);
937     SetFunction(env, dateFuncPrototype, "setSeconds", Date::SetSeconds, FunctionLength::TWO);
938     SetFunction(env, dateFuncPrototype, "setTime", Date::SetTime, FunctionLength::ONE);
939     SetFunction(env, dateFuncPrototype, "setUTCDate", Date::SetUTCDate, FunctionLength::ONE);
940     SetFunction(env, dateFuncPrototype, "setUTCFullYear", Date::SetUTCFullYear, FunctionLength::THREE);
941     SetFunction(env, dateFuncPrototype, "setUTCHours", Date::SetUTCHours, FunctionLength::FOUR);
942     SetFunction(env, dateFuncPrototype, "setUTCMilliseconds", Date::SetUTCMilliseconds, FunctionLength::ONE);
943     SetFunction(env, dateFuncPrototype, "setUTCMinutes", Date::SetUTCMinutes, FunctionLength::THREE);
944     SetFunction(env, dateFuncPrototype, "setUTCMonth", Date::SetUTCMonth, FunctionLength::TWO);
945     SetFunction(env, dateFuncPrototype, "setUTCSeconds", Date::SetUTCSeconds, FunctionLength::TWO);
946 
947     SetFunction(env, dateFuncPrototype, "toDateString", Date::ToDateString, FunctionLength::ZERO);
948     SetFunction(env, dateFuncPrototype, "toISOString", Date::ToISOString, FunctionLength::ZERO);
949     SetFunction(env, dateFuncPrototype, "toJSON", Date::ToJSON, FunctionLength::ONE);
950     SetFunction(env, dateFuncPrototype, "toLocaleDateString", Date::ToLocaleDateString, FunctionLength::ZERO);
951     SetFunction(env, dateFuncPrototype, "toLocaleString", Date::ToLocaleString, FunctionLength::ZERO);
952     SetFunction(env, dateFuncPrototype, "toLocaleTimeString", Date::ToLocaleTimeString, FunctionLength::ZERO);
953     SetFunction(env, dateFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(), Date::ToString,
954                 FunctionLength::ZERO);
955     SetFunction(env, dateFuncPrototype, "toTimeString", Date::ToTimeString, FunctionLength::ZERO);
956     SetFunction(env, dateFuncPrototype, "toUTCString", Date::ToUTCString, FunctionLength::ZERO);
957     SetFunction(env, dateFuncPrototype, thread_->GlobalConstants()->GetHandledValueOfString(), Date::ValueOf,
958                 FunctionLength::ZERO);
959 
960     SetFunctionAtSymbol(env, dateFuncPrototype, env->GetToPrimitiveSymbol(), "[Symbol.toPrimitive]", Date::ToPrimitive,
961                         FunctionLength::ONE);
962 
963     // Date method
964     SetFunction(env, dateFunction, "now", Date::Now, FunctionLength::ZERO);
965     SetFunction(env, dateFunction, "parse", Date::Parse, FunctionLength::ONE);
966     SetFunction(env, dateFunction, "UTC", Date::UTC, utcLength);
967 
968     // Date.length
969     SetConstant(dateFunction, "length", JSTaggedValue(utcLength));
970 
971     env->SetDateFunction(thread_, dateFunction);
972 }
973 
LazyInitializeDate(const JSHandle<GlobalEnv> & env) const974 void Builtins::LazyInitializeDate(const JSHandle<GlobalEnv> &env) const
975 {
976     [[maybe_unused]] EcmaHandleScope scope(thread_);
977     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
978     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("Date"));
979     auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::Date));
980     SetLazyAccessor(globalObject, key, accessor);
981     env->SetDateFunction(thread_, accessor);
982 }
983 
InitializeBoolean(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & primRefObjHClass) const984 void Builtins::InitializeBoolean(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &primRefObjHClass) const
985 {
986     [[maybe_unused]] EcmaHandleScope scope(thread_);
987     // Boolean.prototype
988     JSHandle<JSTaggedValue> toObject(thread_, JSTaggedValue::False());
989     JSHandle<JSObject> booleanFuncPrototype =
990         JSHandle<JSObject>::Cast(factory_->NewJSPrimitiveRef(primRefObjHClass, toObject));
991     JSHandle<JSTaggedValue> booleanFuncPrototypeValue(booleanFuncPrototype);
992 
993     // Boolean.prototype_or_hclass
994     JSHandle<JSHClass> booleanFuncInstanceHClass =
995         factory_->NewEcmaHClass(JSPrimitiveRef::SIZE, JSType::JS_PRIMITIVE_REF, booleanFuncPrototypeValue);
996 
997     // new Boolean Function()
998     JSHandle<JSFunction> booleanFunction = NewBuiltinConstructor(env, booleanFuncPrototype, Boolean::BooleanConstructor,
999         "Boolean", FunctionLength::ONE, BUILTINS_STUB_ID(BooleanConstructor));
1000     booleanFunction->SetFunctionPrototype(thread_, booleanFuncInstanceHClass.GetTaggedValue());
1001 
1002     // Boolean.prototype method
1003     SetFunction(env, booleanFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(),
1004                 Boolean::BooleanPrototypeToString, FunctionLength::ZERO);
1005     SetFunction(env, booleanFuncPrototype, thread_->GlobalConstants()->GetHandledValueOfString(),
1006                 Boolean::BooleanPrototypeValueOf, FunctionLength::ZERO);
1007 
1008     env->SetBooleanFunction(thread_, booleanFunction);
1009 }
1010 
InitializeProxy(const JSHandle<GlobalEnv> & env)1011 void Builtins::InitializeProxy(const JSHandle<GlobalEnv> &env)
1012 {
1013     JSHandle<JSObject> proxyFunction(InitializeExoticConstructor(env, Proxy::ProxyConstructor, "Proxy", 2));
1014 
1015     // Proxy method
1016     SetFunction(env, proxyFunction, "revocable", Proxy::Revocable, FunctionLength::TWO);
1017     env->SetProxyFunction(thread_, proxyFunction);
1018 }
1019 
InitializeExoticConstructor(const JSHandle<GlobalEnv> & env,EcmaEntrypoint ctorFunc,const char * name,int length)1020 JSHandle<JSFunction> Builtins::InitializeExoticConstructor(const JSHandle<GlobalEnv> &env, EcmaEntrypoint ctorFunc,
1021                                                            const char *name, int length)
1022 {
1023     JSHandle<JSFunction> ctor =
1024         factory_->NewJSFunction(env, reinterpret_cast<void *>(ctorFunc), FunctionKind::BUILTIN_PROXY_CONSTRUCTOR);
1025 
1026     JSFunction::SetFunctionLength(thread_, ctor, JSTaggedValue(length));
1027     JSHandle<JSTaggedValue> nameString(factory_->NewFromUtf8(name));
1028     JSFunction::SetFunctionName(thread_, JSHandle<JSFunctionBase>(ctor), nameString,
1029                                 JSHandle<JSTaggedValue>(thread_, JSTaggedValue::Undefined()));
1030 
1031     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1032     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>(ctor), true, false, true);
1033     JSObject::DefineOwnProperty(thread_, globalObject, nameString, descriptor);
1034     return ctor;
1035 }
1036 
InitializeAsyncFunction(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1037 void Builtins::InitializeAsyncFunction(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
1038 {
1039     [[maybe_unused]] EcmaHandleScope scope(thread_);
1040     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1041     // AsyncFunction.prototype
1042     JSHandle<JSObject> asyncFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
1043     JSObject::SetPrototype(thread_, asyncFuncPrototype, env->GetFunctionPrototype());
1044     JSHandle<JSTaggedValue> asyncFuncPrototypeValue(asyncFuncPrototype);
1045 
1046     // AsyncFunction.prototype_or_hclass
1047     JSHandle<JSHClass> asyncFuncInstanceHClass =
1048         factory_->NewEcmaHClass(JSAsyncFunction::SIZE, JSType::JS_ASYNC_FUNCTION, asyncFuncPrototypeValue);
1049 
1050     // AsyncFunction = new Function()
1051     JSHandle<JSFunction> asyncFunction = NewBuiltinConstructor(
1052         env, asyncFuncPrototype, AsyncFunction::AsyncFunctionConstructor, "AsyncFunction", FunctionLength::ONE);
1053     JSObject::SetPrototype(thread_, JSHandle<JSObject>::Cast(asyncFunction), env->GetFunctionFunction());
1054     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
1055     PropertyDescriptor asyncDesc(thread_, JSHandle<JSTaggedValue>::Cast(asyncFunction), false, false, true);
1056     JSObject::DefineOwnProperty(thread_, asyncFuncPrototype, constructorKey, asyncDesc);
1057     asyncFunction->SetProtoOrHClass(thread_, asyncFuncInstanceHClass.GetTaggedValue());
1058 
1059     // AsyncFunction.prototype property
1060     SetStringTagSymbol(env, asyncFuncPrototype, "AsyncFunction");
1061     env->SetAsyncFunction(thread_, asyncFunction);
1062     env->SetAsyncFunctionPrototype(thread_, asyncFuncPrototype);
1063 }
1064 
InitializeAllTypeError(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1065 void Builtins::InitializeAllTypeError(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
1066 {
1067     // Error.prototype
1068     JSHandle<JSObject> errorFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
1069     JSHandle<JSTaggedValue> errorFuncPrototypeValue(errorFuncPrototype);
1070     // Error.prototype_or_hclass
1071     JSHandle<JSHClass> errorFuncInstanceHClass =
1072         factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_ERROR, errorFuncPrototypeValue);
1073     // Error() = new Function()
1074     JSHandle<JSFunction> errorFunction(
1075         NewBuiltinConstructor(env, errorFuncPrototype, Error::ErrorConstructor, "Error", FunctionLength::ONE));
1076     errorFunction->SetFunctionPrototype(thread_, errorFuncInstanceHClass.GetTaggedValue());
1077 
1078     // Error.prototype method
1079     SetFunction(env, errorFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(), Error::ToString,
1080                 FunctionLength::ZERO);
1081 
1082     // Error.prototype Attribute
1083     SetAttribute(errorFuncPrototype, "name", "Error");
1084     SetAttribute(errorFuncPrototype, "message", "");
1085     env->SetErrorFunction(thread_, errorFunction);
1086 
1087     JSHandle<JSHClass> nativeErrorFuncClass =
1088         factory_->NewEcmaHClass(JSFunction::SIZE, JSType::JS_FUNCTION, env->GetErrorFunction());
1089     nativeErrorFuncClass->SetConstructor(true);
1090     env->SetNativeErrorFunctionClass(thread_, nativeErrorFuncClass);
1091 
1092     JSHandle<JSHClass> errorNativeFuncInstanceHClass =
1093         factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, errorFuncPrototypeValue);
1094     InitializeError(env, errorNativeFuncInstanceHClass, JSType::JS_RANGE_ERROR);
1095     InitializeError(env, errorNativeFuncInstanceHClass, JSType::JS_REFERENCE_ERROR);
1096     InitializeError(env, errorNativeFuncInstanceHClass, JSType::JS_TYPE_ERROR);
1097     InitializeError(env, errorNativeFuncInstanceHClass, JSType::JS_AGGREGATE_ERROR);
1098     InitializeError(env, errorNativeFuncInstanceHClass, JSType::JS_URI_ERROR);
1099     InitializeError(env, errorNativeFuncInstanceHClass, JSType::JS_SYNTAX_ERROR);
1100     InitializeError(env, errorNativeFuncInstanceHClass, JSType::JS_EVAL_ERROR);
1101     InitializeError(env, errorNativeFuncInstanceHClass, JSType::JS_OOM_ERROR);
1102 }
1103 
InitializeAllTypeErrorWithRealm(const JSHandle<GlobalEnv> & realm) const1104 void Builtins::InitializeAllTypeErrorWithRealm(const JSHandle<GlobalEnv> &realm) const
1105 {
1106     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
1107 
1108     realm->SetErrorFunction(thread_, env->GetErrorFunction());
1109     realm->SetNativeErrorFunctionClass(thread_, env->GetNativeErrorFunctionClass());
1110 
1111     SetErrorWithRealm(realm, JSType::JS_RANGE_ERROR);
1112     SetErrorWithRealm(realm, JSType::JS_REFERENCE_ERROR);
1113     SetErrorWithRealm(realm, JSType::JS_TYPE_ERROR);
1114     SetErrorWithRealm(realm, JSType::JS_AGGREGATE_ERROR);
1115     SetErrorWithRealm(realm, JSType::JS_URI_ERROR);
1116     SetErrorWithRealm(realm, JSType::JS_SYNTAX_ERROR);
1117     SetErrorWithRealm(realm, JSType::JS_EVAL_ERROR);
1118     SetErrorWithRealm(realm, JSType::JS_OOM_ERROR);
1119 }
1120 
SetErrorWithRealm(const JSHandle<GlobalEnv> & realm,const JSType & errorTag) const1121 void Builtins::SetErrorWithRealm(const JSHandle<GlobalEnv> &realm, const JSType &errorTag) const
1122 {
1123     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
1124     JSHandle<JSObject> globalObject(thread_, realm->GetGlobalObject());
1125     JSHandle<JSTaggedValue> nameString;
1126     JSHandle<JSTaggedValue> nativeErrorFunction;
1127     switch (errorTag) {
1128         case JSType::JS_RANGE_ERROR:
1129             nativeErrorFunction = env->GetRangeErrorFunction();
1130             nameString = JSHandle<JSTaggedValue>(thread_->GlobalConstants()->GetHandledRangeErrorString());
1131             realm->SetRangeErrorFunction(thread_, nativeErrorFunction);
1132             break;
1133         case JSType::JS_EVAL_ERROR:
1134             nativeErrorFunction = env->GetEvalErrorFunction();
1135             nameString = JSHandle<JSTaggedValue>(thread_->GlobalConstants()->GetHandledEvalErrorString());
1136             realm->SetEvalErrorFunction(thread_, nativeErrorFunction);
1137             break;
1138         case JSType::JS_REFERENCE_ERROR:
1139             nativeErrorFunction = env->GetReferenceErrorFunction();
1140             nameString = JSHandle<JSTaggedValue>(thread_->GlobalConstants()->GetHandledReferenceErrorString());
1141             realm->SetReferenceErrorFunction(thread_, nativeErrorFunction);
1142             break;
1143         case JSType::JS_TYPE_ERROR:
1144             nativeErrorFunction = env->GetTypeErrorFunction();
1145             nameString = JSHandle<JSTaggedValue>(thread_->GlobalConstants()->GetHandledTypeErrorString());
1146             realm->SetTypeErrorFunction(thread_, nativeErrorFunction);
1147             realm->SetThrowTypeError(thread_, env->GetThrowTypeError());
1148             break;
1149         case JSType::JS_AGGREGATE_ERROR:
1150             nativeErrorFunction = env->GetAggregateErrorFunction();
1151             nameString = JSHandle<JSTaggedValue>(thread_->GlobalConstants()->GetHandledAggregateErrorString());
1152             realm->SetAggregateErrorFunction(thread_, nativeErrorFunction);
1153             break;
1154         case JSType::JS_URI_ERROR:
1155             nativeErrorFunction = env->GetURIErrorFunction();
1156             nameString = JSHandle<JSTaggedValue>(thread_->GlobalConstants()->GetHandledURIErrorString());
1157             realm->SetURIErrorFunction(thread_, nativeErrorFunction);
1158             break;
1159         case JSType::JS_SYNTAX_ERROR:
1160             nativeErrorFunction = env->GetSyntaxErrorFunction();
1161             nameString = JSHandle<JSTaggedValue>(thread_->GlobalConstants()->GetHandledSyntaxErrorString());
1162             realm->SetSyntaxErrorFunction(thread_, nativeErrorFunction);
1163             break;
1164         case JSType::JS_OOM_ERROR:
1165             nativeErrorFunction = env->GetOOMErrorFunction();
1166             nameString = JSHandle<JSTaggedValue>(thread_->GlobalConstants()->GetHandledOOMErrorString());
1167             realm->SetOOMErrorFunction(thread_, nativeErrorFunction);
1168             break;
1169         default:
1170             break;
1171     }
1172     PropertyDescriptor descriptor(thread_, nativeErrorFunction, true, false, true);
1173     JSObject::DefineOwnProperty(thread_, globalObject, nameString, descriptor);
1174 }
1175 
GeneralUpdateError(ErrorParameter * error,EcmaEntrypoint constructor,EcmaEntrypoint method,const char * name,JSType type) const1176 void Builtins::GeneralUpdateError(ErrorParameter *error, EcmaEntrypoint constructor, EcmaEntrypoint method,
1177                                   const char *name, JSType type) const
1178 {
1179     error->nativeConstructor = constructor;
1180     error->nativeMethod = method;
1181     error->nativePropertyName = name;
1182     error->nativeJstype = type;
1183 }
1184 
InitializeError(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass,const JSType & errorTag) const1185 void Builtins::InitializeError(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass,
1186                                const JSType &errorTag) const
1187 {
1188     // NativeError.prototype
1189     JSHandle<JSObject> nativeErrorFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
1190     JSHandle<JSTaggedValue> nativeErrorFuncPrototypeValue(nativeErrorFuncPrototype);
1191 
1192     ErrorParameter errorParameter{RangeError::RangeErrorConstructor, RangeError::ToString, "RangeError",
1193                                   JSType::JS_RANGE_ERROR};
1194     switch (errorTag) {
1195         case JSType::JS_RANGE_ERROR:
1196             GeneralUpdateError(&errorParameter, RangeError::RangeErrorConstructor, RangeError::ToString, "RangeError",
1197                                JSType::JS_RANGE_ERROR);
1198             break;
1199         case JSType::JS_EVAL_ERROR:
1200             GeneralUpdateError(&errorParameter, EvalError::EvalErrorConstructor, EvalError::ToString, "EvalError",
1201                                JSType::JS_EVAL_ERROR);
1202             break;
1203         case JSType::JS_REFERENCE_ERROR:
1204             GeneralUpdateError(&errorParameter, ReferenceError::ReferenceErrorConstructor, ReferenceError::ToString,
1205                                "ReferenceError", JSType::JS_REFERENCE_ERROR);
1206             break;
1207         case JSType::JS_TYPE_ERROR:
1208             GeneralUpdateError(&errorParameter, TypeError::TypeErrorConstructor, TypeError::ToString, "TypeError",
1209                                JSType::JS_TYPE_ERROR);
1210             break;
1211         case JSType::JS_AGGREGATE_ERROR:
1212             GeneralUpdateError(&errorParameter, AggregateError::AggregateErrorConstructor, AggregateError::ToString,
1213                                "AggregateError", JSType::JS_AGGREGATE_ERROR);
1214             break;
1215         case JSType::JS_URI_ERROR:
1216             GeneralUpdateError(&errorParameter, URIError::URIErrorConstructor, URIError::ToString, "URIError",
1217                                JSType::JS_URI_ERROR);
1218             break;
1219         case JSType::JS_SYNTAX_ERROR:
1220             GeneralUpdateError(&errorParameter, SyntaxError::SyntaxErrorConstructor, SyntaxError::ToString,
1221                                "SyntaxError", JSType::JS_SYNTAX_ERROR);
1222             break;
1223         case JSType::JS_OOM_ERROR:
1224             GeneralUpdateError(&errorParameter, OOMError::OOMErrorConstructor, OOMError::ToString,
1225                                "OutOfMemoryError", JSType::JS_OOM_ERROR);
1226             break;
1227         default:
1228             break;
1229     }
1230 
1231     // NativeError.prototype_or_hclass
1232     JSHandle<JSHClass> nativeErrorFuncInstanceHClass =
1233         factory_->NewEcmaHClass(JSObject::SIZE, errorParameter.nativeJstype, nativeErrorFuncPrototypeValue);
1234 
1235     // NativeError() = new Error()
1236     FunctionLength functionLength = FunctionLength::ONE;
1237     if (errorTag == JSType::JS_AGGREGATE_ERROR) {
1238         functionLength = FunctionLength::TWO;
1239     }
1240     JSHandle<JSFunction> nativeErrorFunction =
1241         factory_->NewJSNativeErrorFunction(env, reinterpret_cast<void *>(errorParameter.nativeConstructor));
1242     InitializeCtor(env, nativeErrorFuncPrototype, nativeErrorFunction, errorParameter.nativePropertyName,
1243                    functionLength);
1244 
1245     nativeErrorFunction->SetFunctionPrototype(thread_, nativeErrorFuncInstanceHClass.GetTaggedValue());
1246 
1247     // NativeError.prototype method
1248     SetFunction(env, nativeErrorFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(),
1249                 errorParameter.nativeMethod, FunctionLength::ZERO);
1250 
1251     // Error.prototype Attribute
1252     SetAttribute(nativeErrorFuncPrototype, "name", errorParameter.nativePropertyName);
1253     SetAttribute(nativeErrorFuncPrototype, "message", "");
1254 
1255     if (errorTag == JSType::JS_RANGE_ERROR) {
1256         env->SetRangeErrorFunction(thread_, nativeErrorFunction);
1257     } else if (errorTag == JSType::JS_REFERENCE_ERROR) {
1258         env->SetReferenceErrorFunction(thread_, nativeErrorFunction);
1259     } else if (errorTag == JSType::JS_TYPE_ERROR) {
1260         env->SetTypeErrorFunction(thread_, nativeErrorFunction);
1261         JSHandle<JSFunction> throwTypeErrorFunction =
1262             factory_->NewJSFunction(env, reinterpret_cast<void *>(TypeError::ThrowTypeError));
1263         JSFunction::SetFunctionLength(thread_, throwTypeErrorFunction, JSTaggedValue(1), false);
1264         JSObject::PreventExtensions(thread_, JSHandle<JSObject>::Cast(throwTypeErrorFunction));
1265         env->SetThrowTypeError(thread_, throwTypeErrorFunction);
1266     } else if (errorTag == JSType::JS_AGGREGATE_ERROR) {
1267         env->SetAggregateErrorFunction(thread_, nativeErrorFunction);
1268     } else if (errorTag == JSType::JS_URI_ERROR) {
1269         env->SetURIErrorFunction(thread_, nativeErrorFunction);
1270     } else if (errorTag == JSType::JS_SYNTAX_ERROR) {
1271         env->SetSyntaxErrorFunction(thread_, nativeErrorFunction);
1272     } else if (errorTag == JSType::JS_EVAL_ERROR) {
1273         env->SetEvalErrorFunction(thread_, nativeErrorFunction);
1274     } else {
1275         env->SetOOMErrorFunction(thread_, nativeErrorFunction);
1276     }
1277 }  // namespace panda::ecmascript
1278 
InitializeCtor(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & prototype,const JSHandle<JSFunction> & ctor,const char * name,int length) const1279 void Builtins::InitializeCtor(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &prototype,
1280                               const JSHandle<JSFunction> &ctor, const char *name, int length) const
1281 {
1282     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1283     JSFunction::SetFunctionLength(thread_, ctor, JSTaggedValue(length));
1284     JSHandle<JSTaggedValue> nameString(factory_->NewFromUtf8(name));
1285     JSFunction::SetFunctionName(thread_, JSHandle<JSFunctionBase>(ctor), nameString,
1286                                 JSHandle<JSTaggedValue>(thread_, JSTaggedValue::Undefined()));
1287     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
1288     PropertyDescriptor descriptor1(thread_, JSHandle<JSTaggedValue>::Cast(ctor), true, false, true);
1289     JSObject::DefineOwnProperty(thread_, prototype, constructorKey, descriptor1);
1290 
1291     /* set "prototype" in constructor */
1292     ctor->SetFunctionPrototype(thread_, prototype.GetTaggedValue());
1293 
1294     if (!JSTaggedValue::SameValue(nameString, thread_->GlobalConstants()->GetHandledAsyncFunctionString())) {
1295         JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1296         PropertyDescriptor descriptor2(thread_, JSHandle<JSTaggedValue>::Cast(ctor), true, false, true);
1297         JSObject::DefineOwnProperty(thread_, globalObject, nameString, descriptor2);
1298     }
1299 }
1300 
InitializeSet(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1301 void Builtins::InitializeSet(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
1302 {
1303     [[maybe_unused]] EcmaHandleScope scope(thread_);
1304     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1305     // Set.prototype
1306     JSHandle<JSObject> setFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
1307     JSHandle<JSTaggedValue> setFuncPrototypeValue(setFuncPrototype);
1308     // Set.prototype_or_hclass
1309     JSHandle<JSHClass> setFuncInstanceHClass =
1310         factory_->NewEcmaHClass(JSSet::SIZE, JSType::JS_SET, setFuncPrototypeValue);
1311     // Set() = new Function()
1312     JSHandle<JSTaggedValue> setFunction(
1313         NewBuiltinConstructor(env, setFuncPrototype, BuiltinsSet::SetConstructor, "Set", FunctionLength::ZERO));
1314     JSHandle<JSFunction>(setFunction)->SetFunctionPrototype(thread_, setFuncInstanceHClass.GetTaggedValue());
1315 
1316     // "constructor" property on the prototype
1317     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
1318     JSObject::SetProperty(thread_, JSHandle<JSTaggedValue>(setFuncPrototype), constructorKey, setFunction);
1319     RETURN_IF_ABRUPT_COMPLETION(thread_);
1320     // set.prototype.add()
1321     SetFunction(env, setFuncPrototype, "add", BuiltinsSet::Add, FunctionLength::ONE);
1322     // set.prototype.clear()
1323     SetFunction(env, setFuncPrototype, "clear", BuiltinsSet::Clear, FunctionLength::ZERO);
1324     // set.prototype.delete()
1325     SetFunction(env, setFuncPrototype, "delete", BuiltinsSet::Delete, FunctionLength::ONE);
1326     // set.prototype.has()
1327     SetFunction(env, setFuncPrototype, "has", BuiltinsSet::Has, FunctionLength::ONE);
1328     // set.prototype.forEach()
1329     SetFunction(env, setFuncPrototype, "forEach", BuiltinsSet::ForEach, FunctionLength::ONE);
1330     // set.prototype.entries()
1331     SetFunction(env, setFuncPrototype, "entries", BuiltinsSet::Entries, FunctionLength::ZERO);
1332     // set.prototype.keys()
1333     SetFunction(env, setFuncPrototype, "values", BuiltinsSet::Values, FunctionLength::ZERO);
1334     // set.prototype.values()
1335     JSHandle<JSTaggedValue> keys(factory_->NewFromASCII("keys"));
1336     JSHandle<JSTaggedValue> values(factory_->NewFromASCII("values"));
1337     JSHandle<JSTaggedValue> valuesFunc =
1338         JSObject::GetMethod(thread_, JSHandle<JSTaggedValue>::Cast(setFuncPrototype), values);
1339     RETURN_IF_ABRUPT_COMPLETION(thread_);
1340     PropertyDescriptor descriptor(thread_, valuesFunc, true, false, true);
1341     JSObject::DefineOwnProperty(thread_, setFuncPrototype, keys, descriptor);
1342 
1343     // @@ToStringTag
1344     SetStringTagSymbol(env, setFuncPrototype, "Set");
1345 
1346     // 23.1.3.10get Set.prototype.size
1347     JSHandle<JSTaggedValue> sizeGetter = CreateGetter(env, BuiltinsSet::GetSize, "size", FunctionLength::ZERO);
1348     JSHandle<JSTaggedValue> sizeKey(factory_->NewFromASCII("size"));
1349     SetGetter(setFuncPrototype, sizeKey, sizeGetter);
1350 
1351     // 23.1.2.2get Set [ @@species ]
1352     JSHandle<JSTaggedValue> speciesSymbol = env->GetSpeciesSymbol();
1353     JSHandle<JSTaggedValue> speciesGetter =
1354         CreateGetter(env, BuiltinsSet::Species, "[Symbol.species]", FunctionLength::ZERO);
1355     SetGetter(JSHandle<JSObject>(setFunction), speciesSymbol, speciesGetter);
1356 
1357     // %SetPrototype% [ @@iterator ]
1358     JSHandle<JSTaggedValue> iteratorSymbol = env->GetIteratorSymbol();
1359     JSObject::DefineOwnProperty(thread_, setFuncPrototype, iteratorSymbol, descriptor);
1360 
1361     env->SetBuiltinsSetFunction(thread_, setFunction);
1362 }
1363 
LazyInitializeSet(const JSHandle<GlobalEnv> & env)1364 void Builtins::LazyInitializeSet(const JSHandle<GlobalEnv> &env)
1365 {
1366     [[maybe_unused]] EcmaHandleScope scope(thread_);
1367     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1368     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("Set"));
1369     auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::Set));
1370     SetLazyAccessor(globalObject, key, accessor);
1371     env->SetBuiltinsSetFunction(thread_, accessor);
1372 }
1373 
InitializeMap(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1374 void Builtins::InitializeMap(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
1375 {
1376     [[maybe_unused]] EcmaHandleScope scope(thread_);
1377     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1378     // Map.prototype
1379     JSHandle<JSObject> mapFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
1380     JSHandle<JSTaggedValue> mapFuncPrototypeValue(mapFuncPrototype);
1381     // Map.prototype_or_hclass
1382     JSHandle<JSHClass> mapFuncInstanceHClass =
1383         factory_->NewEcmaHClass(JSMap::SIZE, JSType::JS_MAP, mapFuncPrototypeValue);
1384     // Map() = new Function()
1385     JSHandle<JSTaggedValue> mapFunction(
1386         NewBuiltinConstructor(env, mapFuncPrototype, BuiltinsMap::MapConstructor, "Map", FunctionLength::ZERO));
1387     // Map().prototype = Map.Prototype & Map.prototype.constructor = Map()
1388     JSFunction::Cast(mapFunction->GetTaggedObject())
1389         ->SetFunctionPrototype(thread_, mapFuncInstanceHClass.GetTaggedValue());
1390 
1391     // "constructor" property on the prototype
1392     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
1393     JSObject::SetProperty(thread_, JSHandle<JSTaggedValue>(mapFuncPrototype), constructorKey, mapFunction);
1394     RETURN_IF_ABRUPT_COMPLETION(thread_);
1395     // map.prototype.set()
1396     SetFunction(env, mapFuncPrototype, globalConst->GetHandledSetString(), BuiltinsMap::Set, FunctionLength::TWO);
1397     // map.prototype.clear()
1398     SetFunction(env, mapFuncPrototype, "clear", BuiltinsMap::Clear, FunctionLength::ZERO);
1399     // map.prototype.delete()
1400     SetFunction(env, mapFuncPrototype, "delete", BuiltinsMap::Delete, FunctionLength::ONE);
1401     // map.prototype.has()
1402     SetFunction(env, mapFuncPrototype, "has", BuiltinsMap::Has, FunctionLength::ONE);
1403     // map.prototype.get()
1404     SetFunction(env, mapFuncPrototype, thread_->GlobalConstants()->GetHandledGetString(), BuiltinsMap::Get,
1405                 FunctionLength::ONE);
1406     // map.prototype.forEach()
1407     SetFunction(env, mapFuncPrototype, "forEach", BuiltinsMap::ForEach, FunctionLength::ONE);
1408     // map.prototype.keys()
1409     SetFunction(env, mapFuncPrototype, "keys", BuiltinsMap::Keys, FunctionLength::ZERO);
1410     // map.prototype.values()
1411     SetFunction(env, mapFuncPrototype, "values", BuiltinsMap::Values, FunctionLength::ZERO);
1412     // map.prototype.entries()
1413     SetFunction(env, mapFuncPrototype, "entries", BuiltinsMap::Entries, FunctionLength::ZERO);
1414     // @@ToStringTag
1415     SetStringTagSymbol(env, mapFuncPrototype, "Map");
1416 
1417     // 23.1.3.10get Map.prototype.size
1418     JSHandle<JSTaggedValue> sizeGetter = CreateGetter(env, BuiltinsMap::GetSize, "size", FunctionLength::ZERO);
1419     JSHandle<JSTaggedValue> sizeKey(factory_->NewFromASCII("size"));
1420     SetGetter(mapFuncPrototype, sizeKey, sizeGetter);
1421 
1422     // 23.1.2.2get Map [ @@species ]
1423     JSHandle<JSTaggedValue> speciesSymbol = env->GetSpeciesSymbol();
1424     JSHandle<JSTaggedValue> speciesGetter =
1425         CreateGetter(env, BuiltinsMap::Species, "[Symbol.species]", FunctionLength::ZERO);
1426     SetGetter(JSHandle<JSObject>(mapFunction), speciesSymbol, speciesGetter);
1427 
1428     // %MapPrototype% [ @@iterator ]
1429     JSHandle<JSTaggedValue> iteratorSymbol = env->GetIteratorSymbol();
1430     JSHandle<JSTaggedValue> entries(factory_->NewFromASCII("entries"));
1431     JSHandle<JSTaggedValue> entriesFunc =
1432         JSObject::GetMethod(thread_, JSHandle<JSTaggedValue>::Cast(mapFuncPrototype), entries);
1433     RETURN_IF_ABRUPT_COMPLETION(thread_);
1434     PropertyDescriptor descriptor(thread_, entriesFunc, true, false, true);
1435     JSObject::DefineOwnProperty(thread_, mapFuncPrototype, iteratorSymbol, descriptor);
1436 
1437     env->SetBuiltinsMapFunction(thread_, mapFunction);
1438     env->SetMapPrototype(thread_, mapFuncPrototype);
1439 }
1440 
LazyInitializeMap(const JSHandle<GlobalEnv> & env) const1441 void Builtins::LazyInitializeMap(const JSHandle<GlobalEnv> &env) const
1442 {
1443     [[maybe_unused]] EcmaHandleScope scope(thread_);
1444     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1445     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("Map"));
1446     auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::Map));
1447     SetLazyAccessor(globalObject, key, accessor);
1448     env->SetBuiltinsMapFunction(thread_, accessor);
1449     env->SetMapPrototype(thread_, accessor);
1450 }
1451 
InitializeWeakMap(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1452 void Builtins::InitializeWeakMap(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
1453 {
1454     [[maybe_unused]] EcmaHandleScope scope(thread_);
1455     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1456     // WeakMap.prototype
1457     JSHandle<JSObject> weakMapFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
1458     JSHandle<JSTaggedValue> weakMapFuncPrototypeValue(weakMapFuncPrototype);
1459     // WeakMap.prototype_or_hclass
1460     JSHandle<JSHClass> weakMapFuncInstanceHClass =
1461         factory_->NewEcmaHClass(JSWeakMap::SIZE, JSType::JS_WEAK_MAP, weakMapFuncPrototypeValue);
1462     // WeakMap() = new Function()
1463     JSHandle<JSTaggedValue> weakMapFunction(NewBuiltinConstructor(
1464         env, weakMapFuncPrototype, BuiltinsWeakMap::WeakMapConstructor, "WeakMap", FunctionLength::ZERO));
1465     // WeakMap().prototype = WeakMap.Prototype & WeakMap.prototype.constructor = WeakMap()
1466     JSFunction::Cast(weakMapFunction->GetTaggedObject())
1467         ->SetProtoOrHClass(thread_, weakMapFuncInstanceHClass.GetTaggedValue());
1468 
1469     // "constructor" property on the prototype
1470     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
1471     JSObject::SetProperty(thread_, JSHandle<JSTaggedValue>(weakMapFuncPrototype), constructorKey, weakMapFunction);
1472     RETURN_IF_ABRUPT_COMPLETION(thread_);
1473     // weakmap.prototype.set()
1474     SetFunction(env, weakMapFuncPrototype, globalConst->GetHandledSetString(), BuiltinsWeakMap::Set,
1475                 FunctionLength::TWO);
1476     // weakmap.prototype.delete()
1477     SetFunction(env, weakMapFuncPrototype, "delete", BuiltinsWeakMap::Delete, FunctionLength::ONE);
1478     // weakmap.prototype.has()
1479     SetFunction(env, weakMapFuncPrototype, "has", BuiltinsWeakMap::Has, FunctionLength::ONE);
1480     // weakmap.prototype.get()
1481     SetFunction(env, weakMapFuncPrototype, thread_->GlobalConstants()->GetHandledGetString(), BuiltinsWeakMap::Get,
1482                 FunctionLength::ONE);
1483     // @@ToStringTag
1484     SetStringTagSymbol(env, weakMapFuncPrototype, "WeakMap");
1485 
1486     env->SetBuiltinsWeakMapFunction(thread_, weakMapFunction);
1487 }
1488 
LazyInitializeWeakMap(const JSHandle<GlobalEnv> & env) const1489 void Builtins::LazyInitializeWeakMap(const JSHandle<GlobalEnv> &env) const
1490 {
1491     [[maybe_unused]] EcmaHandleScope scope(thread_);
1492     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1493     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("WeakMap"));
1494     auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::WeakMap));
1495     SetLazyAccessor(globalObject, key, accessor);
1496     env->SetBuiltinsWeakMapFunction(thread_, accessor);
1497 }
1498 
InitializeWeakSet(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1499 void Builtins::InitializeWeakSet(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
1500 {
1501     [[maybe_unused]] EcmaHandleScope scope(thread_);
1502     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1503     // Set.prototype
1504     JSHandle<JSObject> weakSetFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
1505     JSHandle<JSTaggedValue> weakSetFuncPrototypeValue(weakSetFuncPrototype);
1506     // Set.prototype_or_hclass
1507     JSHandle<JSHClass> weakSetFuncInstanceHClass =
1508         factory_->NewEcmaHClass(JSWeakSet::SIZE, JSType::JS_WEAK_SET, weakSetFuncPrototypeValue);
1509     // Set() = new Function()
1510     JSHandle<JSTaggedValue> weakSetFunction(NewBuiltinConstructor(
1511         env, weakSetFuncPrototype, BuiltinsWeakSet::WeakSetConstructor, "WeakSet", FunctionLength::ZERO));
1512     JSHandle<JSFunction>(weakSetFunction)->SetProtoOrHClass(thread_, weakSetFuncInstanceHClass.GetTaggedValue());
1513 
1514     // "constructor" property on the prototype
1515     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
1516     JSObject::SetProperty(thread_, JSHandle<JSTaggedValue>(weakSetFuncPrototype), constructorKey, weakSetFunction);
1517     RETURN_IF_ABRUPT_COMPLETION(thread_);
1518     // set.prototype.add()
1519     SetFunction(env, weakSetFuncPrototype, "add", BuiltinsWeakSet::Add, FunctionLength::ONE);
1520     // set.prototype.delete()
1521     SetFunction(env, weakSetFuncPrototype, "delete", BuiltinsWeakSet::Delete, FunctionLength::ONE);
1522     // set.prototype.has()
1523     SetFunction(env, weakSetFuncPrototype, "has", BuiltinsWeakSet::Has, FunctionLength::ONE);
1524 
1525     // @@ToStringTag
1526     SetStringTagSymbol(env, weakSetFuncPrototype, "WeakSet");
1527 
1528     env->SetBuiltinsWeakSetFunction(thread_, weakSetFunction);
1529 }
1530 
LazyInitializeWeakSet(const JSHandle<GlobalEnv> & env) const1531 void Builtins::LazyInitializeWeakSet(const JSHandle<GlobalEnv> &env) const
1532 {
1533     [[maybe_unused]] EcmaHandleScope scope(thread_);
1534     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1535     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("WeakSet"));
1536     auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::WeakSet));
1537     SetLazyAccessor(globalObject, key, accessor);
1538     env->SetBuiltinsWeakSetFunction(thread_, accessor);
1539 }
1540 
InitializeAtomics(const JSHandle<GlobalEnv> & env,const JSHandle<JSTaggedValue> & objFuncPrototypeVal) const1541 void Builtins::InitializeAtomics(const JSHandle<GlobalEnv> &env,
1542                                  const JSHandle<JSTaggedValue> &objFuncPrototypeVal) const
1543 {
1544     [[maybe_unused]] EcmaHandleScope scope(thread_);
1545     JSHandle<JSHClass> atomicsHClass = factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT,
1546                                                                    objFuncPrototypeVal);
1547     JSHandle<JSObject> atomicsObject = factory_->NewJSObject(atomicsHClass);
1548     SetFunction(env, atomicsObject, "add", Atomics::Add, FunctionLength::THREE);
1549     SetFunction(env, atomicsObject, "and", Atomics::And, FunctionLength::THREE);
1550     SetFunction(env, atomicsObject, "sub", Atomics::Sub, FunctionLength::THREE);
1551     SetFunction(env, atomicsObject, "or", Atomics::Or, FunctionLength::THREE);
1552     SetFunction(env, atomicsObject, "xor", Atomics::Xor, FunctionLength::THREE);
1553     SetFunction(env, atomicsObject, "compareExchange", Atomics::CompareExchange, FunctionLength::FOUR);
1554     SetFunction(env, atomicsObject, "exchange", Atomics::Exchange, FunctionLength::THREE);
1555     SetFunction(env, atomicsObject, "isLockFree", Atomics::IsLockFree, FunctionLength::ONE);
1556     SetFunction(env, atomicsObject, "load", Atomics::Load, FunctionLength::TWO);
1557     SetFunction(env, atomicsObject, "store", Atomics::Store, FunctionLength::THREE);
1558     SetFunction(env, atomicsObject, "wait", Atomics::Wait, FunctionLength::FOUR);
1559     SetFunction(env, atomicsObject, "notify", Atomics::Notify, FunctionLength::THREE);
1560     JSHandle<JSTaggedValue> atomicsString(factory_->NewFromASCII("Atomics"));
1561     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1562     PropertyDescriptor atomicsDesc(thread_, JSHandle<JSTaggedValue>::Cast(atomicsObject), true, false, true);
1563     JSObject::DefineOwnProperty(thread_, globalObject, atomicsString, atomicsDesc);
1564     // @@ToStringTag
1565     SetStringTagSymbol(env, atomicsObject, "Atomics");
1566     env->SetAtomicsFunction(thread_, atomicsObject);
1567 }
1568 
InitializeWeakRef(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1569 void Builtins::InitializeWeakRef(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
1570 {
1571     [[maybe_unused]] EcmaHandleScope scope(thread_);
1572     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1573     // WeakRef.prototype
1574     JSHandle<JSObject> weakRefFuncPrototype = factory_->NewJSObject(objFuncClass);
1575     JSHandle<JSTaggedValue> weakRefFuncPrototypeValue(weakRefFuncPrototype);
1576     // WeakRef.prototype_or_hclass
1577     JSHandle<JSHClass> weakRefFuncInstanceHClass =
1578         factory_->NewEcmaHClass(JSWeakRef::SIZE, JSType::JS_WEAK_REF, weakRefFuncPrototypeValue);
1579     // WeakRef() = new Function()
1580     JSHandle<JSTaggedValue> weakRefFunction(NewBuiltinConstructor(
1581         env, weakRefFuncPrototype, BuiltinsWeakRef::WeakRefConstructor, "WeakRef", FunctionLength::ONE));
1582     JSHandle<JSFunction>(weakRefFunction)->SetProtoOrHClass(thread_, weakRefFuncInstanceHClass.GetTaggedValue());
1583 
1584     // "constructor" property on the prototype
1585     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
1586     JSObject::SetProperty(thread_, JSHandle<JSTaggedValue>(weakRefFuncPrototype), constructorKey, weakRefFunction);
1587     RETURN_IF_ABRUPT_COMPLETION(thread_);
1588     // WeakRef.prototype.deref()
1589     SetFunction(env, weakRefFuncPrototype, "deref", BuiltinsWeakRef::Deref, FunctionLength::ZERO);
1590 
1591     // @@ToStringTag
1592     SetStringTagSymbol(env, weakRefFuncPrototype, "WeakRef");
1593 
1594     env->SetBuiltinsWeakRefFunction(thread_, weakRefFunction);
1595 }
1596 
LazyInitializeWeakRef(const JSHandle<GlobalEnv> & env) const1597 void Builtins::LazyInitializeWeakRef(const JSHandle<GlobalEnv> &env) const
1598 {
1599     [[maybe_unused]] EcmaHandleScope scope(thread_);
1600     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1601     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("WeakRef"));
1602     auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::WeakRef));
1603     SetLazyAccessor(globalObject, key, accessor);
1604     env->SetBuiltinsWeakRefFunction(thread_, accessor);
1605 }
1606 
InitializeFinalizationRegistry(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1607 void Builtins::InitializeFinalizationRegistry(const JSHandle<GlobalEnv> &env,
1608                                               const JSHandle<JSHClass> &objFuncClass) const
1609 {
1610     [[maybe_unused]] EcmaHandleScope scope(thread_);
1611     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1612     // FinalizationRegistry.prototype
1613     JSHandle<JSObject> finalizationRegistryFuncPrototype = factory_->NewJSObject(objFuncClass);
1614     JSHandle<JSTaggedValue> finalizationRegistryFuncPrototypeValue(finalizationRegistryFuncPrototype);
1615     // FinalizationRegistry.prototype_or_hclass
1616     JSHandle<JSHClass> finalizationRegistryFuncInstanceHClass =
1617         factory_->NewEcmaHClass(JSFinalizationRegistry::SIZE, JSType::JS_FINALIZATION_REGISTRY,
1618                                   finalizationRegistryFuncPrototypeValue);
1619     // FinalizationRegistry() = new Function()
1620     JSHandle<JSTaggedValue> finalizationRegistryFunction(NewBuiltinConstructor(
1621         env, finalizationRegistryFuncPrototype, BuiltinsFinalizationRegistry::FinalizationRegistryConstructor,
1622         "FinalizationRegistry", FunctionLength::ONE));
1623     JSHandle<JSFunction>(finalizationRegistryFunction)->SetProtoOrHClass(
1624         thread_, finalizationRegistryFuncInstanceHClass.GetTaggedValue());
1625 
1626     // "constructor" property on the prototype
1627     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
1628     JSObject::SetProperty(thread_, JSHandle<JSTaggedValue>(finalizationRegistryFuncPrototype),
1629                           constructorKey, finalizationRegistryFunction);
1630     RETURN_IF_ABRUPT_COMPLETION(thread_);
1631     // FinalizationRegistry.prototype.deref()
1632     SetFunction(env, finalizationRegistryFuncPrototype, "register",
1633                 BuiltinsFinalizationRegistry::Register, FunctionLength::TWO);
1634     SetFunction(env, finalizationRegistryFuncPrototype, "unregister",
1635                 BuiltinsFinalizationRegistry::Unregister, FunctionLength::ONE);
1636     // @@ToStringTag
1637     SetStringTagSymbol(env, finalizationRegistryFuncPrototype, "FinalizationRegistry");
1638 
1639     env->SetBuiltinsFinalizationRegistryFunction(thread_, finalizationRegistryFunction);
1640 }
1641 
LazyInitializeFinalizationRegistry(const JSHandle<GlobalEnv> & env) const1642 void Builtins::LazyInitializeFinalizationRegistry(const JSHandle<GlobalEnv> &env) const
1643 {
1644     [[maybe_unused]] EcmaHandleScope scope(thread_);
1645     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1646     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("FinalizationRegistry"));
1647     auto accessor = factory_->NewInternalAccessor(nullptr,
1648         reinterpret_cast<void *>(BuiltinsLazyCallback::FinalizationRegistry));
1649     SetLazyAccessor(globalObject, key, accessor);
1650     env->SetBuiltinsFinalizationRegistryFunction(thread_, accessor);
1651 }
1652 
InitializeMath(const JSHandle<GlobalEnv> & env,const JSHandle<JSTaggedValue> & objFuncPrototypeVal) const1653 void Builtins::InitializeMath(const JSHandle<GlobalEnv> &env, const JSHandle<JSTaggedValue> &objFuncPrototypeVal) const
1654 {
1655     [[maybe_unused]] EcmaHandleScope scope(thread_);
1656     JSHandle<JSHClass> mathClass = factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, objFuncPrototypeVal);
1657     JSHandle<JSObject> mathObject = factory_->NewJSObjectWithInit(mathClass);
1658     RandomGenerator::InitRandom();
1659     SetFunction(env, mathObject, "abs", Math::Abs, FunctionLength::ONE, BUILTINS_STUB_ID(ABS));
1660     SetFunction(env, mathObject, "acos", Math::Acos, FunctionLength::ONE, BUILTINS_STUB_ID(ACOS));
1661     SetFunction(env, mathObject, "acosh", Math::Acosh, FunctionLength::ONE);
1662     SetFunction(env, mathObject, "asin", Math::Asin, FunctionLength::ONE);
1663     SetFunction(env, mathObject, "asinh", Math::Asinh, FunctionLength::ONE);
1664     SetFunction(env, mathObject, "atan", Math::Atan, FunctionLength::ONE, BUILTINS_STUB_ID(ATAN));
1665     SetFunction(env, mathObject, "atanh", Math::Atanh, FunctionLength::ONE);
1666     SetFunction(env, mathObject, "atan2", Math::Atan2, FunctionLength::TWO);
1667     SetFunction(env, mathObject, "cbrt", Math::Cbrt, FunctionLength::ONE);
1668     SetFunction(env, mathObject, "ceil", Math::Ceil, FunctionLength::ONE);
1669     SetFunction(env, mathObject, "clz32", Math::Clz32, FunctionLength::ONE);
1670     SetFunction(env, mathObject, "cos", Math::Cos, FunctionLength::ONE, BUILTINS_STUB_ID(COS));
1671     SetFunction(env, mathObject, "cosh", Math::Cosh, FunctionLength::ONE);
1672     SetFunction(env, mathObject, "exp", Math::Exp, FunctionLength::ONE);
1673     SetFunction(env, mathObject, "expm1", Math::Expm1, FunctionLength::ONE);
1674     SetFunction(env, mathObject, "floor", Math::Floor, FunctionLength::ONE, BUILTINS_STUB_ID(FLOOR));
1675     SetFunction(env, mathObject, "fround", Math::Fround, FunctionLength::ONE);
1676     SetFunction(env, mathObject, "hypot", Math::Hypot, FunctionLength::TWO);
1677     SetFunction(env, mathObject, "imul", Math::Imul, FunctionLength::TWO);
1678     SetFunction(env, mathObject, "log", Math::Log, FunctionLength::ONE);
1679     SetFunction(env, mathObject, "log1p", Math::Log1p, FunctionLength::ONE);
1680     SetFunction(env, mathObject, "log10", Math::Log10, FunctionLength::ONE);
1681     SetFunction(env, mathObject, "log2", Math::Log2, FunctionLength::ONE);
1682     SetFunction(env, mathObject, "max", Math::Max, FunctionLength::TWO);
1683     SetFunction(env, mathObject, "min", Math::Min, FunctionLength::TWO);
1684     SetFunction(env, mathObject, "pow", Math::Pow, FunctionLength::TWO);
1685     SetFunction(env, mathObject, "random", Math::Random, FunctionLength::ZERO);
1686     SetFunction(env, mathObject, "round", Math::Round, FunctionLength::ONE);
1687     SetFunction(env, mathObject, "sign", Math::Sign, FunctionLength::ONE);
1688     SetFunction(env, mathObject, "sin", Math::Sin, FunctionLength::ONE, BUILTINS_STUB_ID(SIN));
1689     SetFunction(env, mathObject, "sinh", Math::Sinh, FunctionLength::ONE);
1690     SetFunction(env, mathObject, "sqrt", Math::Sqrt, FunctionLength::ONE, BUILTINS_STUB_ID(SQRT));
1691     SetFunction(env, mathObject, "tan", Math::Tan, FunctionLength::ONE);
1692     SetFunction(env, mathObject, "tanh", Math::Tanh, FunctionLength::ONE);
1693     SetFunction(env, mathObject, "trunc", Math::Trunc, FunctionLength::ONE);
1694 
1695     SetConstant(mathObject, "E", JSTaggedValue(Math::E));
1696     SetConstant(mathObject, "LN10", JSTaggedValue(Math::LN10));
1697     SetConstant(mathObject, "LN2", JSTaggedValue(Math::LN2));
1698     SetConstant(mathObject, "LOG10E", JSTaggedValue(Math::LOG10E));
1699     SetConstant(mathObject, "LOG2E", JSTaggedValue(Math::LOG2E));
1700     SetConstant(mathObject, "PI", JSTaggedValue(Math::PI));
1701     SetConstant(mathObject, "SQRT1_2", JSTaggedValue(Math::SQRT1_2));
1702     SetConstant(mathObject, "SQRT2", JSTaggedValue(Math::SQRT2));
1703 
1704     JSHandle<JSTaggedValue> mathString(factory_->NewFromASCII("Math"));
1705     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1706     PropertyDescriptor mathDesc(thread_, JSHandle<JSTaggedValue>::Cast(mathObject), true, false, true);
1707     JSObject::DefineOwnProperty(thread_, globalObject, mathString, mathDesc);
1708     // @@ToStringTag
1709     SetStringTagSymbol(env, mathObject, "Math");
1710     env->SetMathFunction(thread_, mathObject);
1711 }
1712 
InitializeJson(const JSHandle<GlobalEnv> & env,const JSHandle<JSTaggedValue> & objFuncPrototypeVal) const1713 void Builtins::InitializeJson(const JSHandle<GlobalEnv> &env, const JSHandle<JSTaggedValue> &objFuncPrototypeVal) const
1714 {
1715     [[maybe_unused]] EcmaHandleScope scope(thread_);
1716     JSHandle<JSHClass> jsonHClass = factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, objFuncPrototypeVal);
1717     JSHandle<JSObject> jsonObject = factory_->NewJSObjectWithInit(jsonHClass);
1718 
1719     SetFunction(env, jsonObject, "parse", Json::Parse, FunctionLength::TWO);
1720     SetFunction(env, jsonObject, "stringify", Json::Stringify, FunctionLength::THREE);
1721 
1722     PropertyDescriptor jsonDesc(thread_, JSHandle<JSTaggedValue>::Cast(jsonObject), true, false, true);
1723     JSHandle<JSTaggedValue> jsonString(factory_->NewFromASCII("JSON"));
1724     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
1725     JSObject::DefineOwnProperty(thread_, globalObject, jsonString, jsonDesc);
1726     // @@ToStringTag
1727     SetStringTagSymbol(env, jsonObject, "JSON");
1728     env->SetJsonFunction(thread_, jsonObject);
1729 }
1730 
InitializeString(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & primRefObjHClass) const1731 void Builtins::InitializeString(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &primRefObjHClass) const
1732 {
1733     [[maybe_unused]] EcmaHandleScope scope(thread_);
1734     // String.prototype
1735     JSHandle<JSTaggedValue> toObject(factory_->GetEmptyString());
1736     JSHandle<JSObject> stringFuncPrototype =
1737         JSHandle<JSObject>::Cast(factory_->NewJSPrimitiveRef(primRefObjHClass, toObject));
1738     JSHandle<JSTaggedValue> stringFuncPrototypeValue(stringFuncPrototype);
1739 
1740     // String.prototype_or_hclass
1741     JSHandle<JSHClass> stringFuncInstanceHClass =
1742         factory_->NewEcmaHClass(JSPrimitiveRef::SIZE, JSType::JS_PRIMITIVE_REF, stringFuncPrototypeValue);
1743 
1744     // String = new Function()
1745     JSHandle<JSObject> stringFunction(NewBuiltinConstructor(env, stringFuncPrototype, BuiltinsString::StringConstructor,
1746                                                             "String", FunctionLength::ONE));
1747     stringFunction.GetObject<JSFunction>()->SetFunctionPrototype(thread_, stringFuncInstanceHClass.GetTaggedValue());
1748 
1749     // String.prototype method
1750     SetFunction(env, stringFuncPrototype, "charAt", BuiltinsString::CharAt, FunctionLength::ONE,
1751                 BUILTINS_STUB_ID(CharAt));
1752     SetFunction(env, stringFuncPrototype, "charCodeAt", BuiltinsString::CharCodeAt, FunctionLength::ONE,
1753                 BUILTINS_STUB_ID(CharCodeAt));
1754     SetFunction(env, stringFuncPrototype, "codePointAt", BuiltinsString::CodePointAt, FunctionLength::ONE);
1755     SetFunction(env, stringFuncPrototype, "concat", BuiltinsString::Concat, FunctionLength::ONE);
1756     SetFunction(env, stringFuncPrototype, "endsWith", BuiltinsString::EndsWith, FunctionLength::ONE);
1757     SetFunction(env, stringFuncPrototype, "includes", BuiltinsString::Includes, FunctionLength::ONE);
1758     SetFunction(env, stringFuncPrototype, "indexOf", BuiltinsString::IndexOf, FunctionLength::ONE,
1759                 BUILTINS_STUB_ID(IndexOf));
1760     SetFunction(env, stringFuncPrototype, "lastIndexOf", BuiltinsString::LastIndexOf, FunctionLength::ONE);
1761     SetFunction(env, stringFuncPrototype, "localeCompare", BuiltinsString::LocaleCompare, FunctionLength::ONE);
1762     SetFunction(env, stringFuncPrototype, "match", BuiltinsString::Match, FunctionLength::ONE);
1763     SetFunction(env, stringFuncPrototype, "matchAll", BuiltinsString::MatchAll, FunctionLength::ONE);
1764     SetFunction(env, stringFuncPrototype, "repeat", BuiltinsString::Repeat, FunctionLength::ONE);
1765     SetFunction(env, stringFuncPrototype, "normalize", BuiltinsString::Normalize, FunctionLength::ZERO);
1766     SetFunction(env, stringFuncPrototype, "padStart", BuiltinsString::PadStart, FunctionLength::ONE);
1767     SetFunction(env, stringFuncPrototype, "padEnd", BuiltinsString::PadEnd, FunctionLength::ONE);
1768     SetFunction(env, stringFuncPrototype, "replace", BuiltinsString::Replace, FunctionLength::TWO);
1769     SetFunction(env, stringFuncPrototype, "replaceAll", BuiltinsString::ReplaceAll, FunctionLength::TWO);
1770     SetFunction(env, stringFuncPrototype, "search", BuiltinsString::Search, FunctionLength::ONE);
1771     SetFunction(env, stringFuncPrototype, "slice", BuiltinsString::Slice, FunctionLength::TWO);
1772     SetFunction(env, stringFuncPrototype, "split", BuiltinsString::Split, FunctionLength::TWO);
1773     SetFunction(env, stringFuncPrototype, "startsWith", BuiltinsString::StartsWith, FunctionLength::ONE);
1774     SetFunction(env, stringFuncPrototype, "substring", BuiltinsString::Substring, FunctionLength::TWO,
1775                 BUILTINS_STUB_ID(Substring));
1776     SetFunction(env, stringFuncPrototype, "substr", BuiltinsString::SubStr, FunctionLength::TWO);
1777     SetFunction(env, stringFuncPrototype, "at", BuiltinsString::At, FunctionLength::ONE);
1778     SetFunction(env, stringFuncPrototype, "toLocaleLowerCase", BuiltinsString::ToLocaleLowerCase, FunctionLength::ZERO);
1779     SetFunction(env, stringFuncPrototype, "toLocaleUpperCase", BuiltinsString::ToLocaleUpperCase, FunctionLength::ZERO);
1780     SetFunction(env, stringFuncPrototype, "toLowerCase", BuiltinsString::ToLowerCase, FunctionLength::ZERO);
1781     SetFunction(env, stringFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(),
1782                 BuiltinsString::ToString, FunctionLength::ZERO);
1783     SetFunction(env, stringFuncPrototype, "toUpperCase", BuiltinsString::ToUpperCase, FunctionLength::ZERO);
1784     SetFunction(env, stringFuncPrototype, "trim", BuiltinsString::Trim, FunctionLength::ZERO);
1785     SetFunction(env, stringFuncPrototype, "trimStart", BuiltinsString::TrimStart, FunctionLength::ZERO);
1786     SetFunction(env, stringFuncPrototype, "trimEnd", BuiltinsString::TrimEnd, FunctionLength::ZERO);
1787     SetFunction(env, stringFuncPrototype, "trimLeft", BuiltinsString::TrimLeft, FunctionLength::ZERO);
1788     SetFunction(env, stringFuncPrototype, "trimRight", BuiltinsString::TrimRight, FunctionLength::ZERO);
1789     SetFunction(env, stringFuncPrototype, thread_->GlobalConstants()->GetHandledValueOfString(),
1790                 BuiltinsString::ValueOf, FunctionLength::ZERO);
1791     SetFunctionAtSymbol(env, stringFuncPrototype, env->GetIteratorSymbol(), "[Symbol.iterator]",
1792                         BuiltinsString::GetStringIterator, FunctionLength::ZERO);
1793 
1794     // String method
1795     SetFunction(env, stringFunction, "fromCharCode", BuiltinsString::FromCharCode, FunctionLength::ONE);
1796     SetFunction(env, stringFunction, "fromCodePoint", BuiltinsString::FromCodePoint, FunctionLength::ONE);
1797     SetFunction(env, stringFunction, "raw", BuiltinsString::Raw, FunctionLength::ONE);
1798 
1799     // String.prototype.length
1800     JSHandle<JSTaggedValue> lengthGetter = CreateGetter(env, BuiltinsString::GetLength, "length", FunctionLength::ZERO);
1801     JSHandle<JSTaggedValue> lengthKey(factory_->NewFromASCII("length"));
1802     SetGetter(stringFuncPrototype, lengthKey, lengthGetter);
1803 
1804     env->SetStringFunction(thread_, stringFunction);
1805 }
1806 
InitializeStringIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & iteratorFuncClass) const1807 void Builtins::InitializeStringIterator(const JSHandle<GlobalEnv> &env,
1808                                         const JSHandle<JSHClass> &iteratorFuncClass) const
1809 {
1810     // StringIterator.prototype
1811     JSHandle<JSObject> strIterPrototype(factory_->NewJSObjectWithInit(iteratorFuncClass));
1812 
1813     // StringIterator.prototype_or_hclass
1814     JSHandle<JSHClass> strIterFuncInstanceHClass = factory_->NewEcmaHClass(
1815         JSStringIterator::SIZE, JSType::JS_STRING_ITERATOR, JSHandle<JSTaggedValue>(strIterPrototype));
1816 
1817     JSHandle<JSFunction> strIterFunction(
1818         factory_->NewJSFunction(env, static_cast<void *>(nullptr), FunctionKind::BASE_CONSTRUCTOR));
1819     strIterFunction->SetFunctionPrototype(thread_, strIterFuncInstanceHClass.GetTaggedValue());
1820 
1821     SetFunction(env, strIterPrototype, "next", StringIterator::Next, FunctionLength::ZERO);
1822     SetStringTagSymbol(env, strIterPrototype, "String Iterator");
1823 
1824     env->SetStringIterator(thread_, strIterFunction);
1825     env->SetStringIteratorPrototype(thread_, strIterPrototype);
1826 }
1827 
InitializeAsyncFromSyncIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & iteratorFuncClass) const1828 void Builtins::InitializeAsyncFromSyncIterator(const JSHandle<GlobalEnv> &env,
1829                                                const JSHandle<JSHClass> &iteratorFuncClass) const
1830 {
1831     [[maybe_unused]] EcmaHandleScope scope(thread_);
1832 
1833     JSHandle<JSObject> asyncItPrototype = factory_->NewJSObjectWithInit(iteratorFuncClass);
1834     SetFunction(env, asyncItPrototype, "next", BuiltinsAsyncFromSyncIterator::Next, FunctionLength::ONE);
1835     SetFunction(env, asyncItPrototype, "return", BuiltinsAsyncFromSyncIterator::Return, FunctionLength::ONE);
1836     SetFunction(env, asyncItPrototype, "throw", BuiltinsAsyncFromSyncIterator::Throw, FunctionLength::ONE);
1837     JSHandle<JSHClass> hclass = factory_->NewEcmaHClass(JSAsyncFromSyncIterator::SIZE,
1838                                                         JSType::JS_ASYNC_FROM_SYNC_ITERATOR,
1839                                                         JSHandle<JSTaggedValue>(asyncItPrototype));
1840     JSHandle<JSFunction> iterFunction(
1841         factory_->NewJSFunction(env, static_cast<void *>(nullptr), FunctionKind::BASE_CONSTRUCTOR));
1842     iterFunction->SetFunctionPrototype(thread_, hclass.GetTaggedValue());
1843     env->SetAsyncFromSyncIterator(thread_, iterFunction);
1844     env->SetAsyncFromSyncIteratorPrototype(thread_, asyncItPrototype);
1845 
1846     JSHandle<JSHClass> asyncFromSyncIterUnwarpClass =
1847         factory_->NewEcmaHClass(JSAsyncFromSyncIterUnwarpFunction::SIZE,
1848                                 JSType::JS_ASYNC_FROM_SYNC_ITER_UNWARP_FUNCTION,
1849                                 env->GetFunctionPrototype());
1850     asyncFromSyncIterUnwarpClass->SetCallable(true);
1851     asyncFromSyncIterUnwarpClass->SetExtensible(true);
1852     env->SetAsyncFromSyncIterUnwarpClass(thread_, asyncFromSyncIterUnwarpClass);
1853 }
1854 
InitializeIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const1855 void Builtins::InitializeIterator(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
1856 {
1857     [[maybe_unused]] EcmaHandleScope scope(thread_);
1858     // Iterator.prototype
1859     JSHandle<JSObject> iteratorPrototype = factory_->NewJSObjectWithInit(objFuncClass);
1860     // Iterator.prototype.next()
1861     SetFunction(env, iteratorPrototype, "next", BuiltinsIterator::Next, FunctionLength::ONE);
1862     // Iterator.prototype.return()
1863     SetFunction(env, iteratorPrototype, "return", BuiltinsIterator::Return, FunctionLength::ONE);
1864     // Iterator.prototype.throw()
1865     SetFunction(env, iteratorPrototype, "throw", BuiltinsIterator::Throw, FunctionLength::ONE);
1866     // %IteratorPrototype% [ @@iterator ]
1867     SetFunctionAtSymbol(env, iteratorPrototype, env->GetIteratorSymbol(), "[Symbol.iterator]",
1868                         BuiltinsIterator::GetIteratorObj, FunctionLength::ZERO);
1869     env->SetIteratorPrototype(thread_, iteratorPrototype);
1870 
1871     // Iterator.hclass
1872     JSHandle<JSHClass> iteratorFuncClass =
1873         factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_ITERATOR, JSHandle<JSTaggedValue>(iteratorPrototype));
1874 
1875     auto globalConst = const_cast<GlobalEnvConstants *>(thread_->GlobalConstants());
1876     globalConst->SetConstant(ConstantIndex::JS_API_ITERATOR_FUNC_CLASS_INDEX, iteratorFuncClass);
1877 
1878     // Iterator result hclass
1879     JSHandle<JSHClass> iterResultHClass = factory_->CreateIteratorResultInstanceClass(env);
1880     globalConst->SetConstant(ConstantIndex::ITERATOR_RESULT_CLASS, iterResultHClass);
1881 
1882     // ues for CloseIterator
1883     JSHandle<CompletionRecord> record =
1884         factory_->NewCompletionRecord(CompletionRecordType::NORMAL, globalConst->GetHandledUndefined());
1885     globalConst->SetConstant(ConstantIndex::UNDEFINED_COMPLRTION_RECORD_INDEX, record);
1886 
1887     InitializeForinIterator(env, iteratorFuncClass);
1888     InitializeSetIterator(env, iteratorFuncClass);
1889     InitializeMapIterator(env, iteratorFuncClass);
1890     InitializeArrayIterator(env, iteratorFuncClass);
1891     InitializeStringIterator(env, iteratorFuncClass);
1892     InitializeRegexpIterator(env, iteratorFuncClass);
1893 }
1894 
InitializeAsyncIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncDynclass) const1895 void Builtins::InitializeAsyncIterator(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncDynclass) const
1896 {
1897     [[maybe_unused]] EcmaHandleScope scope(thread_);
1898     // AsyncIterator.prototype
1899     JSHandle<JSObject> asyncIteratorPrototype = factory_->NewJSObjectWithInit(objFuncDynclass);
1900     // AsyncIterator.prototype.next()
1901     SetFunction(env, asyncIteratorPrototype, "next", BuiltinsAsyncIterator::Next, FunctionLength::ONE);
1902     // AsyncIterator.prototype.return()
1903     SetFunction(env, asyncIteratorPrototype, "return", BuiltinsAsyncIterator::Return, FunctionLength::ONE);
1904     // AsyncIterator.prototype.throw()
1905     SetFunction(env, asyncIteratorPrototype, "throw", BuiltinsAsyncIterator::Throw, FunctionLength::ONE);
1906     // %AsyncIteratorPrototype% [ @@AsyncIterator ]
1907     SetFunctionAtSymbol(env, asyncIteratorPrototype, env->GetAsyncIteratorSymbol(), "[Symbol.asyncIterator]",
1908                         BuiltinsAsyncIterator::GetAsyncIteratorObj, FunctionLength::ZERO);
1909     env->SetAsyncIteratorPrototype(thread_, asyncIteratorPrototype);
1910 
1911     // AsyncIterator.dynclass
1912     JSHandle<JSHClass> asyncIteratorFuncDynclass =
1913         factory_->NewEcmaHClass(JSObject::SIZE,
1914                                   JSType::JS_ASYNCITERATOR, JSHandle<JSTaggedValue>(asyncIteratorPrototype));
1915 
1916     auto globalConst = const_cast<GlobalEnvConstants *>(thread_->GlobalConstants());
1917     globalConst->SetConstant(ConstantIndex::JS_API_ASYNCITERATOR_FUNC_CLASS_INDEX, asyncIteratorFuncDynclass);
1918 }
1919 
InitializeForinIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & iteratorFuncClass) const1920 void Builtins::InitializeForinIterator(const JSHandle<GlobalEnv> &env,
1921                                        const JSHandle<JSHClass> &iteratorFuncClass) const
1922 {
1923     [[maybe_unused]] EcmaHandleScope scope(thread_);
1924     // Iterator.prototype
1925     JSHandle<JSObject> forinIteratorPrototype = factory_->NewJSObjectWithInit(iteratorFuncClass);
1926     JSHandle<JSHClass> hclass = factory_->NewEcmaHClass(JSForInIterator::SIZE, JSType::JS_FORIN_ITERATOR,
1927                                                             JSHandle<JSTaggedValue>(forinIteratorPrototype));
1928 
1929     // Iterator.prototype.next()
1930     SetFunction(env, forinIteratorPrototype, "next", JSForInIterator::Next, FunctionLength::ONE);
1931     env->SetForinIteratorPrototype(thread_, forinIteratorPrototype);
1932     env->SetForinIteratorClass(thread_, hclass);
1933 }
1934 
InitializeSetIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & iteratorFuncClass) const1935 void Builtins::InitializeSetIterator(const JSHandle<GlobalEnv> &env,
1936                                      const JSHandle<JSHClass> &iteratorFuncClass) const
1937 {
1938     // SetIterator.prototype
1939     JSHandle<JSObject> setIteratorPrototype(factory_->NewJSObjectWithInit(iteratorFuncClass));
1940     // Iterator.prototype.next()
1941     SetFunction(env, setIteratorPrototype, "next", JSSetIterator::Next, FunctionLength::ZERO);
1942     SetStringTagSymbol(env, setIteratorPrototype, "Set Iterator");
1943     env->SetSetIteratorPrototype(thread_, setIteratorPrototype);
1944 }
1945 
InitializeMapIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & iteratorFuncClass) const1946 void Builtins::InitializeMapIterator(const JSHandle<GlobalEnv> &env,
1947                                      const JSHandle<JSHClass> &iteratorFuncClass) const
1948 {
1949     // MapIterator.prototype
1950     JSHandle<JSObject> mapIteratorPrototype(factory_->NewJSObjectWithInit(iteratorFuncClass));
1951     // Iterator.prototype.next()
1952     SetFunction(env, mapIteratorPrototype, "next", JSMapIterator::Next, FunctionLength::ZERO);
1953     SetStringTagSymbol(env, mapIteratorPrototype, "Map Iterator");
1954     env->SetMapIteratorPrototype(thread_, mapIteratorPrototype);
1955 }
InitializeArrayIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & iteratorFuncClass) const1956 void Builtins::InitializeArrayIterator(const JSHandle<GlobalEnv> &env,
1957                                        const JSHandle<JSHClass> &iteratorFuncClass) const
1958 {
1959     // ArrayIterator.prototype
1960     JSHandle<JSObject> arrayIteratorPrototype(factory_->NewJSObjectWithInit(iteratorFuncClass));
1961     // Iterator.prototype.next()
1962     SetFunction(env, arrayIteratorPrototype, "next", JSArrayIterator::Next, FunctionLength::ZERO);
1963     SetStringTagSymbol(env, arrayIteratorPrototype, "Array Iterator");
1964     env->SetArrayIteratorPrototype(thread_, arrayIteratorPrototype);
1965 }
1966 
InitializeRegexpIterator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & iteratorFuncClass) const1967 void Builtins::InitializeRegexpIterator(const JSHandle<GlobalEnv> &env,
1968                                         const JSHandle<JSHClass> &iteratorFuncClass) const
1969 {
1970     // RegExpIterator.prototype
1971     JSHandle<JSObject> regExpIteratorPrototype(factory_->NewJSObject(iteratorFuncClass));
1972     // Iterator.prototype.next()
1973     SetFunction(env, regExpIteratorPrototype, "next", JSRegExpIterator::Next, FunctionLength::ZERO);
1974     SetStringTagSymbol(env, regExpIteratorPrototype, "RegExp String Iterator");
1975     env->SetRegExpIteratorPrototype(thread_, regExpIteratorPrototype);
1976 }
1977 
InitializeRegExp(const JSHandle<GlobalEnv> & env)1978 void Builtins::InitializeRegExp(const JSHandle<GlobalEnv> &env)
1979 {
1980     [[maybe_unused]] EcmaHandleScope scope(thread_);
1981     // RegExp.prototype
1982     JSHandle<JSFunction> objFun(env->GetObjectFunction());
1983     JSHandle<JSObject> regPrototype = factory_->NewJSObjectByConstructor(objFun);
1984     JSHandle<JSTaggedValue> regPrototypeValue(regPrototype);
1985 
1986     // RegExp.prototype_or_hclass
1987     JSHandle<JSHClass> regexpFuncInstanceHClass = factory_->CreateJSRegExpInstanceClass(regPrototypeValue);
1988 
1989     // RegExp = new Function()
1990     JSHandle<JSObject> regexpFunction(
1991         NewBuiltinConstructor(env, regPrototype, RegExp::RegExpConstructor, "RegExp", FunctionLength::TWO));
1992 
1993     // initialize RegExp.$1 .. $9 static and read-only attributes
1994     InitializeGlobalRegExp(regexpFunction);
1995 
1996     JSHandle<JSFunction>(regexpFunction)->SetFunctionPrototype(thread_, regexpFuncInstanceHClass.GetTaggedValue());
1997 
1998     const GlobalEnvConstants *globalConstants = thread_->GlobalConstants();
1999     // RegExp.prototype method
2000     SetFunction(env, regPrototype, "exec", RegExp::Exec, FunctionLength::ONE);
2001     SetFunction(env, regPrototype, "test", RegExp::Test, FunctionLength::ONE);
2002     SetFunction(env, regPrototype, globalConstants->GetHandledToStringString(), RegExp::ToString,
2003                 FunctionLength::ZERO);
2004 
2005     JSHandle<JSTaggedValue> flagsGetter = CreateGetter(env, RegExp::GetFlags, "flags", FunctionLength::ZERO);
2006     JSHandle<JSTaggedValue> flagsKey(globalConstants->GetHandledFlagsString());
2007     SetGetter(regPrototype, flagsKey, flagsGetter);
2008 
2009     JSHandle<JSTaggedValue> sourceGetter = CreateGetter(env, RegExp::GetSource, "source", FunctionLength::ZERO);
2010     JSHandle<JSTaggedValue> sourceKey(globalConstants->GetHandledSourceString());
2011     SetGetter(regPrototype, sourceKey, sourceGetter);
2012 
2013     JSHandle<JSTaggedValue> globalGetter = CreateGetter(env, RegExp::GetGlobal, "global", FunctionLength::ZERO);
2014     JSHandle<JSTaggedValue> globalKey(globalConstants->GetHandledGlobalString());
2015     SetGetter(regPrototype, globalKey, globalGetter);
2016 
2017     JSHandle<JSTaggedValue> ignoreCaseGetter =
2018         CreateGetter(env, RegExp::GetIgnoreCase, "ignoreCase", FunctionLength::ZERO);
2019     JSHandle<JSTaggedValue> ignoreCaseKey(factory_->NewFromASCII("ignoreCase"));
2020     SetGetter(regPrototype, ignoreCaseKey, ignoreCaseGetter);
2021 
2022     JSHandle<JSTaggedValue> multilineGetter =
2023         CreateGetter(env, RegExp::GetMultiline, "multiline", FunctionLength::ZERO);
2024     JSHandle<JSTaggedValue> multilineKey(factory_->NewFromASCII("multiline"));
2025     SetGetter(regPrototype, multilineKey, multilineGetter);
2026 
2027     JSHandle<JSTaggedValue> dotAllGetter = CreateGetter(env, RegExp::GetDotAll, "dotAll", FunctionLength::ZERO);
2028     JSHandle<JSTaggedValue> dotAllKey(factory_->NewFromASCII("dotAll"));
2029     SetGetter(regPrototype, dotAllKey, dotAllGetter);
2030 
2031     JSHandle<JSTaggedValue> stickyGetter = CreateGetter(env, RegExp::GetSticky, "sticky", FunctionLength::ZERO);
2032     JSHandle<JSTaggedValue> stickyKey(globalConstants->GetHandledStickyString());
2033     SetGetter(regPrototype, stickyKey, stickyGetter);
2034 
2035     JSHandle<JSTaggedValue> unicodeGetter = CreateGetter(env, RegExp::GetUnicode, "unicode", FunctionLength::ZERO);
2036     JSHandle<JSTaggedValue> unicodeKey(globalConstants->GetHandledUnicodeString());
2037     SetGetter(regPrototype, unicodeKey, unicodeGetter);
2038 
2039     // Set RegExp [ @@species ]
2040     JSHandle<JSTaggedValue> speciesSymbol = env->GetSpeciesSymbol();
2041     JSHandle<JSTaggedValue> speciesGetter =
2042         CreateGetter(env, BuiltinsMap::Species, "[Symbol.species]", FunctionLength::ZERO);
2043     SetGetter(JSHandle<JSObject>(regexpFunction), speciesSymbol, speciesGetter);
2044 
2045     // Set RegExp.prototype[@@split]
2046     SetFunctionAtSymbol(env, regPrototype, env->GetSplitSymbol(), "[Symbol.split]", RegExp::Split, FunctionLength::TWO);
2047     // Set RegExp.prototype[@@search]
2048     SetFunctionAtSymbol(env, regPrototype, env->GetSearchSymbol(), "[Symbol.search]", RegExp::Search,
2049                         FunctionLength::ONE);
2050     // Set RegExp.prototype[@@match]
2051     SetFunctionAtSymbol(env, regPrototype, env->GetMatchSymbol(), "[Symbol.match]", RegExp::Match, FunctionLength::ONE);
2052     // Set RegExp.prototype[@@matchAll]
2053     SetFunctionAtSymbol(env, regPrototype, env->GetMatchAllSymbol(), "[Symbol.matchAll]", RegExp::MatchAll,
2054                         FunctionLength::ONE);
2055     // Set RegExp.prototype[@@replace]
2056     SetFunctionAtSymbol(env, regPrototype, env->GetReplaceSymbol(), "[Symbol.replace]", RegExp::Replace,
2057                         FunctionLength::TWO);
2058 
2059     env->SetRegExpFunction(thread_, regexpFunction);
2060     auto globalConst = const_cast<GlobalEnvConstants *>(thread_->GlobalConstants());
2061     globalConst->SetConstant(ConstantIndex::JS_REGEXP_CLASS_INDEX, regexpFuncInstanceHClass.GetTaggedValue());
2062 }
2063 
InitializeArray(const JSHandle<GlobalEnv> & env,const JSHandle<JSTaggedValue> & objFuncPrototypeVal) const2064 void Builtins::InitializeArray(const JSHandle<GlobalEnv> &env, const JSHandle<JSTaggedValue> &objFuncPrototypeVal) const
2065 {
2066     [[maybe_unused]] EcmaHandleScope scope(thread_);
2067     // Arraybase.prototype
2068     JSHandle<JSHClass> arrBaseFuncInstanceHClass = factory_->CreateJSArrayInstanceClass(objFuncPrototypeVal);
2069 
2070     // Array.prototype
2071     JSHandle<JSObject> arrFuncPrototype = factory_->NewJSObjectWithInit(arrBaseFuncInstanceHClass);
2072     JSHandle<JSArray>::Cast(arrFuncPrototype)->SetLength(FunctionLength::ZERO);
2073     auto accessor = thread_->GlobalConstants()->GetArrayLengthAccessor();
2074     JSArray::Cast(*arrFuncPrototype)->SetPropertyInlinedProps(thread_, JSArray::LENGTH_INLINE_PROPERTY_INDEX, accessor);
2075     JSHandle<JSTaggedValue> arrFuncPrototypeValue(arrFuncPrototype);
2076 
2077     //  Array.prototype_or_hclass
2078     JSHandle<JSHClass> arrFuncInstanceHClass = factory_->CreateJSArrayInstanceClass(arrFuncPrototypeValue);
2079     auto globalConstant = const_cast<GlobalEnvConstants *>(thread_->GlobalConstants());
2080     globalConstant->InitElementKindHClass(thread_, arrFuncInstanceHClass);
2081 
2082     // Array = new Function()
2083     JSHandle<JSObject> arrayFunction(
2084         NewBuiltinConstructor(env, arrFuncPrototype, BuiltinsArray::ArrayConstructor, "Array", FunctionLength::ONE,
2085                               BUILTINS_STUB_ID(ArrayConstructor)));
2086     JSHandle<JSFunction> arrayFuncFunction(arrayFunction);
2087 
2088     // Set the [[Realm]] internal slot of F to the running execution context's Realm
2089     JSHandle<LexicalEnv> lexicalEnv = factory_->NewLexicalEnv(0);
2090     lexicalEnv->SetParentEnv(thread_, env.GetTaggedValue());
2091     arrayFuncFunction->SetLexicalEnv(thread_, lexicalEnv.GetTaggedValue());
2092 
2093     arrayFuncFunction->SetFunctionPrototype(thread_, arrFuncInstanceHClass.GetTaggedValue());
2094 
2095     // Array.prototype method
2096     SetFunction(env, arrFuncPrototype, "concat", BuiltinsArray::Concat, FunctionLength::ONE);
2097     SetFunction(env, arrFuncPrototype, "copyWithin", BuiltinsArray::CopyWithin, FunctionLength::TWO);
2098     SetFunction(env, arrFuncPrototype, "entries", BuiltinsArray::Entries, FunctionLength::ZERO);
2099     SetFunction(env, arrFuncPrototype, "every", BuiltinsArray::Every, FunctionLength::ONE);
2100     SetFunction(env, arrFuncPrototype, "fill", BuiltinsArray::Fill, FunctionLength::ONE);
2101     SetFunction(env, arrFuncPrototype, "filter", BuiltinsArray::Filter, FunctionLength::ONE);
2102     SetFunction(env, arrFuncPrototype, "find", BuiltinsArray::Find, FunctionLength::ONE);
2103     SetFunction(env, arrFuncPrototype, "findIndex", BuiltinsArray::FindIndex, FunctionLength::ONE);
2104     SetFunction(env, arrFuncPrototype, "findLast", BuiltinsArray::FindLast, FunctionLength::ONE);
2105     SetFunction(env, arrFuncPrototype, "findLastIndex", BuiltinsArray::FindLastIndex, FunctionLength::ONE);
2106     SetFunction(env, arrFuncPrototype, "forEach", BuiltinsArray::ForEach, FunctionLength::ONE);
2107     SetFunction(env, arrFuncPrototype, "indexOf", BuiltinsArray::IndexOf, FunctionLength::ONE);
2108     SetFunction(env, arrFuncPrototype, "join", BuiltinsArray::Join, FunctionLength::ONE);
2109     SetFunction(env, arrFuncPrototype, "keys", BuiltinsArray::Keys, FunctionLength::ZERO);
2110     SetFunction(env, arrFuncPrototype, "lastIndexOf", BuiltinsArray::LastIndexOf, FunctionLength::ONE);
2111     SetFunction(env, arrFuncPrototype, "map", BuiltinsArray::Map, FunctionLength::ONE);
2112     SetFunction(env, arrFuncPrototype, "pop", BuiltinsArray::Pop, FunctionLength::ZERO);
2113     SetFunction(env, arrFuncPrototype, "push", BuiltinsArray::Push, FunctionLength::ONE);
2114     SetFunction(env, arrFuncPrototype, "reduce", BuiltinsArray::Reduce, FunctionLength::ONE);
2115     SetFunction(env, arrFuncPrototype, "reduceRight", BuiltinsArray::ReduceRight, FunctionLength::ONE);
2116     SetFunction(env, arrFuncPrototype, "reverse", BuiltinsArray::Reverse, FunctionLength::ZERO);
2117     SetFunction(env, arrFuncPrototype, "shift", BuiltinsArray::Shift, FunctionLength::ZERO);
2118     SetFunction(env, arrFuncPrototype, "slice", BuiltinsArray::Slice, FunctionLength::TWO);
2119     SetFunction(env, arrFuncPrototype, "some", BuiltinsArray::Some, FunctionLength::ONE);
2120     SetFunction(env, arrFuncPrototype, "sort", BuiltinsArray::Sort, FunctionLength::ONE);
2121     SetFunction(env, arrFuncPrototype, "splice", BuiltinsArray::Splice, FunctionLength::TWO);
2122     SetFunction(env, arrFuncPrototype, thread_->GlobalConstants()->GetHandledToLocaleStringString(),
2123                 BuiltinsArray::ToLocaleString, FunctionLength::ZERO);
2124     SetFunction(env, arrFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(), BuiltinsArray::ToString,
2125                 FunctionLength::ZERO);
2126     SetFunction(env, arrFuncPrototype, "unshift", BuiltinsArray::Unshift, FunctionLength::ONE);
2127     SetFunction(env, arrFuncPrototype, "values", BuiltinsArray::Values, FunctionLength::ZERO);
2128     SetFunction(env, arrFuncPrototype, "includes", BuiltinsArray::Includes, FunctionLength::ONE);
2129     SetFunction(env, arrFuncPrototype, "flat", BuiltinsArray::Flat, FunctionLength::ZERO);
2130     SetFunction(env, arrFuncPrototype, "flatMap", BuiltinsArray::FlatMap, FunctionLength::ONE);
2131     SetFunction(env, arrFuncPrototype, "at", BuiltinsArray::At, FunctionLength::ONE);
2132     SetFunction(env, arrFuncPrototype, "toReversed", BuiltinsArray::ToReversed, FunctionLength::ZERO);
2133     SetFunction(env, arrFuncPrototype, "with", BuiltinsArray::With, FunctionLength::TWO);
2134     SetFunction(env, arrFuncPrototype, "toSorted", BuiltinsArray::ToSorted, FunctionLength::ONE);
2135     SetFunction(env, arrFuncPrototype, "toSpliced", BuiltinsArray::ToSpliced, FunctionLength::TWO);
2136 
2137     // %ArrayPrototype% [ @@iterator ]
2138     JSHandle<JSTaggedValue> values(factory_->NewFromASCII("values"));
2139     JSHandle<JSTaggedValue> iteratorSymbol = env->GetIteratorSymbol();
2140     JSHandle<JSTaggedValue> valuesFunc =
2141         JSObject::GetMethod(thread_, JSHandle<JSTaggedValue>::Cast(arrFuncPrototype), values);
2142     RETURN_IF_ABRUPT_COMPLETION(thread_);
2143     PropertyDescriptor iteartorDesc(thread_, valuesFunc, true, false, true);
2144     JSObject::DefineOwnProperty(thread_, arrFuncPrototype, iteratorSymbol, iteartorDesc);
2145 
2146     // Array method
2147     SetFunction(env, arrayFunction, "from", BuiltinsArray::From, FunctionLength::ONE);
2148     SetFunction(env, arrayFunction, "isArray", BuiltinsArray::IsArray, FunctionLength::ONE);
2149     SetFunction(env, arrayFunction, "of", BuiltinsArray::Of, FunctionLength::ZERO);
2150 
2151     // 22.1.2.5 get %Array% [ @@species ]
2152     JSHandle<JSTaggedValue> speciesSymbol = env->GetSpeciesSymbol();
2153     JSHandle<JSTaggedValue> speciesGetter =
2154         CreateGetter(env, BuiltinsArray::Species, "[Symbol.species]", FunctionLength::ZERO);
2155     SetGetter(JSHandle<JSObject>(arrayFunction), speciesSymbol, speciesGetter);
2156 
2157     constexpr int arrProtoLen = 0;
2158     JSHandle<JSTaggedValue> keyString = thread_->GlobalConstants()->GetHandledLengthString();
2159     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>(thread_, JSTaggedValue(arrProtoLen)), true, false,
2160                                   false);
2161     JSObject::DefineOwnProperty(thread_, arrFuncPrototype, keyString, descriptor);
2162 
2163     JSHandle<JSTaggedValue> valuesKey(factory_->NewFromASCII("values"));
2164     PropertyDescriptor desc(thread_);
2165     JSObject::GetOwnProperty(thread_, arrFuncPrototype, valuesKey, desc);
2166 
2167     // Array.prototype [ @@unscopables ]
2168     JSHandle<JSTaggedValue> unscopablesSymbol = env->GetUnscopablesSymbol();
2169     JSHandle<JSTaggedValue> unscopablesGetter =
2170         CreateGetter(env, BuiltinsArray::Unscopables, "[Symbol.unscopables]", FunctionLength::ZERO);
2171     SetGetter(JSHandle<JSObject>(arrFuncPrototype), unscopablesSymbol, unscopablesGetter);
2172 
2173     env->SetArrayProtoValuesFunction(thread_, desc.GetValue());
2174     env->SetArrayFunction(thread_, arrayFunction);
2175     env->SetArrayPrototype(thread_, arrFuncPrototype);
2176 }
2177 
InitializeTypedArray(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2178 void Builtins::InitializeTypedArray(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2179 {
2180     [[maybe_unused]] EcmaHandleScope scope(thread_);
2181     // TypedArray.prototype
2182     JSHandle<JSObject> typedArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2183     JSHandle<JSTaggedValue> typedArrFuncPrototypeValue(typedArrFuncPrototype);
2184 
2185     // TypedArray.prototype_or_hclass
2186     JSHandle<JSHClass> typedArrFuncInstanceHClass = factory_->NewEcmaHClass(
2187         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_TYPED_ARRAY, typedArrFuncPrototypeValue);
2188 
2189     // TypedArray = new Function()
2190     JSHandle<JSObject> typedArrayFunction(NewBuiltinConstructor(
2191         env, typedArrFuncPrototype, BuiltinsTypedArray::TypedArrayBaseConstructor, "TypedArray", FunctionLength::ZERO));
2192 
2193     JSHandle<JSFunction>(typedArrayFunction)
2194         ->SetProtoOrHClass(thread_, typedArrFuncInstanceHClass.GetTaggedValue());
2195 
2196     // TypedArray.prototype method
2197     SetFunction(env, typedArrFuncPrototype, "copyWithin", BuiltinsTypedArray::CopyWithin, FunctionLength::TWO);
2198     SetFunction(env, typedArrFuncPrototype, "entries", BuiltinsTypedArray::Entries, FunctionLength::ZERO);
2199     SetFunction(env, typedArrFuncPrototype, "every", BuiltinsTypedArray::Every, FunctionLength::ONE);
2200     SetFunction(env, typedArrFuncPrototype, "at", BuiltinsTypedArray::At, FunctionLength::ONE);
2201     SetFunction(env, typedArrFuncPrototype, "fill", BuiltinsTypedArray::Fill, FunctionLength::ONE);
2202     SetFunction(env, typedArrFuncPrototype, "filter", BuiltinsTypedArray::Filter, FunctionLength::ONE);
2203     SetFunction(env, typedArrFuncPrototype, "find", BuiltinsTypedArray::Find, FunctionLength::ONE);
2204     SetFunction(env, typedArrFuncPrototype, "findIndex", BuiltinsTypedArray::FindIndex, FunctionLength::ONE);
2205     SetFunction(env, typedArrFuncPrototype, "findLast", BuiltinsTypedArray::FindLast, FunctionLength::ONE);
2206     SetFunction(env, typedArrFuncPrototype, "findLastIndex", BuiltinsTypedArray::FindLastIndex, FunctionLength::ONE);
2207     SetFunction(env, typedArrFuncPrototype, "forEach", BuiltinsTypedArray::ForEach, FunctionLength::ONE);
2208     SetFunction(env, typedArrFuncPrototype, "indexOf", BuiltinsTypedArray::IndexOf, FunctionLength::ONE);
2209     SetFunction(env, typedArrFuncPrototype, "join", BuiltinsTypedArray::Join, FunctionLength::ONE);
2210     SetFunction(env, typedArrFuncPrototype, "keys", BuiltinsTypedArray::Keys, FunctionLength::ZERO);
2211     SetFunction(env, typedArrFuncPrototype, "lastIndexOf", BuiltinsTypedArray::LastIndexOf, FunctionLength::ONE);
2212     SetFunction(env, typedArrFuncPrototype, "map", BuiltinsTypedArray::Map, FunctionLength::ONE);
2213     SetFunction(env, typedArrFuncPrototype, "reduce", BuiltinsTypedArray::Reduce, FunctionLength::ONE);
2214     SetFunction(env, typedArrFuncPrototype, "reduceRight", BuiltinsTypedArray::ReduceRight, FunctionLength::ONE);
2215     SetFunction(env, typedArrFuncPrototype, "reverse", BuiltinsTypedArray::Reverse, FunctionLength::ZERO);
2216     SetFunction(env, typedArrFuncPrototype, "set", BuiltinsTypedArray::Set, FunctionLength::ONE);
2217     SetFunction(env, typedArrFuncPrototype, "slice", BuiltinsTypedArray::Slice, FunctionLength::TWO);
2218     SetFunction(env, typedArrFuncPrototype, "some", BuiltinsTypedArray::Some, FunctionLength::ONE);
2219     SetFunction(env, typedArrFuncPrototype, "sort", BuiltinsTypedArray::Sort, FunctionLength::ONE);
2220     SetFunction(env, typedArrFuncPrototype, "toSorted", BuiltinsTypedArray::ToSorted, FunctionLength::ONE);
2221     SetFunction(env, typedArrFuncPrototype, "subarray", BuiltinsTypedArray::Subarray, FunctionLength::TWO);
2222     SetFunction(env, typedArrFuncPrototype, thread_->GlobalConstants()->GetHandledToLocaleStringString(),
2223                 BuiltinsTypedArray::ToLocaleString, FunctionLength::ZERO);
2224     SetFunction(env, typedArrFuncPrototype, "values", BuiltinsTypedArray::Values, FunctionLength::ZERO);
2225     SetFunction(env, typedArrFuncPrototype, "with", BuiltinsTypedArray::With, FunctionLength::TWO);
2226     SetFunction(env, typedArrFuncPrototype, "includes", BuiltinsTypedArray::Includes, FunctionLength::ONE);
2227     SetFunction(env, typedArrFuncPrototype, "toReversed", BuiltinsTypedArray::ToReversed, FunctionLength::ZERO);
2228 
2229     JSHandle<JSTaggedValue> bufferGetter =
2230         CreateGetter(env, BuiltinsTypedArray::GetBuffer, "buffer", FunctionLength::ZERO);
2231     JSHandle<JSTaggedValue> bufferKey(factory_->NewFromASCII("buffer"));
2232     SetGetter(typedArrFuncPrototype, bufferKey, bufferGetter);
2233 
2234     JSHandle<JSTaggedValue> byteLengthGetter =
2235         CreateGetter(env, BuiltinsTypedArray::GetByteLength, "byteLength", FunctionLength::ZERO);
2236     JSHandle<JSTaggedValue> byteLengthKey(factory_->NewFromASCII("byteLength"));
2237     SetGetter(typedArrFuncPrototype, byteLengthKey, byteLengthGetter);
2238 
2239     JSHandle<JSTaggedValue> byteOffsetGetter =
2240         CreateGetter(env, BuiltinsTypedArray::GetByteOffset, "byteOffset", FunctionLength::ZERO);
2241     JSHandle<JSTaggedValue> byteOffsetKey(factory_->NewFromASCII("byteOffset"));
2242     SetGetter(typedArrFuncPrototype, byteOffsetKey, byteOffsetGetter);
2243 
2244     JSHandle<JSTaggedValue> lengthGetter =
2245         CreateGetter(env, BuiltinsTypedArray::GetLength, "length", FunctionLength::ZERO);
2246     JSHandle<JSTaggedValue> lengthKey(factory_->NewFromASCII("length"));
2247     SetGetter(typedArrFuncPrototype, lengthKey, lengthGetter);
2248 
2249     // %TypedArray%.prototype.toString()
2250     JSHandle<JSTaggedValue> arrFuncPrototype = env->GetArrayPrototype();
2251     JSHandle<JSTaggedValue> toStringFunc =
2252         JSObject::GetMethod(thread_, arrFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString());
2253     RETURN_IF_ABRUPT_COMPLETION(thread_);
2254     PropertyDescriptor toStringDesc(thread_, toStringFunc, true, false, true);
2255     JSObject::DefineOwnProperty(thread_, typedArrFuncPrototype, thread_->GlobalConstants()->GetHandledToStringString(),
2256                                 toStringDesc);
2257 
2258     // %TypedArray%.prototype [ @@iterator ] ( )
2259     JSHandle<JSTaggedValue> values(factory_->NewFromASCII("values"));
2260     JSHandle<JSTaggedValue> iteratorSymbol = env->GetIteratorSymbol();
2261     JSHandle<JSTaggedValue> valuesFunc =
2262         JSObject::GetMethod(thread_, JSHandle<JSTaggedValue>::Cast(typedArrFuncPrototype), values);
2263     RETURN_IF_ABRUPT_COMPLETION(thread_);
2264     PropertyDescriptor iteartorDesc(thread_, valuesFunc, true, false, true);
2265     JSObject::DefineOwnProperty(thread_, typedArrFuncPrototype, iteratorSymbol, iteartorDesc);
2266 
2267     // 22.2.3.31 get %TypedArray%.prototype [ @@toStringTag ]
2268     JSHandle<JSTaggedValue> toStringTagSymbol = env->GetToStringTagSymbol();
2269     JSHandle<JSTaggedValue> toStringTagGetter =
2270         CreateGetter(env, BuiltinsTypedArray::ToStringTag, "[Symbol.toStringTag]", FunctionLength::ZERO);
2271     SetGetter(typedArrFuncPrototype, toStringTagSymbol, toStringTagGetter);
2272 
2273     // TypedArray method
2274     SetFunction(env, typedArrayFunction, "from", BuiltinsTypedArray::From, FunctionLength::ONE);
2275     SetFunction(env, typedArrayFunction, "of", BuiltinsTypedArray::Of, FunctionLength::ZERO);
2276 
2277     // 22.2.2.4 get %TypedArray% [ @@species ]
2278     JSHandle<JSTaggedValue> speciesSymbol = env->GetSpeciesSymbol();
2279     JSHandle<JSTaggedValue> speciesGetter =
2280         CreateGetter(env, BuiltinsTypedArray::Species, "[Symbol.species]", FunctionLength::ZERO);
2281     SetGetter(JSHandle<JSObject>(typedArrayFunction), speciesSymbol, speciesGetter);
2282 
2283     env->SetTypedArrayFunction(thread_, typedArrayFunction.GetTaggedValue());
2284     env->SetTypedArrayPrototype(thread_, typedArrFuncPrototype);
2285 
2286     JSHandle<JSHClass> specificTypedArrayFuncClass =
2287         factory_->NewEcmaHClass(JSFunction::SIZE, JSType::JS_FUNCTION, env->GetTypedArrayFunction());
2288     specificTypedArrayFuncClass->SetConstructor(true);
2289     env->SetSpecificTypedArrayFunctionClass(thread_, specificTypedArrayFuncClass);
2290 
2291     InitializeInt8Array(env, typedArrFuncInstanceHClass);
2292     InitializeUint8Array(env, typedArrFuncInstanceHClass);
2293     InitializeUint8ClampedArray(env, typedArrFuncInstanceHClass);
2294     InitializeInt16Array(env, typedArrFuncInstanceHClass);
2295     InitializeUint16Array(env, typedArrFuncInstanceHClass);
2296     InitializeInt32Array(env, typedArrFuncInstanceHClass);
2297     InitializeUint32Array(env, typedArrFuncInstanceHClass);
2298     InitializeFloat32Array(env, typedArrFuncInstanceHClass);
2299     InitializeFloat64Array(env, typedArrFuncInstanceHClass);
2300     InitializeBigInt64Array(env, typedArrFuncInstanceHClass);
2301     InitializeBigUint64Array(env, typedArrFuncInstanceHClass);
2302 }
2303 
LazyInitializeTypedArray(const JSHandle<GlobalEnv> & env) const2304 void Builtins::LazyInitializeTypedArray(const JSHandle<GlobalEnv> &env) const
2305 {
2306     [[maybe_unused]] EcmaHandleScope scope(thread_);
2307     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
2308     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("TypedArray"));
2309     auto accessor = factory_->NewInternalAccessor(nullptr,
2310         reinterpret_cast<void *>(BuiltinsLazyCallback::TypedArray));
2311     SetLazyAccessor(globalObject, key, accessor);
2312     env->SetTypedArrayFunction(thread_, accessor);
2313     env->SetTypedArrayPrototype(thread_, accessor);
2314     env->SetSpecificTypedArrayFunctionClass(thread_, accessor);
2315     LazyInitializeInt8Array(env);
2316     LazyInitializeUint8Array(env);
2317     LazyInitializeUint8ClampedArray(env);
2318     LazyInitializeInt16Array(env);
2319     LazyInitializeUint16Array(env);
2320     LazyInitializeInt32Array(env);
2321     LazyInitializeUint32Array(env);
2322     LazyInitializeFloat32Array(env);
2323     LazyInitializeFloat64Array(env);
2324     LazyInitializeBigInt64Array(env);
2325     LazyInitializeBigUint64Array(env);
2326 }
2327 
InitializeInt8Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2328 void Builtins::InitializeInt8Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2329 {
2330     [[maybe_unused]] EcmaHandleScope scope(thread_);
2331     // Int8Array.prototype
2332     JSHandle<JSObject> int8ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2333     JSHandle<JSTaggedValue> int8ArrFuncPrototypeValue(int8ArrFuncPrototype);
2334 
2335     // Int8Array.prototype_or_hclass
2336     JSHandle<JSHClass> int8ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2337         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_INT8_ARRAY, int8ArrFuncPrototypeValue);
2338 
2339     // Int8Array = new Function()
2340     JSHandle<JSFunction> int8ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2341         env, reinterpret_cast<void *>(BuiltinsTypedArray::Int8ArrayConstructor));
2342     InitializeCtor(env, int8ArrFuncPrototype, int8ArrayFunction, "Int8Array", FunctionLength::THREE);
2343 
2344     int8ArrayFunction->SetProtoOrHClass(thread_, int8ArrFuncInstanceHClass.GetTaggedValue());
2345 
2346     constexpr int bytesPerElement = 1;
2347     SetConstant(int8ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2348     SetConstant(JSHandle<JSObject>(int8ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2349     env->SetInt8ArrayFunction(thread_, int8ArrayFunction);
2350 }
2351 
InitializeUint8Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2352 void Builtins::InitializeUint8Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2353 {
2354     [[maybe_unused]] EcmaHandleScope scope(thread_);
2355     // Uint8Array.prototype
2356     JSHandle<JSObject> uint8ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2357     JSHandle<JSTaggedValue> uint8ArrFuncPrototypeValue(uint8ArrFuncPrototype);
2358 
2359     // Uint8Array.prototype_or_hclass
2360     JSHandle<JSHClass> uint8ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2361         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_UINT8_ARRAY, uint8ArrFuncPrototypeValue);
2362 
2363     // Uint8Array = new Function()
2364     JSHandle<JSFunction> uint8ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2365         env, reinterpret_cast<void *>(BuiltinsTypedArray::Uint8ArrayConstructor));
2366     InitializeCtor(env, uint8ArrFuncPrototype, uint8ArrayFunction, "Uint8Array", FunctionLength::THREE);
2367 
2368     uint8ArrayFunction->SetProtoOrHClass(thread_, uint8ArrFuncInstanceHClass.GetTaggedValue());
2369 
2370     constexpr int bytesPerElement = 1;
2371     SetConstant(uint8ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2372     SetConstant(JSHandle<JSObject>(uint8ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2373     env->SetUint8ArrayFunction(thread_, uint8ArrayFunction);
2374 }
2375 
2376 #define TYPED_ARRAY_LAZY_INITIALIZE(type)                                                                             \
2377     void Builtins::LazyInitialize##type(const JSHandle<GlobalEnv> &env) const                                         \
2378     {                                                                                                                 \
2379          [[maybe_unused]] EcmaHandleScope scope(thread_);                                                             \
2380         JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());                                             \
2381         JSHandle<JSTaggedValue> key(factory_->NewFromUtf8(#type));                                                    \
2382         auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::type)); \
2383         SetLazyAccessor(globalObject, key, accessor);                                                                 \
2384         env->Set##type##Function(thread_, accessor);                                                                  \
2385     }
2386 
ITERATE_TYPED_ARRAY(TYPED_ARRAY_LAZY_INITIALIZE)2387 ITERATE_TYPED_ARRAY(TYPED_ARRAY_LAZY_INITIALIZE)
2388 #undef TYPED_ARRAY_LAZY_INITIALIZE
2389 
2390 void Builtins::InitializeUint8ClampedArray(const JSHandle<GlobalEnv> &env,
2391                                            const JSHandle<JSHClass> &objFuncClass) const
2392 {
2393     [[maybe_unused]] EcmaHandleScope scope(thread_);
2394     // Uint8ClampedArray.prototype
2395     JSHandle<JSObject> uint8ClampedArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2396     JSHandle<JSTaggedValue> uint8ClampedArrFuncPrototypeValue(uint8ClampedArrFuncPrototype);
2397 
2398     // Uint8ClampedArray.prototype_or_hclass
2399     JSHandle<JSHClass> uint8ClampedArrFuncInstanceHClass =
2400         factory_->NewEcmaHClass(panda::ecmascript::JSTypedArray::SIZE, JSType::JS_UINT8_CLAMPED_ARRAY,
2401                                   uint8ClampedArrFuncPrototypeValue);
2402 
2403     // Uint8ClampedArray = new Function()
2404     JSHandle<JSFunction> uint8ClampedArrayFunction = factory_->NewSpecificTypedArrayFunction(
2405         env, reinterpret_cast<void *>(BuiltinsTypedArray::Uint8ClampedArrayConstructor));
2406     InitializeCtor(env, uint8ClampedArrFuncPrototype, uint8ClampedArrayFunction, "Uint8ClampedArray",
2407                    FunctionLength::THREE);
2408 
2409     uint8ClampedArrayFunction->SetProtoOrHClass(thread_, uint8ClampedArrFuncInstanceHClass.GetTaggedValue());
2410 
2411     constexpr int bytesPerElement = 1;
2412     SetConstant(uint8ClampedArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2413     SetConstant(JSHandle<JSObject>(uint8ClampedArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2414     env->SetUint8ClampedArrayFunction(thread_, uint8ClampedArrayFunction);
2415 }
2416 
InitializeInt16Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2417 void Builtins::InitializeInt16Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2418 {
2419     [[maybe_unused]] EcmaHandleScope scope(thread_);
2420     // Int16Array.prototype
2421     JSHandle<JSObject> int16ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2422     JSHandle<JSTaggedValue> int16ArrFuncPrototypeValue(int16ArrFuncPrototype);
2423 
2424     // Int16Array.prototype_or_hclass
2425     JSHandle<JSHClass> int16ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2426         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_INT16_ARRAY, int16ArrFuncPrototypeValue);
2427 
2428     // Int16Array = new Function()
2429     JSHandle<JSFunction> int16ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2430         env, reinterpret_cast<void *>(BuiltinsTypedArray::Int16ArrayConstructor));
2431     InitializeCtor(env, int16ArrFuncPrototype, int16ArrayFunction, "Int16Array", FunctionLength::THREE);
2432 
2433     int16ArrayFunction->SetProtoOrHClass(thread_, int16ArrFuncInstanceHClass.GetTaggedValue());
2434 
2435     constexpr int bytesPerElement = 2;
2436     SetConstant(int16ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2437     SetConstant(JSHandle<JSObject>(int16ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2438     env->SetInt16ArrayFunction(thread_, int16ArrayFunction);
2439 }
2440 
InitializeUint16Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2441 void Builtins::InitializeUint16Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2442 {
2443     [[maybe_unused]] EcmaHandleScope scope(thread_);
2444     // Uint16Array.prototype
2445     JSHandle<JSObject> uint16ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2446     JSHandle<JSTaggedValue> uint16ArrFuncPrototypeValue(uint16ArrFuncPrototype);
2447 
2448     // Uint16Array.prototype_or_hclass
2449     JSHandle<JSHClass> uint16ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2450         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_UINT16_ARRAY, uint16ArrFuncPrototypeValue);
2451 
2452     // Uint16Array = new Function()
2453     JSHandle<JSFunction> uint16ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2454         env, reinterpret_cast<void *>(BuiltinsTypedArray::Uint16ArrayConstructor));
2455     InitializeCtor(env, uint16ArrFuncPrototype, uint16ArrayFunction, "Uint16Array", FunctionLength::THREE);
2456 
2457     uint16ArrayFunction->SetProtoOrHClass(thread_, uint16ArrFuncInstanceHClass.GetTaggedValue());
2458 
2459     constexpr int bytesPerElement = 2;
2460     SetConstant(uint16ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2461     SetConstant(JSHandle<JSObject>(uint16ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2462     env->SetUint16ArrayFunction(thread_, uint16ArrayFunction);
2463 }
2464 
InitializeInt32Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2465 void Builtins::InitializeInt32Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2466 {
2467     [[maybe_unused]] EcmaHandleScope scope(thread_);
2468     // Int32Array.prototype
2469     JSHandle<JSObject> int32ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2470     JSHandle<JSTaggedValue> int32ArrFuncPrototypeValue(int32ArrFuncPrototype);
2471 
2472     // Int32Array.prototype_or_hclass
2473     JSHandle<JSHClass> int32ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2474         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_INT32_ARRAY, int32ArrFuncPrototypeValue);
2475 
2476     // Int32Array = new Function()
2477     JSHandle<JSFunction> int32ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2478         env, reinterpret_cast<void *>(BuiltinsTypedArray::Int32ArrayConstructor));
2479     InitializeCtor(env, int32ArrFuncPrototype, int32ArrayFunction, "Int32Array", FunctionLength::THREE);
2480 
2481     int32ArrayFunction->SetProtoOrHClass(thread_, int32ArrFuncInstanceHClass.GetTaggedValue());
2482 
2483     constexpr int bytesPerElement = 4;
2484     SetConstant(int32ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2485     SetConstant(JSHandle<JSObject>(int32ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2486     env->SetInt32ArrayFunction(thread_, int32ArrayFunction);
2487 }
2488 
InitializeUint32Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2489 void Builtins::InitializeUint32Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2490 {
2491     [[maybe_unused]] EcmaHandleScope scope(thread_);
2492     // Uint32Array.prototype
2493     JSHandle<JSObject> uint32ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2494     JSHandle<JSTaggedValue> uint32ArrFuncPrototypeValue(uint32ArrFuncPrototype);
2495 
2496     // Uint32Array.prototype_or_hclass
2497     JSHandle<JSHClass> uint32ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2498         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_UINT32_ARRAY, uint32ArrFuncPrototypeValue);
2499 
2500     // Uint32Array = new Function()
2501     JSHandle<JSFunction> uint32ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2502         env, reinterpret_cast<void *>(BuiltinsTypedArray::Uint32ArrayConstructor));
2503     InitializeCtor(env, uint32ArrFuncPrototype, uint32ArrayFunction, "Uint32Array", FunctionLength::THREE);
2504 
2505     uint32ArrayFunction->SetProtoOrHClass(thread_, uint32ArrFuncInstanceHClass.GetTaggedValue());
2506 
2507     constexpr int bytesPerElement = 4;
2508     SetConstant(uint32ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2509     SetConstant(JSHandle<JSObject>(uint32ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2510     env->SetUint32ArrayFunction(thread_, uint32ArrayFunction);
2511 }
2512 
InitializeFloat32Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2513 void Builtins::InitializeFloat32Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2514 {
2515     [[maybe_unused]] EcmaHandleScope scope(thread_);
2516     // Float32Array.prototype
2517     JSHandle<JSObject> float32ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2518     JSHandle<JSTaggedValue> float32ArrFuncPrototypeValue(float32ArrFuncPrototype);
2519 
2520     // Float32Array.prototype_or_hclass
2521     JSHandle<JSHClass> float32ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2522         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_FLOAT32_ARRAY, float32ArrFuncPrototypeValue);
2523 
2524     // Float32Array = new Function()
2525     JSHandle<JSFunction> float32ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2526         env, reinterpret_cast<void *>(BuiltinsTypedArray::Float32ArrayConstructor));
2527     InitializeCtor(env, float32ArrFuncPrototype, float32ArrayFunction, "Float32Array", FunctionLength::THREE);
2528 
2529     float32ArrayFunction->SetProtoOrHClass(thread_, float32ArrFuncInstanceHClass.GetTaggedValue());
2530 
2531     constexpr int bytesPerElement = 4;
2532     SetConstant(float32ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2533     SetConstant(JSHandle<JSObject>(float32ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2534     env->SetFloat32ArrayFunction(thread_, float32ArrayFunction);
2535 }
2536 
InitializeFloat64Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2537 void Builtins::InitializeFloat64Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2538 {
2539     [[maybe_unused]] EcmaHandleScope scope(thread_);
2540     // Float64Array.prototype
2541     JSHandle<JSObject> float64ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2542     JSHandle<JSTaggedValue> float64ArrFuncPrototypeValue(float64ArrFuncPrototype);
2543 
2544     // Float64Array.prototype_or_hclass
2545     JSHandle<JSHClass> float64ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2546         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_FLOAT64_ARRAY, float64ArrFuncPrototypeValue);
2547 
2548     // Float64Array = new Function()
2549     JSHandle<JSFunction> float64ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2550         env, reinterpret_cast<void *>(BuiltinsTypedArray::Float64ArrayConstructor));
2551     InitializeCtor(env, float64ArrFuncPrototype, float64ArrayFunction, "Float64Array", FunctionLength::THREE);
2552 
2553     float64ArrayFunction->SetProtoOrHClass(thread_, float64ArrFuncInstanceHClass.GetTaggedValue());
2554 
2555     constexpr int bytesPerElement = 8;
2556     SetConstant(float64ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2557     SetConstant(JSHandle<JSObject>(float64ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2558     env->SetFloat64ArrayFunction(thread_, float64ArrayFunction);
2559 }
2560 
InitializeBigInt64Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2561 void Builtins::InitializeBigInt64Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2562 {
2563     [[maybe_unused]] EcmaHandleScope scope(thread_);
2564     // BigInt64Array.prototype
2565     JSHandle<JSObject> bigInt64ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2566     JSHandle<JSTaggedValue> bigInt64ArrFuncPrototypeValue(bigInt64ArrFuncPrototype);
2567 
2568     // BigInt64Array.prototype_or_hclass
2569     JSHandle<JSHClass> bigInt64ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2570         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_BIGINT64_ARRAY, bigInt64ArrFuncPrototypeValue);
2571 
2572     // BigInt64Array = new Function()
2573     JSHandle<JSFunction> bigInt64ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2574         env, reinterpret_cast<void *>(BuiltinsTypedArray::BigInt64ArrayConstructor));
2575     InitializeCtor(env, bigInt64ArrFuncPrototype, bigInt64ArrayFunction, "BigInt64Array", FunctionLength::THREE);
2576 
2577     bigInt64ArrayFunction->SetProtoOrHClass(thread_, bigInt64ArrFuncInstanceHClass.GetTaggedValue());
2578 
2579     constexpr int bytesPerElement = 8;
2580     SetConstant(bigInt64ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2581     SetConstant(JSHandle<JSObject>(bigInt64ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2582     env->SetBigInt64ArrayFunction(thread_, bigInt64ArrayFunction);
2583 }
2584 
InitializeBigUint64Array(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2585 void Builtins::InitializeBigUint64Array(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2586 {
2587     [[maybe_unused]] EcmaHandleScope scope(thread_);
2588     // BigUint64Array.prototype
2589     JSHandle<JSObject> bigUint64ArrFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2590     JSHandle<JSTaggedValue> bigUint64ArrFuncPrototypeValue(bigUint64ArrFuncPrototype);
2591 
2592     // BigUint64Array.prototype_or_hclass
2593     JSHandle<JSHClass> bigUint64ArrFuncInstanceHClass = factory_->NewEcmaHClass(
2594         panda::ecmascript::JSTypedArray::SIZE, JSType::JS_BIGUINT64_ARRAY, bigUint64ArrFuncPrototypeValue);
2595 
2596     // BigUint64Array = new Function()
2597     JSHandle<JSFunction> bigUint64ArrayFunction = factory_->NewSpecificTypedArrayFunction(
2598         env, reinterpret_cast<void *>(BuiltinsTypedArray::BigUint64ArrayConstructor));
2599     InitializeCtor(env, bigUint64ArrFuncPrototype, bigUint64ArrayFunction, "BigUint64Array", FunctionLength::THREE);
2600 
2601     bigUint64ArrayFunction->SetProtoOrHClass(thread_, bigUint64ArrFuncInstanceHClass.GetTaggedValue());
2602 
2603     constexpr int bytesPerElement = 8;
2604     SetConstant(bigUint64ArrFuncPrototype, "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2605     SetConstant(JSHandle<JSObject>(bigUint64ArrayFunction), "BYTES_PER_ELEMENT", JSTaggedValue(bytesPerElement));
2606     env->SetBigUint64ArrayFunction(thread_, bigUint64ArrayFunction);
2607 }
2608 
InitializeArrayBuffer(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2609 void Builtins::InitializeArrayBuffer(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2610 {
2611     [[maybe_unused]] EcmaHandleScope scope(thread_);
2612     // ArrayBuffer.prototype
2613     JSHandle<JSObject> arrayBufferFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2614     JSHandle<JSTaggedValue> arrayBufferFuncPrototypeValue(arrayBufferFuncPrototype);
2615 
2616     //  ArrayBuffer.prototype_or_hclass
2617     JSHandle<JSHClass> arrayBufferFuncInstanceHClass =
2618         factory_->NewEcmaHClass(JSArrayBuffer::SIZE, JSType::JS_ARRAY_BUFFER, arrayBufferFuncPrototypeValue);
2619 
2620     // ArrayBuffer = new Function()
2621     JSHandle<JSObject> arrayBufferFunction(NewBuiltinConstructor(
2622         env, arrayBufferFuncPrototype, ArrayBuffer::ArrayBufferConstructor, "ArrayBuffer", FunctionLength::ONE));
2623 
2624     JSHandle<JSFunction>(arrayBufferFunction)
2625         ->SetFunctionPrototype(thread_, arrayBufferFuncInstanceHClass.GetTaggedValue());
2626 
2627     // ArrayBuffer prototype method
2628     SetFunction(env, arrayBufferFuncPrototype, "slice", ArrayBuffer::Slice, FunctionLength::TWO);
2629 
2630     // ArrayBuffer method
2631     SetFunction(env, arrayBufferFunction, "isView", ArrayBuffer::IsView, FunctionLength::ONE);
2632 
2633     // 24.1.3.3 get ArrayBuffer[@@species]
2634     JSHandle<JSTaggedValue> speciesSymbol = env->GetSpeciesSymbol();
2635     JSHandle<JSTaggedValue> speciesGetter =
2636         CreateGetter(env, ArrayBuffer::Species, "[Symbol.species]", FunctionLength::ZERO);
2637     SetGetter(JSHandle<JSObject>(arrayBufferFunction), speciesSymbol, speciesGetter);
2638 
2639     // 24.1.4.1 get ArrayBuffer.prototype.byteLength
2640     JSHandle<JSTaggedValue> lengthGetter =
2641         CreateGetter(env, ArrayBuffer::GetByteLength, "byteLength", FunctionLength::ZERO);
2642     JSHandle<JSTaggedValue> lengthKey(factory_->NewFromASCII("byteLength"));
2643     SetGetter(arrayBufferFuncPrototype, lengthKey, lengthGetter);
2644 
2645     // 24.1.4.4 ArrayBuffer.prototype[@@toStringTag]
2646     SetStringTagSymbol(env, arrayBufferFuncPrototype, "ArrayBuffer");
2647 
2648     env->SetArrayBufferFunction(thread_, arrayBufferFunction.GetTaggedValue());
2649 }
2650 
LazyInitializeArrayBuffer(const JSHandle<GlobalEnv> & env) const2651 void Builtins::LazyInitializeArrayBuffer(const JSHandle<GlobalEnv> &env) const
2652 {
2653     [[maybe_unused]] EcmaHandleScope scope(thread_);
2654     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
2655     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("ArrayBuffer"));
2656     auto accessor = factory_->NewInternalAccessor(nullptr,
2657         reinterpret_cast<void *>(BuiltinsLazyCallback::ArrayBuffer));
2658     SetLazyAccessor(globalObject, key, accessor);
2659     env->SetArrayBufferFunction(thread_, accessor);
2660 }
2661 
InitializeReflect(const JSHandle<GlobalEnv> & env,const JSHandle<JSTaggedValue> & objFuncPrototypeVal) const2662 void Builtins::InitializeReflect(const JSHandle<GlobalEnv> &env,
2663                                  const JSHandle<JSTaggedValue> &objFuncPrototypeVal) const
2664 {
2665     [[maybe_unused]] EcmaHandleScope scope(thread_);
2666     JSHandle<JSHClass> reflectHClass =
2667         factory_->NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, objFuncPrototypeVal);
2668     JSHandle<JSObject> reflectObject = factory_->NewJSObjectWithInit(reflectHClass);
2669 
2670     SetFunction(env, reflectObject, "apply", Reflect::ReflectApply, FunctionLength::THREE);
2671     SetFunction(env, reflectObject, "construct", Reflect::ReflectConstruct, FunctionLength::TWO);
2672     SetFunction(env, reflectObject, "defineProperty", Reflect::ReflectDefineProperty, FunctionLength::THREE);
2673     SetFunction(env, reflectObject, "deleteProperty", Reflect::ReflectDeleteProperty, FunctionLength::TWO);
2674     SetFunction(env, reflectObject, "get", Reflect::ReflectGet, FunctionLength::TWO);
2675     SetFunction(env, reflectObject, "getOwnPropertyDescriptor", Reflect::ReflectGetOwnPropertyDescriptor,
2676                 FunctionLength::TWO);
2677     SetFunction(env, reflectObject, "getPrototypeOf", Reflect::ReflectGetPrototypeOf, FunctionLength::ONE);
2678     SetFunction(env, reflectObject, "has", Reflect::ReflectHas, FunctionLength::TWO);
2679     SetFunction(env, reflectObject, "isExtensible", Reflect::ReflectIsExtensible, FunctionLength::ONE);
2680     SetFunction(env, reflectObject, "ownKeys", Reflect::ReflectOwnKeys, FunctionLength::ONE);
2681     SetFunction(env, reflectObject, "preventExtensions", Reflect::ReflectPreventExtensions, FunctionLength::ONE);
2682     SetFunction(env, reflectObject, "set", Reflect::ReflectSet, FunctionLength::THREE);
2683     SetFunction(env, reflectObject, "setPrototypeOf", Reflect::ReflectSetPrototypeOf, FunctionLength::TWO);
2684 
2685     JSHandle<JSTaggedValue> reflectString(factory_->NewFromASCII("Reflect"));
2686     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
2687     PropertyDescriptor reflectDesc(thread_, JSHandle<JSTaggedValue>::Cast(reflectObject), true, false, true);
2688     JSObject::DefineOwnProperty(thread_, globalObject, reflectString, reflectDesc);
2689 
2690     // @@ToStringTag
2691     SetStringTagSymbol(env, reflectObject, "Reflect");
2692 
2693     env->SetReflectFunction(thread_, reflectObject.GetTaggedValue());
2694 }
2695 
InitializeSharedArrayBuffer(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2696 void Builtins::InitializeSharedArrayBuffer(const JSHandle<GlobalEnv> &env,
2697                                            const JSHandle<JSHClass> &objFuncClass) const
2698 {
2699     [[maybe_unused]] EcmaHandleScope scope(thread_);
2700     // SharedArrayBuffer.prototype
2701     JSHandle<JSObject> sharedArrayBufferFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2702     JSHandle<JSTaggedValue> sharedArrayBufferFuncPrototypeValue(sharedArrayBufferFuncPrototype);
2703 
2704     //  SharedArrayBuffer.prototype_or_hclass
2705     JSHandle<JSHClass> sharedArrayBufferFuncInstanceHClass =
2706         factory_->NewEcmaHClass(
2707             JSArrayBuffer::SIZE, JSType::JS_SHARED_ARRAY_BUFFER, sharedArrayBufferFuncPrototypeValue);
2708 
2709     // SharedArrayBuffer = new Function()
2710     JSHandle<JSObject> SharedArrayBufferFunction(NewBuiltinConstructor(env, sharedArrayBufferFuncPrototype,
2711         SharedArrayBuffer::SharedArrayBufferConstructor, "SharedArrayBuffer", FunctionLength::ONE));
2712 
2713     JSHandle<JSFunction>(SharedArrayBufferFunction)
2714         ->SetFunctionPrototype(thread_, sharedArrayBufferFuncInstanceHClass.GetTaggedValue());
2715 
2716     // SharedArrayBuffer prototype method
2717     SetFunction(env, sharedArrayBufferFuncPrototype, "slice", SharedArrayBuffer::Slice, FunctionLength::TWO);
2718 
2719     // SharedArrayBuffer method
2720     SetFunction(env, SharedArrayBufferFunction,
2721                 "IsSharedArrayBuffer", SharedArrayBuffer::IsSharedArrayBuffer, FunctionLength::ONE);
2722 
2723     // 25.2.3.2 get SharedArrayBuffer [ @@species ]
2724     JSHandle<JSTaggedValue> speciesSymbol = env->GetSpeciesSymbol();
2725     JSHandle<JSTaggedValue> speciesGetter =
2726         CreateGetter(env, SharedArrayBuffer::Species, "[Symbol.species]", FunctionLength::ZERO);
2727     SetGetter(JSHandle<JSObject>(SharedArrayBufferFunction), speciesSymbol, speciesGetter);
2728 
2729     // 25.2.4.1 get SharedArrayBuffer.prototype.byteLength
2730     JSHandle<JSTaggedValue> lengthGetter =
2731         CreateGetter(env, SharedArrayBuffer::GetByteLength, "byteLength", FunctionLength::ZERO);
2732     JSHandle<JSTaggedValue> lengthKey(factory_->NewFromASCII("byteLength"));
2733     SetGetter(sharedArrayBufferFuncPrototype, lengthKey, lengthGetter);
2734 
2735     // 25.2.4.4 SharedArrayBuffer.prototype [ @@toStringTag ]
2736     SetStringTagSymbol(env, sharedArrayBufferFuncPrototype, "SharedArrayBuffer");
2737 
2738     env->SetSharedArrayBufferFunction(thread_, SharedArrayBufferFunction.GetTaggedValue());
2739 }
2740 
LazyInitializeSharedArrayBuffer(const JSHandle<GlobalEnv> & env) const2741 void Builtins::LazyInitializeSharedArrayBuffer(const JSHandle<GlobalEnv> &env) const
2742 {
2743     [[maybe_unused]] EcmaHandleScope scope(thread_);
2744     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
2745     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("SharedArrayBuffer"));
2746     auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::SharedArrayBuffer));
2747     SetLazyAccessor(globalObject, key, accessor);
2748     env->SetSharedArrayBufferFunction(thread_, accessor);
2749 }
2750 
InitializePromise(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & promiseFuncClass)2751 void Builtins::InitializePromise(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &promiseFuncClass)
2752 {
2753     [[maybe_unused]] EcmaHandleScope scope(thread_);
2754     // Promise.prototype
2755     JSHandle<JSObject> promiseFuncPrototype = factory_->NewJSObjectWithInit(promiseFuncClass);
2756     JSHandle<JSTaggedValue> promiseFuncPrototypeValue(promiseFuncPrototype);
2757     // Promise.prototype_or_hclass
2758     JSHandle<JSHClass> promiseFuncInstanceHClass =
2759         factory_->NewEcmaHClass(JSPromise::SIZE, JSType::JS_PROMISE, promiseFuncPrototypeValue);
2760     // Promise() = new Function()
2761     JSHandle<JSObject> promiseFunction(
2762         NewBuiltinConstructor(env, promiseFuncPrototype, Promise::PromiseConstructor, "Promise", FunctionLength::ONE));
2763     JSHandle<JSFunction>(promiseFunction)->SetFunctionPrototype(thread_, promiseFuncInstanceHClass.GetTaggedValue());
2764 
2765     // Promise method
2766     SetFunction(env, promiseFunction, "all", Promise::All, FunctionLength::ONE);
2767     SetFunction(env, promiseFunction, "race", Promise::Race, FunctionLength::ONE);
2768     SetFunction(env, promiseFunction, "resolve", Promise::Resolve, FunctionLength::ONE);
2769     SetFunction(env, promiseFunction, "reject", Promise::Reject, FunctionLength::ONE);
2770     SetFunction(env, promiseFunction, "any", Promise::Any, FunctionLength::ONE);
2771     SetFunction(env, promiseFunction, "allSettled", Promise::AllSettled, FunctionLength::ONE);
2772 
2773     // promise.prototype method
2774     SetFunction(env, promiseFuncPrototype, "catch", Promise::Catch, FunctionLength::ONE);
2775     SetFunction(env, promiseFuncPrototype, "then", Promise::Then, FunctionLength::TWO);
2776     SetFunction(env, promiseFuncPrototype, "finally", Promise::Finally, FunctionLength::ONE);
2777 
2778     // Promise.prototype [ @@toStringTag ]
2779     SetStringTagSymbol(env, promiseFuncPrototype, "Promise");
2780 
2781     // Set Promise [@@species]
2782     JSHandle<JSTaggedValue> speciesSymbol(env->GetSpeciesSymbol());
2783     JSHandle<JSTaggedValue> speciesGetter =
2784         CreateGetter(env, Promise::GetSpecies, "[Symbol.species]", FunctionLength::ZERO);
2785     SetGetter(promiseFunction, speciesSymbol, speciesGetter);
2786 
2787     env->SetPromiseFunction(thread_, promiseFunction);
2788     InitializeForPromiseFuncClass(env);
2789 }
2790 
2791 
InitializeForPromiseFuncClass(const JSHandle<GlobalEnv> & env)2792 void Builtins::InitializeForPromiseFuncClass(const JSHandle<GlobalEnv> &env)
2793 {
2794     vm_ = thread_->GetEcmaVM();
2795     factory_ = vm_->GetFactory();
2796 
2797     JSHandle<JSHClass> promiseReactionFuncClass = factory_->NewEcmaHClass(
2798         JSPromiseReactionsFunction::SIZE, JSType::JS_PROMISE_REACTIONS_FUNCTION, env->GetFunctionPrototype());
2799     promiseReactionFuncClass->SetCallable(true);
2800     promiseReactionFuncClass->SetExtensible(true);
2801     env->SetPromiseReactionFunctionClass(thread_, promiseReactionFuncClass);
2802 
2803     JSHandle<JSHClass> promiseExecutorFuncClass = factory_->NewEcmaHClass(
2804         JSPromiseExecutorFunction::SIZE, JSType::JS_PROMISE_EXECUTOR_FUNCTION, env->GetFunctionPrototype());
2805     promiseExecutorFuncClass->SetCallable(true);
2806     promiseExecutorFuncClass->SetExtensible(true);
2807     env->SetPromiseExecutorFunctionClass(thread_, promiseExecutorFuncClass);
2808 
2809     JSHandle<JSHClass> promiseAllResolveElementFunctionClass =
2810         factory_->NewEcmaHClass(JSPromiseAllResolveElementFunction::SIZE,
2811                                   JSType::JS_PROMISE_ALL_RESOLVE_ELEMENT_FUNCTION, env->GetFunctionPrototype());
2812     promiseAllResolveElementFunctionClass->SetCallable(true);
2813     promiseAllResolveElementFunctionClass->SetExtensible(true);
2814     env->SetPromiseAllResolveElementFunctionClass(thread_, promiseAllResolveElementFunctionClass);
2815 
2816     JSHandle<JSHClass> promiseAnyRejectElementFunctionClass =
2817         factory_->NewEcmaHClass(JSPromiseAnyRejectElementFunction::SIZE,
2818                                   JSType::JS_PROMISE_ANY_REJECT_ELEMENT_FUNCTION, env->GetFunctionPrototype());
2819     promiseAnyRejectElementFunctionClass->SetCallable(true);
2820     promiseAnyRejectElementFunctionClass->SetExtensible(true);
2821     env->SetPromiseAnyRejectElementFunctionClass(thread_, promiseAnyRejectElementFunctionClass);
2822 
2823     JSHandle<JSHClass> promiseAllSettledElementFunctionClass =
2824         factory_->NewEcmaHClass(JSPromiseAllSettledElementFunction::SIZE,
2825                                   JSType::JS_PROMISE_ALL_SETTLED_ELEMENT_FUNCTION, env->GetFunctionPrototype());
2826     promiseAllSettledElementFunctionClass->SetCallable(true);
2827     promiseAllSettledElementFunctionClass->SetExtensible(true);
2828     env->SetPromiseAllSettledElementFunctionClass(thread_, promiseAllSettledElementFunctionClass);
2829 
2830     JSHandle<JSHClass> promiseFinallyFunctionClass =
2831         factory_->NewEcmaHClass(JSPromiseFinallyFunction::SIZE,
2832                                   JSType::JS_PROMISE_FINALLY_FUNCTION, env->GetFunctionPrototype());
2833     promiseFinallyFunctionClass->SetCallable(true);
2834     promiseFinallyFunctionClass->SetExtensible(true);
2835     env->SetPromiseFinallyFunctionClass(thread_, promiseFinallyFunctionClass);
2836 
2837     JSHandle<JSHClass> promiseValueThunkOrThrowerFunctionClass =
2838         factory_->NewEcmaHClass(JSPromiseValueThunkOrThrowerFunction::SIZE,
2839                                   JSType::JS_PROMISE_VALUE_THUNK_OR_THROWER_FUNCTION, env->GetFunctionPrototype());
2840     promiseValueThunkOrThrowerFunctionClass->SetCallable(true);
2841     promiseValueThunkOrThrowerFunctionClass->SetExtensible(true);
2842     env->SetPromiseValueThunkOrThrowerFunctionClass(thread_, promiseValueThunkOrThrowerFunctionClass);
2843 }
2844 
InitializePromiseJob(const JSHandle<GlobalEnv> & env)2845 void Builtins::InitializePromiseJob(const JSHandle<GlobalEnv> &env)
2846 {
2847     JSHandle<JSTaggedValue> keyString(thread_->GlobalConstants()->GetHandledEmptyString());
2848     auto func = NewFunction(env, keyString, BuiltinsPromiseJob::PromiseReactionJob, FunctionLength::TWO);
2849     env->SetPromiseReactionJob(thread_, func);
2850     func = NewFunction(env, keyString, BuiltinsPromiseJob::PromiseResolveThenableJob, FunctionLength::THREE);
2851     env->SetPromiseResolveThenableJob(thread_, func);
2852     func = NewFunction(env, keyString, BuiltinsPromiseJob::DynamicImportJob, FunctionLength::FOUR);
2853     env->SetDynamicImportJob(thread_, func);
2854 }
2855 
InitializeDataView(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const2856 void Builtins::InitializeDataView(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
2857 {
2858     [[maybe_unused]] EcmaHandleScope scope(thread_);
2859     // ArrayBuffer.prototype
2860     JSHandle<JSObject> dataViewFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
2861     JSHandle<JSTaggedValue> dataViewFuncPrototypeValue(dataViewFuncPrototype);
2862 
2863     //  ArrayBuffer.prototype_or_hclass
2864     JSHandle<JSHClass> dataViewFuncInstanceHClass =
2865         factory_->NewEcmaHClass(JSDataView::SIZE, JSType::JS_DATA_VIEW, dataViewFuncPrototypeValue);
2866 
2867     // ArrayBuffer = new Function()
2868     JSHandle<JSObject> dataViewFunction(NewBuiltinConstructor(env, dataViewFuncPrototype, DataView::DataViewConstructor,
2869                                                               "DataView", FunctionLength::ONE));
2870 
2871     JSHandle<JSFunction>(dataViewFunction)->SetProtoOrHClass(thread_, dataViewFuncInstanceHClass.GetTaggedValue());
2872     // DataView.prototype method
2873     SetFunction(env, dataViewFuncPrototype, "getFloat32", DataView::GetFloat32, FunctionLength::ONE);
2874     SetFunction(env, dataViewFuncPrototype, "getFloat64", DataView::GetFloat64, FunctionLength::ONE);
2875     SetFunction(env, dataViewFuncPrototype, "getInt8", DataView::GetInt8, FunctionLength::ONE);
2876     SetFunction(env, dataViewFuncPrototype, "getInt16", DataView::GetInt16, FunctionLength::ONE);
2877     SetFunction(env, dataViewFuncPrototype, "getInt32", DataView::GetInt32, FunctionLength::ONE);
2878     SetFunction(env, dataViewFuncPrototype, "getUint8", DataView::GetUint8, FunctionLength::ONE);
2879     SetFunction(env, dataViewFuncPrototype, "getUint16", DataView::GetUint16, FunctionLength::ONE);
2880     SetFunction(env, dataViewFuncPrototype, "getUint32", DataView::GetUint32, FunctionLength::ONE);
2881     SetFunction(env, dataViewFuncPrototype, "getBigInt64", DataView::GetBigInt64, FunctionLength::ONE);
2882     SetFunction(env, dataViewFuncPrototype, "getBigUint64", DataView::GetBigUint64, FunctionLength::ONE);
2883     SetFunction(env, dataViewFuncPrototype, "setFloat32", DataView::SetFloat32, FunctionLength::TWO);
2884     SetFunction(env, dataViewFuncPrototype, "setFloat64", DataView::SetFloat64, FunctionLength::TWO);
2885     SetFunction(env, dataViewFuncPrototype, "setInt8", DataView::SetInt8, FunctionLength::TWO);
2886     SetFunction(env, dataViewFuncPrototype, "setInt16", DataView::SetInt16, FunctionLength::TWO);
2887     SetFunction(env, dataViewFuncPrototype, "setInt32", DataView::SetInt32, FunctionLength::TWO);
2888     SetFunction(env, dataViewFuncPrototype, "setUint8", DataView::SetUint8, FunctionLength::TWO);
2889     SetFunction(env, dataViewFuncPrototype, "setUint16", DataView::SetUint16, FunctionLength::TWO);
2890     SetFunction(env, dataViewFuncPrototype, "setUint32", DataView::SetUint32, FunctionLength::TWO);
2891     SetFunction(env, dataViewFuncPrototype, "setBigInt64", DataView::SetBigInt64, FunctionLength::TWO);
2892     SetFunction(env, dataViewFuncPrototype, "setBigUint64", DataView::SetBigUint64, FunctionLength::TWO);
2893 
2894     // 24.2.4.1 get DataView.prototype.buffer
2895     JSHandle<JSTaggedValue> bufferGetter = CreateGetter(env, DataView::GetBuffer, "buffer", FunctionLength::ZERO);
2896     JSHandle<JSTaggedValue> bufferKey(factory_->NewFromASCII("buffer"));
2897     SetGetter(dataViewFuncPrototype, bufferKey, bufferGetter);
2898 
2899     // 24.2.4.2 get DataView.prototype.byteLength
2900     JSHandle<JSTaggedValue> lengthGetter =
2901         CreateGetter(env, DataView::GetByteLength, "byteLength", FunctionLength::ZERO);
2902     JSHandle<JSTaggedValue> lengthKey(factory_->NewFromASCII("byteLength"));
2903     SetGetter(dataViewFuncPrototype, lengthKey, lengthGetter);
2904 
2905     // 24.2.4.3 get DataView.prototype.byteOffset
2906     JSHandle<JSTaggedValue> offsetGetter = CreateGetter(env, DataView::GetOffset, "byteOffset", FunctionLength::ZERO);
2907     JSHandle<JSTaggedValue> offsetKey(factory_->NewFromASCII("byteOffset"));
2908     SetGetter(dataViewFuncPrototype, offsetKey, offsetGetter);
2909 
2910     // 24.2.4.21 DataView.prototype[ @@toStringTag ]
2911     SetStringTagSymbol(env, dataViewFuncPrototype, "DataView");
2912     env->SetDataViewFunction(thread_, dataViewFunction.GetTaggedValue());
2913 }
2914 
LazyInitializeDataView(const JSHandle<GlobalEnv> & env) const2915 void Builtins::LazyInitializeDataView(const JSHandle<GlobalEnv> &env) const
2916 {
2917     [[maybe_unused]] EcmaHandleScope scope(thread_);
2918     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
2919     JSHandle<JSTaggedValue> key(factory_->NewFromUtf8("DataView"));
2920     auto accessor = factory_->NewInternalAccessor(nullptr, reinterpret_cast<void *>(BuiltinsLazyCallback::DataView));
2921     SetLazyAccessor(globalObject, key, accessor);
2922     env->SetDataViewFunction(thread_, accessor);
2923 }
2924 
NewBuiltinConstructor(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & prototype,EcmaEntrypoint ctorFunc,const char * name,int length,kungfu::BuiltinsStubCSigns::ID builtinId) const2925 JSHandle<JSFunction> Builtins::NewBuiltinConstructor(const JSHandle<GlobalEnv> &env,
2926                                                      const JSHandle<JSObject> &prototype, EcmaEntrypoint ctorFunc,
2927                                                      const char *name, int length,
2928                                                      kungfu::BuiltinsStubCSigns::ID builtinId) const
2929 {
2930     JSHandle<JSFunction> ctor =
2931         factory_->NewJSFunction(env, reinterpret_cast<void *>(ctorFunc), FunctionKind::BUILTIN_CONSTRUCTOR, builtinId);
2932     InitializeCtor(env, prototype, ctor, name, length);
2933     return ctor;
2934 }
2935 
NewBuiltinCjsCtor(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & prototype,EcmaEntrypoint ctorFunc,const char * name,int length) const2936 JSHandle<JSFunction> Builtins::NewBuiltinCjsCtor(const JSHandle<GlobalEnv> &env,
2937                                                  const JSHandle<JSObject> &prototype, EcmaEntrypoint ctorFunc,
2938                                                  const char *name, int length) const
2939 {
2940     JSHandle<JSFunction> ctor =
2941         factory_->NewJSFunction(env, reinterpret_cast<void *>(ctorFunc), FunctionKind::BUILTIN_CONSTRUCTOR);
2942 
2943     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
2944     JSFunction::SetFunctionLength(thread_, ctor, JSTaggedValue(length));
2945     JSHandle<JSTaggedValue> nameString(factory_->NewFromUtf8(name));
2946     JSFunction::SetFunctionName(thread_, JSHandle<JSFunctionBase>(ctor), nameString,
2947                                 JSHandle<JSTaggedValue>(thread_, JSTaggedValue::Undefined()));
2948     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
2949     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>::Cast(ctor), true, false, true);
2950     JSObject::DefineOwnProperty(thread_, prototype, constructorKey, descriptor);
2951 
2952     return ctor;
2953 }
2954 
NewFunction(const JSHandle<GlobalEnv> & env,const JSHandle<JSTaggedValue> & key,EcmaEntrypoint func,int length,kungfu::BuiltinsStubCSigns::ID builtinId) const2955 JSHandle<JSFunction> Builtins::NewFunction(const JSHandle<GlobalEnv> &env, const JSHandle<JSTaggedValue> &key,
2956                                            EcmaEntrypoint func, int length,
2957                                            kungfu::BuiltinsStubCSigns::ID builtinId) const
2958 {
2959     JSHandle<JSFunction> function = factory_->NewJSFunction(env, reinterpret_cast<void *>(func),
2960         FunctionKind::NORMAL_FUNCTION, builtinId, MemSpaceType::NON_MOVABLE);
2961     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(length));
2962     JSHandle<JSFunctionBase> baseFunction(function);
2963     JSHandle<JSTaggedValue> handleUndefine(thread_, JSTaggedValue::Undefined());
2964     JSFunction::SetFunctionName(thread_, baseFunction, key, handleUndefine);
2965     if (IS_TYPED_BUILTINS_ID(builtinId)) {
2966         auto globalConst = const_cast<GlobalEnvConstants *>(thread_->GlobalConstants());
2967         globalConst->SetConstant(GET_TYPED_CONSTANT_INDEX(builtinId), function);
2968     }
2969     return function;
2970 }
2971 
SetFunction(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & obj,const char * key,EcmaEntrypoint func,int length,kungfu::BuiltinsStubCSigns::ID builtinId) const2972 void Builtins::SetFunction(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &obj, const char *key,
2973                            EcmaEntrypoint func, int length, kungfu::BuiltinsStubCSigns::ID builtinId) const
2974 {
2975     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
2976     SetFunction(env, obj, keyString, func, length, builtinId);
2977 }
2978 
SetFunction(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & obj,const JSHandle<JSTaggedValue> & key,EcmaEntrypoint func,int length,kungfu::BuiltinsStubCSigns::ID builtinId) const2979 void Builtins::SetFunction(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &obj,
2980                            const JSHandle<JSTaggedValue> &key, EcmaEntrypoint func, int length,
2981                            kungfu::BuiltinsStubCSigns::ID builtinId) const
2982 {
2983     JSHandle<JSFunction> function(NewFunction(env, key, func, length, builtinId));
2984     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>(function), true, false, true);
2985     JSObject::DefineOwnProperty(thread_, obj, key, descriptor);
2986 }
2987 
SetFrozenFunction(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & obj,const char * key,EcmaEntrypoint func,int length) const2988 void Builtins::SetFrozenFunction(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &obj, const char *key,
2989                                  EcmaEntrypoint func, int length) const
2990 {
2991     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
2992     JSHandle<JSFunction> function = NewFunction(env, keyString, func, length);
2993     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>(function), false, false, false);
2994     JSObject::DefineOwnProperty(thread_, obj, keyString, descriptor);
2995 }
2996 
2997 template<int flag>
SetFunctionAtSymbol(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & obj,const JSHandle<JSTaggedValue> & symbol,const char * name,EcmaEntrypoint func,int length) const2998 void Builtins::SetFunctionAtSymbol(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &obj,
2999                                    const JSHandle<JSTaggedValue> &symbol, const char *name, EcmaEntrypoint func,
3000                                    int length) const
3001 {
3002     JSHandle<JSFunction> function = factory_->NewJSFunction(env, reinterpret_cast<void *>(func));
3003     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(length));
3004     JSHandle<JSTaggedValue> nameString(factory_->NewFromUtf8(name));
3005     JSHandle<JSFunctionBase> baseFunction(function);
3006     JSHandle<JSTaggedValue> handleUndefine(thread_, JSTaggedValue::Undefined());
3007     JSFunction::SetFunctionName(thread_, baseFunction, nameString, handleUndefine);
3008     // NOLINTNEXTLINE(readability-braces-around-statements, bugprone-suspicious-semicolon)
3009     if constexpr (flag == JSSymbol::SYMBOL_TO_PRIMITIVE_TYPE) {
3010         PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>::Cast(function), false, false, true);
3011         JSObject::DefineOwnProperty(thread_, obj, symbol, descriptor);
3012         return;
3013     } else if constexpr (flag == JSSymbol::SYMBOL_HAS_INSTANCE_TYPE) {  // NOLINTE(readability-braces-around-statements)
3014         // ecma 19.2.3.6 Function.prototype[@@hasInstance] has the attributes
3015         // { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
3016         PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>::Cast(function), false, false, false);
3017         JSObject::DefineOwnProperty(thread_, obj, symbol, descriptor);
3018         env->SetHasInstanceFunction(thread_, function);
3019         return;
3020     }
3021     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>::Cast(function), true, false, true);
3022     JSObject::DefineOwnProperty(thread_, obj, symbol, descriptor);
3023 }
3024 
SetStringTagSymbol(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & obj,const char * key) const3025 void Builtins::SetStringTagSymbol(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &obj, const char *key) const
3026 {
3027     JSHandle<JSTaggedValue> tag(factory_->NewFromUtf8(key));
3028     JSHandle<JSTaggedValue> symbol = env->GetToStringTagSymbol();
3029     PropertyDescriptor desc(thread_, tag, false, false, true);
3030     JSObject::DefineOwnProperty(thread_, obj, symbol, desc);
3031 }
3032 
CreateGetter(const JSHandle<GlobalEnv> & env,EcmaEntrypoint func,const char * name,int length) const3033 JSHandle<JSTaggedValue> Builtins::CreateGetter(const JSHandle<GlobalEnv> &env, EcmaEntrypoint func, const char *name,
3034                                                int length) const
3035 {
3036     JSHandle<JSFunction> function = factory_->NewJSFunction(env, reinterpret_cast<void *>(func));
3037     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(length));
3038     JSHandle<JSTaggedValue> funcName(factory_->NewFromUtf8(name));
3039     JSHandle<JSTaggedValue> prefix = thread_->GlobalConstants()->GetHandledGetString();
3040     JSFunction::SetFunctionName(thread_, JSHandle<JSFunctionBase>(function), funcName, prefix);
3041     return JSHandle<JSTaggedValue>(function);
3042 }
3043 
CreateSetter(const JSHandle<GlobalEnv> & env,EcmaEntrypoint func,const char * name,int length)3044 JSHandle<JSTaggedValue> Builtins::CreateSetter(const JSHandle<GlobalEnv> &env, EcmaEntrypoint func, const char *name,
3045                                                int length)
3046 {
3047     JSHandle<JSFunction> function = factory_->NewJSFunction(env, reinterpret_cast<void *>(func));
3048     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(length));
3049     JSHandle<JSTaggedValue> funcName(factory_->NewFromUtf8(name));
3050     JSHandle<JSTaggedValue> prefix = thread_->GlobalConstants()->GetHandledSetString();
3051     JSFunction::SetFunctionName(thread_, JSHandle<JSFunctionBase>(function), funcName, prefix);
3052     return JSHandle<JSTaggedValue>(function);
3053 }
3054 
SetConstant(const JSHandle<JSObject> & obj,const char * key,JSTaggedValue value) const3055 void Builtins::SetConstant(const JSHandle<JSObject> &obj, const char *key, JSTaggedValue value) const
3056 {
3057     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
3058     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>(thread_, value), false, false, false);
3059     JSObject::DefineOwnProperty(thread_, obj, keyString, descriptor);
3060 }
3061 
SetConstantObject(const JSHandle<JSObject> & obj,const char * key,JSHandle<JSTaggedValue> & value) const3062 void Builtins::SetConstantObject(const JSHandle<JSObject> &obj, const char *key, JSHandle<JSTaggedValue> &value) const
3063 {
3064     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
3065     PropertyDescriptor descriptor(thread_, value, false, false, false);
3066     JSObject::DefineOwnProperty(thread_, obj, keyString, descriptor);
3067 }
3068 
SetNonConstantObject(const JSHandle<JSObject> & obj,const char * key,JSHandle<JSTaggedValue> & value) const3069 void Builtins::SetNonConstantObject(const JSHandle<JSObject> &obj, const char *key,
3070                                     JSHandle<JSTaggedValue> &value) const
3071 {
3072     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
3073     PropertyDescriptor descriptor(thread_, value, true, true, true);
3074     JSObject::DefineOwnProperty(thread_, obj, keyString, descriptor);
3075 }
3076 
SetGlobalThis(const JSHandle<JSObject> & obj,const char * key,const JSHandle<JSTaggedValue> & globalValue)3077 void Builtins::SetGlobalThis(const JSHandle<JSObject> &obj, const char *key, const JSHandle<JSTaggedValue> &globalValue)
3078 {
3079     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
3080     PropertyDescriptor descriptor(thread_, globalValue, true, false, true);
3081     JSObject::DefineOwnProperty(thread_, obj, keyString, descriptor);
3082 }
3083 
SetAttribute(const JSHandle<JSObject> & obj,const char * key,const char * value) const3084 void Builtins::SetAttribute(const JSHandle<JSObject> &obj, const char *key, const char *value) const
3085 {
3086     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
3087     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>(factory_->NewFromUtf8(value)), true, false, true);
3088     JSObject::DefineOwnProperty(thread_, obj, keyString, descriptor);
3089 }
3090 
SetNoneAttributeProperty(const JSHandle<JSObject> & obj,const char * key,const JSHandle<JSTaggedValue> & value) const3091 void Builtins::SetNoneAttributeProperty(const JSHandle<JSObject> &obj, const char *key,
3092                                         const JSHandle<JSTaggedValue> &value) const
3093 {
3094     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
3095     PropertyDescriptor des(thread_, value, false, false, false);
3096     JSObject::DefineOwnProperty(thread_, obj, keyString, des);
3097 }
3098 
SetFuncToObjAndGlobal(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & globalObject,const JSHandle<JSObject> & obj,const char * key,EcmaEntrypoint func,int length)3099 void Builtins::SetFuncToObjAndGlobal(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &globalObject,
3100                                      const JSHandle<JSObject> &obj, const char *key, EcmaEntrypoint func, int length)
3101 {
3102     JSHandle<JSFunction> function = factory_->NewJSFunction(env, reinterpret_cast<void *>(func));
3103     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(length));
3104     JSHandle<JSTaggedValue> keyString(factory_->NewFromUtf8(key));
3105     JSHandle<JSFunctionBase> baseFunction(function);
3106     JSHandle<JSTaggedValue> handleUndefine(thread_, JSTaggedValue::Undefined());
3107     JSFunction::SetFunctionName(thread_, baseFunction, keyString, handleUndefine);
3108     PropertyDescriptor descriptor(thread_, JSHandle<JSTaggedValue>::Cast(function), true, false, true);
3109     JSObject::DefineOwnProperty(thread_, obj, keyString, descriptor);
3110     JSObject::DefineOwnProperty(thread_, globalObject, keyString, descriptor);
3111 }
3112 
StrictModeForbiddenAccessCallerArguments(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & prototype) const3113 void Builtins::StrictModeForbiddenAccessCallerArguments(const JSHandle<GlobalEnv> &env,
3114                                                         const JSHandle<JSObject> &prototype) const
3115 {
3116     JSHandle<JSFunction> function =
3117         factory_->NewJSFunction(env, reinterpret_cast<void *>(JSFunction::AccessCallerArgumentsThrowTypeError));
3118 
3119     JSHandle<JSTaggedValue> caller(factory_->NewFromASCII("caller"));
3120     SetAccessor(prototype, caller, JSHandle<JSTaggedValue>::Cast(function), JSHandle<JSTaggedValue>::Cast(function));
3121 
3122     JSHandle<JSTaggedValue> arguments(factory_->NewFromASCII("arguments"));
3123     SetAccessor(prototype, arguments, JSHandle<JSTaggedValue>::Cast(function), JSHandle<JSTaggedValue>::Cast(function));
3124 }
3125 
InitializeGeneratorFunction(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const3126 void Builtins::InitializeGeneratorFunction(const JSHandle<GlobalEnv> &env,
3127                                            const JSHandle<JSHClass> &objFuncClass) const
3128 {
3129     [[maybe_unused]] EcmaHandleScope scope(thread_);
3130     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3131     JSHandle<JSObject> generatorFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
3132     JSHandle<JSTaggedValue> generatorFuncPrototypeValue(generatorFuncPrototype);
3133 
3134     // 26.3.3.1 GeneratorFunction.prototype.constructor
3135     // GeneratorFunction.prototype_or_hclass
3136     JSHandle<JSHClass> generatorFuncInstanceHClass =
3137         factory_->NewEcmaHClass(JSFunction::SIZE, JSType::JS_GENERATOR_FUNCTION, generatorFuncPrototypeValue);
3138     generatorFuncInstanceHClass->SetCallable(true);
3139     generatorFuncInstanceHClass->SetExtensible(true);
3140     // GeneratorFunction = new GeneratorFunction()
3141     JSHandle<JSFunction> generatorFunction =
3142         NewBuiltinConstructor(env, generatorFuncPrototype, GeneratorObject::GeneratorFunctionConstructor,
3143                               "GeneratorFunction", FunctionLength::ONE);
3144     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
3145     PropertyDescriptor generatorDesc(thread_, JSHandle<JSTaggedValue>::Cast(generatorFunction), false, false, true);
3146     JSObject::DefineOwnProperty(thread_, generatorFuncPrototype, constructorKey, generatorDesc);
3147     generatorFunction->SetProtoOrHClass(thread_, generatorFuncInstanceHClass.GetTaggedValue());
3148     env->SetGeneratorFunctionFunction(thread_, generatorFunction);
3149 
3150     // 26.3.3.2 GeneratorFunction.prototype.prototype -> Generator prototype object.
3151     PropertyDescriptor descriptor(thread_, env->GetGeneratorPrototype(), false, false, true);
3152     JSObject::DefineOwnProperty(thread_, generatorFuncPrototype, globalConst->GetHandledPrototypeString(), descriptor);
3153 
3154     // 26.3.3.3 GeneratorFunction.prototype[@@toStringTag]
3155     SetStringTagSymbol(env, generatorFuncPrototype, "GeneratorFunction");
3156 
3157     // GeneratorFunction prototype __proto__ -> Function.
3158     JSObject::SetPrototype(thread_, generatorFuncPrototype, env->GetFunctionPrototype());
3159 
3160     // 26.5.1.1 Generator.prototype.constructor -> %GeneratorFunction.prototype%.
3161     PropertyDescriptor generatorObjDesc(thread_, generatorFuncPrototypeValue, false, false, true);
3162     JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>(env->GetInitialGenerator()),
3163                                 globalConst->GetHandledConstructorString(), generatorObjDesc);
3164 
3165     // Generator instances prototype -> GeneratorFunction.prototype.prototype
3166     PropertyDescriptor generatorObjProtoDesc(thread_, generatorFuncPrototypeValue, true, false, false);
3167     JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>(env->GetInitialGenerator()),
3168                                 globalConst->GetHandledPrototypeString(), generatorObjProtoDesc);
3169 
3170     env->SetGeneratorFunctionPrototype(thread_, generatorFuncPrototype);
3171 }
3172 
InitializeAsyncGeneratorFunction(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const3173 void Builtins::InitializeAsyncGeneratorFunction(const JSHandle<GlobalEnv> &env,
3174                                                 const JSHandle<JSHClass> &objFuncClass) const
3175 {
3176     [[maybe_unused]] EcmaHandleScope scope(thread_);
3177     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3178     JSHandle<JSObject> asyncGeneratorFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
3179     JSHandle<JSTaggedValue> asyncGeneratorFuncPrototypeValue(asyncGeneratorFuncPrototype);
3180      // 27.4.3.1 AsyncGeneratorFunction.prototype.constructor
3181     JSHandle<JSHClass> asyncGeneratorFuncInstanceHClass =
3182         factory_->NewEcmaHClass(JSFunction::SIZE, JSType::JS_ASYNC_GENERATOR_FUNCTION,
3183                                   asyncGeneratorFuncPrototypeValue);
3184     asyncGeneratorFuncInstanceHClass->SetCallable(true);
3185     asyncGeneratorFuncInstanceHClass->SetExtensible(true);
3186     JSHandle<JSFunction> asyncGeneratorFunction =
3187         NewBuiltinConstructor(env, asyncGeneratorFuncPrototype,
3188                               AsyncGeneratorObject::AsyncGeneratorFunctionConstructor, "AsyncGeneratorFunction",
3189                               FunctionLength::ONE);
3190     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
3191     PropertyDescriptor asyncGeneratorDesc(thread_, JSHandle<JSTaggedValue>::Cast(asyncGeneratorFunction),
3192                                           false, false, true);
3193     JSObject::DefineOwnProperty(thread_, asyncGeneratorFuncPrototype, constructorKey, asyncGeneratorDesc);
3194     asyncGeneratorFunction->SetProtoOrHClass(thread_, asyncGeneratorFuncInstanceHClass.GetTaggedValue());
3195     env->SetAsyncGeneratorFunctionFunction(thread_, asyncGeneratorFunction);
3196 
3197     // 27.4.3.2 AsyncGeneratorFunction.prototype.prototype
3198     PropertyDescriptor descriptor(thread_, env->GetAsyncGeneratorPrototype(), false, false, true);
3199     JSObject::DefineOwnProperty(thread_, asyncGeneratorFuncPrototype, globalConst->GetHandledPrototypeString(),
3200                                 descriptor);
3201 
3202     // 27.4.3.3 AsyncGeneratorFunction.prototype [ @@toStringTag ]
3203     SetStringTagSymbol(env, asyncGeneratorFuncPrototype, "AsyncGeneratorFunction");
3204     // AsyncGeneratorFunction prototype __proto__ -> Function.
3205     JSObject::SetPrototype(thread_, asyncGeneratorFuncPrototype, env->GetFunctionPrototype());
3206 
3207     PropertyDescriptor asyncGeneratorObjDesc(thread_, asyncGeneratorFuncPrototypeValue, false, false, true);
3208     JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>(env->GetInitialAsyncGenerator()),
3209                                 globalConst->GetHandledConstructorString(), asyncGeneratorObjDesc);
3210 
3211     PropertyDescriptor asyncGeneratorObjProtoDesc(thread_, asyncGeneratorFuncPrototypeValue, true, false, false);
3212     JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>(env->GetInitialAsyncGenerator()),
3213                                 globalConst->GetHandledPrototypeString(), asyncGeneratorObjProtoDesc);
3214 
3215     env->SetAsyncGeneratorFunctionPrototype(thread_, asyncGeneratorFuncPrototype);
3216 }
3217 
InitializeGenerator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const3218 void Builtins::InitializeGenerator(const JSHandle<GlobalEnv> &env, const JSHandle<JSHClass> &objFuncClass) const
3219 {
3220     [[maybe_unused]] EcmaHandleScope scope(thread_);
3221     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3222     JSHandle<JSObject> generatorFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
3223 
3224     // GeneratorObject.prototype method
3225     // 26.5.1.2 Generator.prototype.next(value)
3226     SetFunction(env, generatorFuncPrototype, "next", GeneratorObject::GeneratorPrototypeNext, FunctionLength::ONE);
3227     // 26.5.1.3 Generator.prototype.return(value)
3228     SetFunction(env, generatorFuncPrototype, "return", GeneratorObject::GeneratorPrototypeReturn, FunctionLength::ONE);
3229     // 26.5.1.4 Generator.prototype.throw(exception)
3230     SetFunction(env, generatorFuncPrototype, "throw", GeneratorObject::GeneratorPrototypeThrow, FunctionLength::ONE);
3231 
3232     // 26.5.1.5 Generator.prototype[@@toStringTag]
3233     SetStringTagSymbol(env, generatorFuncPrototype, "Generator");
3234 
3235     // Generator with constructor, symbolTag, next/return/throw etc.
3236     PropertyDescriptor descriptor(thread_, env->GetIteratorPrototype(), true, false, false);
3237     JSObject::DefineOwnProperty(thread_, generatorFuncPrototype, globalConst->GetHandledPrototypeString(), descriptor);
3238     env->SetGeneratorPrototype(thread_, generatorFuncPrototype);
3239     JSObject::SetPrototype(thread_, generatorFuncPrototype, env->GetIteratorPrototype());
3240 
3241     // Generator {}
3242     JSHandle<JSObject> initialGeneratorFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
3243     JSObject::SetPrototype(thread_, initialGeneratorFuncPrototype, JSHandle<JSTaggedValue>(generatorFuncPrototype));
3244     env->SetInitialGenerator(thread_, initialGeneratorFuncPrototype);
3245 }
3246 
InitializeAsyncGenerator(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const3247 void Builtins::InitializeAsyncGenerator(const JSHandle<GlobalEnv> &env,
3248                                         const JSHandle<JSHClass> &objFuncClass) const
3249 {
3250     [[maybe_unused]] EcmaHandleScope scope(thread_);
3251 
3252     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3253     JSHandle<JSObject> asyncGeneratorFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
3254 
3255     // GeneratorObject.prototype method
3256     // 27.6.1.2 AsyncGenerator.prototype.next ( value )
3257     SetFunction(env, asyncGeneratorFuncPrototype, "next", AsyncGeneratorObject::AsyncGeneratorPrototypeNext,
3258                 FunctionLength::ONE);
3259     // 27.6.1.3 AsyncGenerator.prototype.return ( value )
3260     SetFunction(env, asyncGeneratorFuncPrototype, "return", AsyncGeneratorObject::AsyncGeneratorPrototypeReturn,
3261                 FunctionLength::ONE);
3262     // 27.6.1.4 AsyncGenerator.prototype.throw ( exception )
3263     SetFunction(env, asyncGeneratorFuncPrototype, "throw", AsyncGeneratorObject::AsyncGeneratorPrototypeThrow,
3264                 FunctionLength::ONE);
3265 
3266     // 27.6.1.5 AsyncGenerator.prototype [ @@toStringTag ]
3267     SetStringTagSymbol(env, asyncGeneratorFuncPrototype, "AsyncGenerator");
3268 
3269     PropertyDescriptor descriptor(thread_, env->GetAsyncIteratorPrototype(), true, false, false);
3270     JSObject::DefineOwnProperty(thread_, asyncGeneratorFuncPrototype,
3271                                 globalConst->GetHandledPrototypeString(), descriptor);
3272     env->SetAsyncGeneratorPrototype(thread_, asyncGeneratorFuncPrototype);
3273     JSObject::SetPrototype(thread_, asyncGeneratorFuncPrototype, env->GetAsyncIteratorPrototype());
3274 
3275     JSHandle<JSObject> initialAsyncGeneratorFuncPrototype = factory_->NewJSObjectWithInit(objFuncClass);
3276     JSObject::SetPrototype(thread_, initialAsyncGeneratorFuncPrototype,
3277                            JSHandle<JSTaggedValue>(asyncGeneratorFuncPrototype));
3278     env->SetInitialAsyncGenerator(thread_, initialAsyncGeneratorFuncPrototype);
3279 }
3280 
SetArgumentsSharedAccessor(const JSHandle<GlobalEnv> & env)3281 void Builtins::SetArgumentsSharedAccessor(const JSHandle<GlobalEnv> &env)
3282 {
3283     JSHandle<JSTaggedValue> throwFunction = env->GetThrowTypeError();
3284 
3285     JSHandle<AccessorData> accessor = factory_->NewAccessorData();
3286     accessor->SetGetter(thread_, throwFunction);
3287     accessor->SetSetter(thread_, throwFunction);
3288     env->SetArgumentsCallerAccessor(thread_, accessor);
3289 
3290     accessor = factory_->NewAccessorData();
3291     accessor->SetGetter(thread_, throwFunction);
3292     accessor->SetSetter(thread_, throwFunction);
3293     env->SetArgumentsCalleeAccessor(thread_, accessor);
3294 }
3295 
SetAccessor(const JSHandle<JSObject> & obj,const JSHandle<JSTaggedValue> & key,const JSHandle<JSTaggedValue> & getter,const JSHandle<JSTaggedValue> & setter) const3296 void Builtins::SetAccessor(const JSHandle<JSObject> &obj, const JSHandle<JSTaggedValue> &key,
3297                            const JSHandle<JSTaggedValue> &getter, const JSHandle<JSTaggedValue> &setter) const
3298 {
3299     JSHandle<AccessorData> accessor = factory_->NewAccessorData();
3300     accessor->SetGetter(thread_, getter);
3301     accessor->SetSetter(thread_, setter);
3302     PropertyAttributes attr = PropertyAttributes::DefaultAccessor(false, false, true);
3303     JSObject::AddAccessor(thread_, JSHandle<JSTaggedValue>::Cast(obj), key, accessor, attr);
3304 }
3305 
SetGetter(const JSHandle<JSObject> & obj,const JSHandle<JSTaggedValue> & key,const JSHandle<JSTaggedValue> & getter) const3306 void Builtins::SetGetter(const JSHandle<JSObject> &obj, const JSHandle<JSTaggedValue> &key,
3307                          const JSHandle<JSTaggedValue> &getter) const
3308 {
3309     JSHandle<AccessorData> accessor = factory_->NewAccessorData();
3310     accessor->SetGetter(thread_, getter);
3311     PropertyAttributes attr = PropertyAttributes::DefaultAccessor(false, false, true);
3312     JSObject::AddAccessor(thread_, JSHandle<JSTaggedValue>::Cast(obj), key, accessor, attr);
3313 }
3314 #ifdef ARK_SUPPORT_INTL
NewIntlConstructor(const JSHandle<GlobalEnv> & env,const JSHandle<JSObject> & prototype,EcmaEntrypoint ctorFunc,const char * name,int length)3315 JSHandle<JSFunction> Builtins::NewIntlConstructor(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &prototype,
3316                                                   EcmaEntrypoint ctorFunc, const char *name, int length)
3317 {
3318     JSHandle<JSFunction> ctor =
3319         factory_->NewJSFunction(env, reinterpret_cast<void *>(ctorFunc), FunctionKind::BUILTIN_CONSTRUCTOR);
3320     InitializeIntlCtor(env, prototype, ctor, name, length);
3321     return ctor;
3322 }
3323 
3324 #define INTL_LAZY_INITIALIZE(type)                                               \
3325     void Builtins::LazyInitialize##type(const JSHandle<GlobalEnv> &env) const    \
3326     {                                                                            \
3327         [[maybe_unused]] EcmaHandleScope scope(thread_);                         \
3328         JSHandle<JSObject> intlObject(env->GetIntlFunction());                   \
3329         JSHandle<JSTaggedValue> key(factory_->NewFromUtf8(#type));               \
3330         auto accessor = factory_->NewInternalAccessor(nullptr,                   \
3331             reinterpret_cast<void *>(BuiltinsLazyCallback::type));               \
3332         SetLazyAccessor(intlObject, key, accessor);                              \
3333         env->Set##type##Function(thread_, accessor);                             \
3334     }
3335 
ITERATE_INTL(INTL_LAZY_INITIALIZE)3336 ITERATE_INTL(INTL_LAZY_INITIALIZE)
3337 #undef INTL_LAZY_INITIALIZE
3338 
3339 void Builtins::InitializeIntlCtor(const JSHandle<GlobalEnv> &env, const JSHandle<JSObject> &prototype,
3340                                   const JSHandle<JSFunction> &ctor, const char *name, int length)
3341 {
3342     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3343     JSFunction::SetFunctionLength(thread_, ctor, JSTaggedValue(length));
3344     JSHandle<JSTaggedValue> nameString(factory_->NewFromUtf8(name));
3345     JSFunction::SetFunctionName(thread_, JSHandle<JSFunctionBase>(ctor), nameString,
3346                                 JSHandle<JSTaggedValue>(thread_, JSTaggedValue::Undefined()));
3347     JSHandle<JSTaggedValue> constructorKey = globalConst->GetHandledConstructorString();
3348     PropertyDescriptor descriptor1(thread_, JSHandle<JSTaggedValue>::Cast(ctor), true, false, true);
3349     JSObject::DefineOwnProperty(thread_, prototype, constructorKey, descriptor1);
3350 
3351     // set "prototype" in constructor.
3352     ctor->SetFunctionPrototype(thread_, prototype.GetTaggedValue());
3353 
3354     if (!JSTaggedValue::SameValue(nameString, thread_->GlobalConstants()->GetHandledAsyncFunctionString())) {
3355         JSHandle<JSObject> intlObject(thread_, env->GetIntlFunction().GetTaggedValue());
3356         PropertyDescriptor descriptor2(thread_, JSHandle<JSTaggedValue>::Cast(ctor), true, false, true);
3357         JSObject::DefineOwnProperty(thread_, intlObject, nameString, descriptor2);
3358     }
3359 }
3360 
InitializeIntl(const JSHandle<GlobalEnv> & env,const JSHandle<JSTaggedValue> & objFuncPrototypeValue)3361 void Builtins::InitializeIntl(const JSHandle<GlobalEnv> &env, const JSHandle<JSTaggedValue> &objFuncPrototypeValue)
3362 {
3363     [[maybe_unused]] EcmaHandleScope scope(thread_);
3364     JSHandle<JSHClass> intlHClass = factory_->NewEcmaHClass(JSIntl::SIZE, JSType::JS_INTL, objFuncPrototypeValue);
3365     JSHandle<JSObject> intlObject = factory_->NewJSObjectWithInit(intlHClass);
3366 
3367     JSHandle<JSTaggedValue> initIntlSymbol(factory_->NewPublicSymbolWithChar("Symbol.IntlLegacyConstructedSymbol"));
3368     SetNoneAttributeProperty(intlObject, "fallbackSymbol", initIntlSymbol);
3369 
3370     SetFunction(env, intlObject, "getCanonicalLocales", Intl::GetCanonicalLocales, FunctionLength::ONE);
3371 
3372     // initial value of the "Intl" property of the global object.
3373     JSHandle<JSTaggedValue> intlString(factory_->NewFromASCII("Intl"));
3374     JSHandle<JSObject> globalObject(thread_, env->GetGlobalObject());
3375     PropertyDescriptor intlDesc(thread_, JSHandle<JSTaggedValue>::Cast(intlObject), true, false, true);
3376     JSObject::DefineOwnProperty(thread_, globalObject, intlString, intlDesc);
3377 
3378     SetStringTagSymbol(env, intlObject, "Intl");
3379 
3380     env->SetIntlFunction(thread_, intlObject);
3381 }
3382 
InitializeDateTimeFormat(const JSHandle<GlobalEnv> & env)3383 void Builtins::InitializeDateTimeFormat(const JSHandle<GlobalEnv> &env)
3384 {
3385     [[maybe_unused]] EcmaHandleScope scope(thread_);
3386     // DateTimeFormat.prototype
3387     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3388     JSHandle<JSObject> dtfPrototype = factory_->NewJSObjectByConstructor(objFun);
3389     JSHandle<JSTaggedValue> dtfPrototypeValue(dtfPrototype);
3390 
3391     // DateTimeFormat.prototype_or_hclass
3392     JSHandle<JSHClass> dtfFuncInstanceHClass =
3393         factory_->NewEcmaHClass(JSDateTimeFormat::SIZE, JSType::JS_DATE_TIME_FORMAT, dtfPrototypeValue);
3394 
3395     // DateTimeFormat = new Function()
3396     // 13.4.1 Intl.DateTimeFormat.prototype.constructor
3397     JSHandle<JSObject> dtfFunction(NewIntlConstructor(env, dtfPrototype, DateTimeFormat::DateTimeFormatConstructor,
3398                                                       "DateTimeFormat", FunctionLength::ZERO));
3399     JSHandle<JSFunction>(dtfFunction)->SetFunctionPrototype(thread_, JSTaggedValue(*dtfFuncInstanceHClass));
3400 
3401     // 13.3.2 Intl.DateTimeFormat.supportedLocalesOf ( locales [ , options ] )
3402     SetFunction(env, dtfFunction, "supportedLocalesOf", DateTimeFormat::SupportedLocalesOf, FunctionLength::ONE);
3403 
3404     // DateTimeFormat.prototype method
3405     // 13.4.2 Intl.DateTimeFormat.prototype [ @@toStringTag ]
3406     SetStringTagSymbol(env, dtfPrototype, "Intl.DateTimeFormat");
3407     env->SetDateTimeFormatFunction(thread_, dtfFunction);
3408 
3409     // 13.4.3 get Intl.DateTimeFormat.prototype.format
3410     JSHandle<JSTaggedValue> formatGetter = CreateGetter(env, DateTimeFormat::Format, "format", FunctionLength::ZERO);
3411     JSHandle<JSTaggedValue> formatSetter(thread_, JSTaggedValue::Undefined());
3412     SetAccessor(dtfPrototype, thread_->GlobalConstants()->GetHandledFormatString(), formatGetter, formatSetter);
3413 
3414     // 13.4.4 Intl.DateTimeFormat.prototype.formatToParts ( date )
3415     SetFunction(env, dtfPrototype, "formatToParts", DateTimeFormat::FormatToParts, FunctionLength::ONE);
3416 
3417     // 13.4.5 Intl.DateTimeFormat.prototype.resolvedOptions ()
3418     SetFunction(env, dtfPrototype, "resolvedOptions", DateTimeFormat::ResolvedOptions, FunctionLength::ZERO);
3419 
3420     SetFunction(env, dtfPrototype, "formatRange", DateTimeFormat::FormatRange, FunctionLength::TWO);
3421 
3422     SetFunction(env, dtfPrototype, "formatRangeToParts", DateTimeFormat::FormatRangeToParts, FunctionLength::TWO);
3423 }
3424 
InitializeRelativeTimeFormat(const JSHandle<GlobalEnv> & env)3425 void Builtins::InitializeRelativeTimeFormat(const JSHandle<GlobalEnv> &env)
3426 {
3427     [[maybe_unused]] EcmaHandleScope scope(thread_);
3428     // RelativeTimeFormat.prototype
3429     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3430     JSHandle<JSObject> rtfPrototype = factory_->NewJSObjectByConstructor(objFun);
3431     JSHandle<JSTaggedValue> rtfPrototypeValue(rtfPrototype);
3432 
3433     // RelativeTimeFormat.prototype_or_hclass
3434     JSHandle<JSHClass> rtfFuncInstanceHClass =
3435         factory_->NewEcmaHClass(JSRelativeTimeFormat::SIZE, JSType::JS_RELATIVE_TIME_FORMAT, rtfPrototypeValue);
3436 
3437     // RelativeTimeFormat = new Function()
3438     // 14.2.1 Intl.RelativeTimeFormat.prototype.constructor
3439     JSHandle<JSObject> rtfFunction(NewIntlConstructor(env, rtfPrototype,
3440                                                       RelativeTimeFormat::RelativeTimeFormatConstructor,
3441                                                       "RelativeTimeFormat", FunctionLength::ZERO));
3442     JSHandle<JSFunction>(rtfFunction)->SetFunctionPrototype(thread_, JSTaggedValue(*rtfFuncInstanceHClass));
3443 
3444     // 14.3.2 Intl.RelativeTimeFormat.supportedLocalesOf ( locales [ , options ] )
3445     SetFunction(env, rtfFunction, "supportedLocalesOf", RelativeTimeFormat::SupportedLocalesOf, FunctionLength::ONE);
3446 
3447     // RelativeTimeFormat.prototype method
3448     // 14.4.2 Intl.RelativeTimeFormat.prototype [ @@toStringTag ]
3449     SetStringTagSymbol(env, rtfPrototype, "Intl.RelativeTimeFormat");
3450     env->SetRelativeTimeFormatFunction(thread_, rtfFunction);
3451 
3452     // 14.4.3 get Intl.RelativeTimeFormat.prototype.format
3453     SetFunction(env, rtfPrototype, "format", RelativeTimeFormat::Format, FunctionLength::TWO);
3454 
3455     // 14.4.4  Intl.RelativeTimeFormat.prototype.formatToParts( value, unit )
3456     SetFunction(env, rtfPrototype, "formatToParts", RelativeTimeFormat::FormatToParts, FunctionLength::TWO);
3457 
3458     // 14.4.5 Intl.RelativeTimeFormat.prototype.resolvedOptions ()
3459     SetFunction(env, rtfPrototype, "resolvedOptions", RelativeTimeFormat::ResolvedOptions, FunctionLength::ZERO);
3460 }
3461 
InitializeNumberFormat(const JSHandle<GlobalEnv> & env)3462 void Builtins::InitializeNumberFormat(const JSHandle<GlobalEnv> &env)
3463 {
3464     [[maybe_unused]] EcmaHandleScope scope(thread_);
3465     // NumberFormat.prototype
3466     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3467     JSHandle<JSObject> nfPrototype = factory_->NewJSObjectByConstructor(objFun);
3468     JSHandle<JSTaggedValue> nfPrototypeValue(nfPrototype);
3469 
3470     // NumberFormat.prototype_or_hclass
3471     JSHandle<JSHClass> nfFuncInstanceHClass =
3472         factory_->NewEcmaHClass(JSNumberFormat::SIZE, JSType::JS_NUMBER_FORMAT, nfPrototypeValue);
3473 
3474     // NumberFormat = new Function()
3475     // 12.4.1 Intl.NumberFormat.prototype.constructor
3476     JSHandle<JSObject> nfFunction(NewIntlConstructor(env, nfPrototype, NumberFormat::NumberFormatConstructor,
3477                                                      "NumberFormat", FunctionLength::ZERO));
3478     JSHandle<JSFunction>(nfFunction)->SetFunctionPrototype(thread_, JSTaggedValue(*nfFuncInstanceHClass));
3479 
3480     // 12.3.2 Intl.NumberFormat.supportedLocalesOf ( locales [ , options ] )
3481     SetFunction(env, nfFunction, "supportedLocalesOf", NumberFormat::SupportedLocalesOf, FunctionLength::ONE);
3482 
3483     // NumberFormat.prototype method
3484     // 12.4.2 Intl.NumberFormat.prototype [ @@toStringTag ]
3485     SetStringTagSymbol(env, nfPrototype, "Intl.NumberFormat");
3486     env->SetNumberFormatFunction(thread_, nfFunction);
3487 
3488     // 12.4.3 get Intl.NumberFormat.prototype.format
3489     JSHandle<JSTaggedValue> formatGetter = CreateGetter(env, NumberFormat::Format, "format", FunctionLength::ZERO);
3490     JSHandle<JSTaggedValue> formatSetter(thread_, JSTaggedValue::Undefined());
3491     SetAccessor(nfPrototype, thread_->GlobalConstants()->GetHandledFormatString(), formatGetter, formatSetter);
3492 
3493     // 12.4.4 Intl.NumberFormat.prototype.formatToParts ( date )
3494     SetFunction(env, nfPrototype, "formatToParts", NumberFormat::FormatToParts, FunctionLength::ONE);
3495 
3496     // 12.4.5 Intl.NumberFormat.prototype.resolvedOptions ()
3497     SetFunction(env, nfPrototype, "resolvedOptions", NumberFormat::ResolvedOptions, FunctionLength::ZERO);
3498 }
3499 
InitializeLocale(const JSHandle<GlobalEnv> & env)3500 void Builtins::InitializeLocale(const JSHandle<GlobalEnv> &env)
3501 {
3502     [[maybe_unused]] EcmaHandleScope scope(thread_);
3503     // Locale.prototype
3504     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3505     JSHandle<JSObject> localePrototype = factory_->NewJSObjectByConstructor(objFun);
3506     JSHandle<JSTaggedValue> localePrototypeValue(localePrototype);
3507 
3508     // Locale.prototype_or_hclass
3509     JSHandle<JSHClass> localeFuncInstanceHClass =
3510         factory_->NewEcmaHClass(JSLocale::SIZE, JSType::JS_LOCALE, localePrototypeValue);
3511 
3512     // Locale = new Function()
3513     JSHandle<JSObject> localeFunction(
3514         NewIntlConstructor(env, localePrototype, Locale::LocaleConstructor, "Locale", FunctionLength::ONE));
3515     JSHandle<JSFunction>(localeFunction)->SetFunctionPrototype(thread_, JSTaggedValue(*localeFuncInstanceHClass));
3516 
3517     // Locale.prototype method
3518     SetFunction(env, localePrototype, "maximize", Locale::Maximize, FunctionLength::ZERO);
3519     SetFunction(env, localePrototype, "minimize", Locale::Minimize, FunctionLength::ZERO);
3520     SetFunction(env, localePrototype, "toString", Locale::ToString, FunctionLength::ZERO);
3521 
3522     JSHandle<JSTaggedValue> baseNameGetter = CreateGetter(env, Locale::GetBaseName, "baseName", FunctionLength::ZERO);
3523     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledBaseNameString(), baseNameGetter);
3524 
3525     JSHandle<JSTaggedValue> calendarGetter = CreateGetter(env, Locale::GetCalendar, "calendar", FunctionLength::ZERO);
3526     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledCalendarString(), calendarGetter);
3527 
3528     JSHandle<JSTaggedValue> caseFirstGetter =
3529         CreateGetter(env, Locale::GetCaseFirst, "caseFirst", FunctionLength::ZERO);
3530     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledCaseFirstString(), caseFirstGetter);
3531 
3532     JSHandle<JSTaggedValue> collationGetter =
3533         CreateGetter(env, Locale::GetCollation, "collation", FunctionLength::ZERO);
3534     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledCollationString(), collationGetter);
3535 
3536     JSHandle<JSTaggedValue> hourCycleGetter =
3537         CreateGetter(env, Locale::GetHourCycle, "hourCycle", FunctionLength::ZERO);
3538     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledHourCycleString(), hourCycleGetter);
3539 
3540     JSHandle<JSTaggedValue> numericGetter = CreateGetter(env, Locale::GetNumeric, "numeric", FunctionLength::ZERO);
3541     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledNumericString(), numericGetter);
3542 
3543     JSHandle<JSTaggedValue> numberingSystemGetter =
3544         CreateGetter(env, Locale::GetNumberingSystem, "numberingSystem", FunctionLength::ZERO);
3545     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledNumberingSystemString(), numberingSystemGetter);
3546 
3547     JSHandle<JSTaggedValue> languageGetter = CreateGetter(env, Locale::GetLanguage, "language", FunctionLength::ZERO);
3548     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledLanguageString(), languageGetter);
3549 
3550     JSHandle<JSTaggedValue> scriptGetter = CreateGetter(env, Locale::GetScript, "script", FunctionLength::ZERO);
3551     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledScriptString(), scriptGetter);
3552 
3553     JSHandle<JSTaggedValue> regionGetter = CreateGetter(env, Locale::GetRegion, "region", FunctionLength::ZERO);
3554     SetGetter(localePrototype, thread_->GlobalConstants()->GetHandledRegionString(), regionGetter);
3555 
3556     // 10.3.2 Intl.Locale.prototype[ @@toStringTag ]
3557     SetStringTagSymbol(env, localePrototype, "Intl.Locale");
3558     env->SetLocaleFunction(thread_, localeFunction);
3559 }
3560 
InitializeCollator(const JSHandle<GlobalEnv> & env)3561 void Builtins::InitializeCollator(const JSHandle<GlobalEnv> &env)
3562 {
3563     [[maybe_unused]] EcmaHandleScope scope(thread_);
3564     // Collator.prototype
3565     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3566     JSHandle<JSObject> collatorPrototype = factory_->NewJSObjectByConstructor(objFun);
3567     JSHandle<JSTaggedValue> collatorPrototypeValue(collatorPrototype);
3568 
3569     // Collator.prototype_or_hclass
3570     JSHandle<JSHClass> collatorFuncInstanceHClass =
3571         factory_->NewEcmaHClass(JSCollator::SIZE, JSType::JS_COLLATOR, collatorPrototypeValue);
3572 
3573     // Collator = new Function()
3574     // 11.1.2 Intl.Collator.prototype.constructor
3575     JSHandle<JSObject> collatorFunction(
3576         NewIntlConstructor(env, collatorPrototype, Collator::CollatorConstructor, "Collator", FunctionLength::ZERO));
3577     JSHandle<JSFunction>(collatorFunction)->SetFunctionPrototype(thread_, JSTaggedValue(*collatorFuncInstanceHClass));
3578 
3579     // 11.2.2 Intl.Collator.supportedLocalesOf ( locales [ , options ] )
3580     SetFunction(env, collatorFunction, "supportedLocalesOf", Collator::SupportedLocalesOf, FunctionLength::ONE);
3581 
3582     // Collator.prototype method
3583     // 11.3.2 Intl.Collator.prototype [ @@toStringTag ]
3584     SetStringTagSymbol(env, collatorPrototype, "Intl.Collator");
3585     env->SetCollatorFunction(thread_, collatorFunction);
3586 
3587     // 11.3.3 get Intl.Collator.prototype.compare
3588     JSHandle<JSTaggedValue> compareGetter = CreateGetter(env, Collator::Compare, "compare", FunctionLength::ZERO);
3589     JSHandle<JSTaggedValue> compareSetter(thread_, JSTaggedValue::Undefined());
3590     SetAccessor(collatorPrototype, thread_->GlobalConstants()->GetHandledCompareString(), compareGetter, compareSetter);
3591 
3592     // 11.3.4 Intl.Collator.prototype.resolvedOptions ()
3593     SetFunction(env, collatorPrototype, "resolvedOptions", Collator::ResolvedOptions, FunctionLength::ZERO);
3594 }
3595 
InitializePluralRules(const JSHandle<GlobalEnv> & env)3596 void Builtins::InitializePluralRules(const JSHandle<GlobalEnv> &env)
3597 {
3598     [[maybe_unused]] EcmaHandleScope scope(thread_);
3599     // PluralRules.prototype
3600     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3601     JSHandle<JSObject> prPrototype = factory_->NewJSObjectByConstructor(objFun);
3602     JSHandle<JSTaggedValue> prPrototypeValue(prPrototype);
3603 
3604     // PluralRules.prototype_or_hclass
3605     JSHandle<JSHClass> prFuncInstanceHClass =
3606         factory_->NewEcmaHClass(JSPluralRules::SIZE, JSType::JS_PLURAL_RULES, prPrototypeValue);
3607 
3608     // PluralRules = new Function()
3609     // 15.2.1 Intl.PluralRules.prototype.constructor
3610     JSHandle<JSObject> prFunction(
3611         NewIntlConstructor(env, prPrototype, PluralRules::PluralRulesConstructor, "PluralRules", FunctionLength::ZERO));
3612     JSHandle<JSFunction>(prFunction)->SetFunctionPrototype(thread_, JSTaggedValue(*prFuncInstanceHClass));
3613 
3614     // 15.3.2 Intl.PluralRules.supportedLocalesOf ( locales [ , options ] )
3615     SetFunction(env, prFunction, "supportedLocalesOf", PluralRules::SupportedLocalesOf, FunctionLength::ONE);
3616 
3617     // PluralRules.prototype method
3618     // 15.4.2 Intl.PluralRules.prototype [ @@toStringTag ]
3619     SetStringTagSymbol(env, prPrototype, "Intl.PluralRules");
3620     env->SetPluralRulesFunction(thread_, prFunction);
3621 
3622     // 15.4.3 get Intl.PluralRules.prototype.select
3623     SetFunction(env, prPrototype, "select", PluralRules::Select, FunctionLength::ONE);
3624 
3625     // 15.4.5 Intl.PluralRules.prototype.resolvedOptions ()
3626     SetFunction(env, prPrototype, "resolvedOptions", PluralRules::ResolvedOptions, FunctionLength::ZERO);
3627 }
3628 
InitializeDisplayNames(const JSHandle<GlobalEnv> & env)3629 void Builtins::InitializeDisplayNames(const JSHandle<GlobalEnv> &env)
3630 {
3631     [[maybe_unused]] EcmaHandleScope scope(thread_);
3632     // DisplayNames.prototype
3633     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3634     JSHandle<JSObject> dnPrototype = factory_->NewJSObjectByConstructor(objFun);
3635     JSHandle<JSTaggedValue> dnPrototypeValue(dnPrototype);
3636 
3637     // DisplayNames.prototype_or_hclass
3638     JSHandle<JSHClass> dnFuncInstanceHClass =
3639         factory_->NewEcmaHClass(JSDisplayNames::SIZE, JSType::JS_DISPLAYNAMES, dnPrototypeValue);
3640 
3641     // DisplayNames = new Function()
3642     // 12.4.1 Intl.DisplayNames.prototype.constructor
3643     JSHandle<JSObject> dnFunction(NewIntlConstructor(env, dnPrototype, DisplayNames::DisplayNamesConstructor,
3644                                                      "DisplayNames", FunctionLength::TWO));
3645     JSHandle<JSFunction>(dnFunction)->SetFunctionPrototype(thread_, JSTaggedValue(*dnFuncInstanceHClass));
3646 
3647     // 12.3.2 Intl.DisplayNames.supportedLocalesOf ( locales [ , options ] )
3648     SetFunction(env, dnFunction, "supportedLocalesOf", DisplayNames::SupportedLocalesOf, FunctionLength::ONE);
3649 
3650     // DisplayNames.prototype method
3651     // 12.4.2 Intl.DisplayNames.prototype[ @@toStringTag ]
3652     SetStringTagSymbol(env, dnPrototype, "Intl.DisplayNames");
3653     env->SetDisplayNamesFunction(thread_, dnFunction);
3654 
3655     // 12.4.3 get Intl.DisplayNames.prototype.of
3656     SetFunction(env, dnPrototype, "of", DisplayNames::Of, FunctionLength::ONE);
3657 
3658     // 12.4.4 Intl.DisplayNames.prototype.resolvedOptions ()
3659     SetFunction(env, dnPrototype, "resolvedOptions", DisplayNames::ResolvedOptions, FunctionLength::ZERO);
3660 }
3661 
InitializeListFormat(const JSHandle<GlobalEnv> & env)3662 void Builtins::InitializeListFormat(const JSHandle<GlobalEnv> &env)
3663 {
3664     [[maybe_unused]] EcmaHandleScope scope(thread_);
3665     // JSListFormat.prototype
3666     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3667     JSHandle<JSObject> lfPrototype = factory_->NewJSObjectByConstructor(objFun);
3668     JSHandle<JSTaggedValue> lfPrototypeValue(lfPrototype);
3669 
3670     // JSListFormat.prototype_or_hclass
3671     JSHandle<JSHClass> lfFuncInstanceHClass =
3672         factory_->NewEcmaHClass(JSListFormat::SIZE, JSType::JS_LIST_FORMAT, lfPrototypeValue);
3673 
3674     // JSListFormat = new Function()
3675     // 13.4.1 Intl.ListFormat.prototype.constructor
3676     JSHandle<JSObject> lfFunction(NewIntlConstructor(env, lfPrototype, ListFormat::ListFormatConstructor,
3677                                                      "ListFormat", FunctionLength::ZERO));
3678     JSHandle<JSFunction>(lfFunction)->SetFunctionPrototype(thread_, JSTaggedValue(*lfFuncInstanceHClass));
3679 
3680     // 13.3.2 Intl.ListFormat.supportedLocalesOf ( locales [ , options ] )
3681     SetFunction(env, lfFunction, "supportedLocalesOf", ListFormat::SupportedLocalesOf, FunctionLength::ONE);
3682 
3683     // ListFormat.prototype method
3684     // 13.4.2 Intl.ListFormat.prototype [ @@toStringTag ]
3685     SetStringTagSymbol(env, lfPrototype, "Intl.ListFormat");
3686     env->SetListFormatFunction(thread_, lfFunction);
3687 
3688     // 13.4.3 get Intl.ListFormat.prototype.format( list )
3689     SetFunction(env, lfPrototype, "format", ListFormat::Format, FunctionLength::ONE);
3690 
3691     // 13.4.4 Intl.ListFormat.prototype.formatToParts( list )
3692     SetFunction(env, lfPrototype, "formatToParts", ListFormat::FormatToParts, FunctionLength::ONE);
3693 
3694     // 13.4.5 Intl.ListFormat.prototype.resolvedOptions()
3695     SetFunction(env, lfPrototype, "resolvedOptions", ListFormat::ResolvedOptions, FunctionLength::ZERO);
3696 }
3697 #endif
InitializeArkTools(const JSHandle<GlobalEnv> & env) const3698 JSHandle<JSObject> Builtins::InitializeArkTools(const JSHandle<GlobalEnv> &env) const
3699 {
3700     JSHandle<JSObject> tools = factory_->NewEmptyJSObject();
3701     SetFunction(env, tools, "print", builtins::BuiltinsArkTools::ObjectDump, FunctionLength::ZERO);
3702     SetFunction(env, tools, "excutePendingJob", builtins::BuiltinsArkTools::ExcutePendingJob, FunctionLength::ZERO);
3703     SetFunction(env, tools, "getLexicalEnv", builtins::BuiltinsArkTools::GetLexicalEnv, FunctionLength::ONE);
3704     SetFunction(env, tools, "compareHClass", builtins::BuiltinsArkTools::CompareHClass, FunctionLength::TWO);
3705     SetFunction(env, tools, "dumpHClass", builtins::BuiltinsArkTools::DumpHClass, FunctionLength::ONE);
3706     SetFunction(env, tools, "isTSHClass", builtins::BuiltinsArkTools::IsTSHClass, FunctionLength::ONE);
3707     SetFunction(env, tools, "getHClass", builtins::BuiltinsArkTools::GetHClass, FunctionLength::ONE);
3708     SetFunction(env, tools, "hasTSSubtyping", builtins::BuiltinsArkTools::HasTSSubtyping, FunctionLength::ONE);
3709     SetFunction(env, tools, "isNotHoleProperty", builtins::BuiltinsArkTools::IsNotHoleProperty,
3710                 FunctionLength::TWO);
3711     SetFunction(env, tools, "forceFullGC", builtins::BuiltinsArkTools::ForceFullGC, FunctionLength::ZERO);
3712     SetFunction(env, tools, "removeAOTFlag", builtins::BuiltinsArkTools::RemoveAOTFlag, FunctionLength::ONE);
3713 #if defined(ECMASCRIPT_SUPPORT_CPUPROFILER)
3714     SetFunction(env, tools, "startCpuProf", builtins::BuiltinsArkTools::StartCpuProfiler, FunctionLength::ZERO);
3715     SetFunction(env, tools, "stopCpuProf", builtins::BuiltinsArkTools::StopCpuProfiler, FunctionLength::ZERO);
3716 #endif
3717     SetFunction(env, tools, "isPrototype", builtins::BuiltinsArkTools::IsPrototype, FunctionLength::ONE);
3718     SetFunction(env, tools, "timeInUs",  builtins::BuiltinsArkTools::TimeInUs, FunctionLength::ZERO);
3719     return tools;
3720 }
3721 
InitializeGlobalRegExp(JSHandle<JSObject> & obj) const3722 void Builtins::InitializeGlobalRegExp(JSHandle<JSObject> &obj) const
3723 {
3724     JSHandle<JSTaggedValue> emptyString = thread_->GlobalConstants()->GetHandledEmptyString();
3725     JSHandle<JSTaggedValue> newBox1 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3726     SetConstantObject(obj, "$1", newBox1);
3727     JSHandle<JSTaggedValue> newBox2 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3728     SetConstantObject(obj, "$2", newBox2);
3729     JSHandle<JSTaggedValue> newBox3 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3730     SetConstantObject(obj, "$3", newBox3);
3731     JSHandle<JSTaggedValue> newBox4 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3732     SetConstantObject(obj, "$4", newBox4);
3733     JSHandle<JSTaggedValue> newBox5 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3734     SetConstantObject(obj, "$5", newBox5);
3735     JSHandle<JSTaggedValue> newBox6 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3736     SetConstantObject(obj, "$6", newBox6);
3737     JSHandle<JSTaggedValue> newBox7 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3738     SetConstantObject(obj, "$7", newBox7);
3739     JSHandle<JSTaggedValue> newBox8 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3740     SetConstantObject(obj, "$8", newBox8);
3741     JSHandle<JSTaggedValue> newBox9 = JSHandle<JSTaggedValue>(factory_->NewPropertyBox(emptyString));
3742     SetConstantObject(obj, "$9", newBox9);
3743 }
3744 
InitializeArkPrivate(const JSHandle<GlobalEnv> & env) const3745 JSHandle<JSObject> Builtins::InitializeArkPrivate(const JSHandle<GlobalEnv> &env) const
3746 {
3747     JSHandle<JSObject> arkPrivate = factory_->NewEmptyJSObject();
3748     SetFrozenFunction(env, arkPrivate, "Load", ContainersPrivate::Load, FunctionLength::ZERO);
3749 
3750     // It is used to provide non ECMA standard jsapi containers.
3751     SetConstant(arkPrivate, "ArrayList", JSTaggedValue(static_cast<int>(containers::ContainerTag::ArrayList)));
3752     SetConstant(arkPrivate, "Queue", JSTaggedValue(static_cast<int>(containers::ContainerTag::Queue)));
3753     SetConstant(arkPrivate, "Deque", JSTaggedValue(static_cast<int>(containers::ContainerTag::Deque)));
3754     SetConstant(arkPrivate, "Stack", JSTaggedValue(static_cast<int>(containers::ContainerTag::Stack)));
3755     SetConstant(arkPrivate, "Vector", JSTaggedValue(static_cast<int>(containers::ContainerTag::Vector)));
3756     SetConstant(arkPrivate, "List", JSTaggedValue(static_cast<int>(containers::ContainerTag::List)));
3757     SetConstant(arkPrivate, "LinkedList", JSTaggedValue(static_cast<int>(containers::ContainerTag::LinkedList)));
3758     SetConstant(arkPrivate, "TreeMap", JSTaggedValue(static_cast<int>(containers::ContainerTag::TreeMap)));
3759     SetConstant(arkPrivate, "TreeSet", JSTaggedValue(static_cast<int>(containers::ContainerTag::TreeSet)));
3760     SetConstant(arkPrivate, "HashMap", JSTaggedValue(static_cast<int>(containers::ContainerTag::HashMap)));
3761     SetConstant(arkPrivate, "HashSet", JSTaggedValue(static_cast<int>(containers::ContainerTag::HashSet)));
3762     SetConstant(arkPrivate, "LightWeightMap",
3763                 JSTaggedValue(static_cast<int>(containers::ContainerTag::LightWeightMap)));
3764     SetConstant(arkPrivate, "LightWeightSet",
3765                 JSTaggedValue(static_cast<int>(containers::ContainerTag::LightWeightSet)));
3766     SetConstant(arkPrivate, "PlainArray", JSTaggedValue(static_cast<int>(containers::ContainerTag::PlainArray)));
3767     return arkPrivate;
3768 }
3769 
InitializeModuleNamespace(const JSHandle<GlobalEnv> & env,const JSHandle<JSHClass> & objFuncClass) const3770 void Builtins::InitializeModuleNamespace(const JSHandle<GlobalEnv> &env,
3771                                          const JSHandle<JSHClass> &objFuncClass) const
3772 {
3773     [[maybe_unused]] EcmaHandleScope scope(thread_);
3774     // ModuleNamespace.prototype
3775     JSHandle<JSObject> moduleNamespacePrototype = factory_->NewJSObjectWithInit(objFuncClass);
3776     JSHandle<JSTaggedValue> moduleNamespacePrototypeValue(moduleNamespacePrototype);
3777 
3778     //  ModuleNamespace.prototype_or_hclass
3779     JSHandle<JSHClass> moduleNamespaceHClass =
3780         factory_->NewEcmaHClass(ModuleNamespace::SIZE, JSType::JS_MODULE_NAMESPACE, moduleNamespacePrototypeValue);
3781     moduleNamespaceHClass->SetPrototype(thread_, JSTaggedValue::Null());
3782     env->SetModuleNamespaceClass(thread_, moduleNamespaceHClass.GetTaggedValue());
3783 
3784     // moduleNamespace.prototype [ @@toStringTag ]
3785     SetStringTagSymbol(env, moduleNamespacePrototype, "Module");
3786 }
3787 
InitializeCjsModule(const JSHandle<GlobalEnv> & env) const3788 void Builtins::InitializeCjsModule(const JSHandle<GlobalEnv> &env) const
3789 {
3790     [[maybe_unused]] EcmaHandleScope scope(thread_);
3791     // CjsModule.prototype
3792     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3793     JSHandle<JSObject> cjsModulePrototype = factory_->NewJSObjectByConstructor(objFun);
3794     JSHandle<JSTaggedValue> cjsModulePrototypeValue(cjsModulePrototype);
3795 
3796     // CjsModule.prototype_or_hclass
3797     JSHandle<JSHClass> cjsModuleHClass =
3798         factory_->NewEcmaHClass(CjsModule::SIZE, JSType::JS_CJS_MODULE, cjsModulePrototypeValue);
3799 
3800     // CjsModule.prototype.Constructor
3801     JSHandle<JSObject> cjsModuleFunction(
3802         NewBuiltinCjsCtor(env, cjsModulePrototype, BuiltinsCjsModule::CjsModuleConstructor, "Module",
3803                           FunctionLength::TWO));
3804 
3805     JSHandle<JSFunction>(cjsModuleFunction)->SetFunctionPrototype(thread_, cjsModuleHClass.GetTaggedValue());
3806 
3807     // CjsModule method
3808     SetFunction(env, cjsModuleFunction, "_load", BuiltinsCjsModule::Load, FunctionLength::ONE);
3809     SetFunction(env, cjsModuleFunction, "_resolveFilename", BuiltinsCjsModule::ResolveFilename, FunctionLength::ONE);
3810 
3811     // CjsModule.prototype method
3812     SetFunction(env, cjsModulePrototype, "require", BuiltinsCjsModule::Require, FunctionLength::ONE);
3813     SetFunction(env, cjsModulePrototype, "getExportsForCircularRequire",
3814                 BuiltinsCjsModule::GetExportsForCircularRequire, FunctionLength::ONE);
3815     SetFunction(env, cjsModulePrototype, "updateChildren", BuiltinsCjsModule::UpdateChildren, FunctionLength::ONE);
3816 
3817     JSHandle<JSTaggedValue> id(thread_->GlobalConstants()->GetHandledEmptyString());
3818     JSHandle<JSTaggedValue> path(thread_->GlobalConstants()->GetHandledEmptyString());
3819     JSHandle<JSTaggedValue> exports(factory_->NewEmptyJSObject());
3820     JSHandle<JSTaggedValue> parent(factory_->NewEmptyJSObject());
3821     JSHandle<JSTaggedValue> filename(thread_->GlobalConstants()->GetHandledEmptyString());
3822     JSHandle<JSTaggedValue> loaded(factory_->NewEmptyJSObject());
3823     JSHandle<JSTaggedValue> children(factory_->NewEmptyJSObject());
3824     JSHandle<JSTaggedValue> cache = JSHandle<JSTaggedValue>::Cast(CjsModuleCache::Create(thread_,
3825                                                                   CjsModuleCache::DEAULT_DICTIONART_CAPACITY));
3826 
3827     // CjsModule.prototype members
3828     SetNonConstantObject(cjsModulePrototype, "id", id);
3829     SetNonConstantObject(cjsModulePrototype, "path", path);
3830     SetNonConstantObject(cjsModulePrototype, "exports", exports);
3831     SetNonConstantObject(cjsModulePrototype, "parent", parent);
3832     SetNonConstantObject(cjsModulePrototype, "filename", filename);
3833     SetNonConstantObject(cjsModulePrototype, "loaded", loaded);
3834     SetNonConstantObject(cjsModulePrototype, "children", children);
3835 
3836     // CjsModule members
3837     SetNonConstantObject(cjsModuleFunction, "_cache", cache);
3838 
3839     env->SetCjsModuleFunction(thread_, cjsModuleFunction);
3840 }
3841 
InitializeCjsExports(const JSHandle<GlobalEnv> & env) const3842 void Builtins::InitializeCjsExports(const JSHandle<GlobalEnv> &env) const
3843 {
3844     [[maybe_unused]] EcmaHandleScope scope(thread_);
3845 
3846     // CjsExports.prototype
3847     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3848     JSHandle<JSObject> cjsExportsPrototype = factory_->NewJSObjectByConstructor(objFun);
3849     JSHandle<JSTaggedValue> cjsExportsPrototypeValue(cjsExportsPrototype);
3850 
3851     // CjsExports.prototype_or_hclass
3852     JSHandle<JSHClass> cjsExportsHClass =
3853         factory_->NewEcmaHClass(CjsExports::SIZE, JSType::JS_CJS_EXPORTS, cjsExportsPrototypeValue);
3854 
3855     // CjsExports.prototype.Constructor
3856     JSHandle<JSObject> cjsExportsFunction(
3857         NewBuiltinCjsCtor(env, cjsExportsPrototype, BuiltinsCjsExports::CjsExportsConstructor, "Exports",
3858                           FunctionLength::TWO));
3859 
3860     JSHandle<JSFunction>(cjsExportsFunction)->SetFunctionPrototype(thread_, cjsExportsHClass.GetTaggedValue());
3861 
3862     env->SetCjsExportsFunction(thread_, cjsExportsFunction);
3863 }
3864 
InitializeCjsRequire(const JSHandle<GlobalEnv> & env) const3865 void Builtins::InitializeCjsRequire(const JSHandle<GlobalEnv> &env) const
3866 {
3867     [[maybe_unused]] EcmaHandleScope scope(thread_);
3868     // CjsRequire.prototype
3869     JSHandle<JSFunction> objFun(env->GetObjectFunction());
3870     JSHandle<JSObject> cjsRequirePrototype = factory_->NewJSObjectByConstructor(objFun);
3871     JSHandle<JSTaggedValue> cjsRequirePrototypeValue(cjsRequirePrototype);
3872 
3873     // CjsExports.prototype_or_hclass
3874     JSHandle<JSHClass> cjsRequireHClass =
3875         factory_->NewEcmaHClass(CjsRequire::SIZE, JSType::JS_CJS_REQUIRE, cjsRequirePrototypeValue);
3876 
3877     // CjsExports.prototype.Constructor
3878     JSHandle<JSFunction> cjsRequireFunction =
3879         NewBuiltinCjsCtor(env, cjsRequirePrototype, BuiltinsCjsRequire::CjsRequireConstructor, "require",
3880                           FunctionLength::ONE);
3881     JSHandle<JSFunction>(cjsRequireFunction)->SetFunctionPrototype(thread_, cjsRequireHClass.GetTaggedValue());
3882 
3883     // CjsModule.prototype method
3884     SetFunction(env, cjsRequirePrototype, "Main", BuiltinsCjsRequire::Main, FunctionLength::ONE);
3885 
3886     env->SetCjsRequireFunction(thread_, cjsRequireFunction);
3887 }
3888 
InitializeDefaultExportOfScript(const JSHandle<GlobalEnv> & env) const3889 void Builtins::InitializeDefaultExportOfScript(const JSHandle<GlobalEnv> &env) const
3890 {
3891     JSHandle<JSFunction> builtinObj(env->GetObjectFunction());
3892     JSHandle<JSTaggedValue> emptyObj(factory_->NewJSObjectByConstructor(builtinObj));
3893     JSHandle<JSTaggedValue> defaultKey(factory_->NewFromUtf8("default"));
3894 
3895     JSHandle<TaggedArray> props(factory_->NewTaggedArray(2)); // 2 : two propertise
3896     props->Set(thread_, 0, defaultKey);
3897     props->Set(thread_, 1, emptyObj);
3898     JSHandle<JSHClass> hclass = factory_->CreateObjectClass(props, 1);
3899     JSHandle<JSObject> obj = factory_->NewJSObject(hclass);
3900     obj->SetPropertyInlinedProps(thread_, 0, props->Get(1));
3901     env->SetExportOfScript(thread_, obj);
3902     return;
3903 }
3904 }  // namespace panda::ecmascript
3905