1 /*
2  * Copyright (c) 2022-2024 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 #ifndef ECMASCRIPT_JS_WEAK_REF_H
17 #define ECMASCRIPT_JS_WEAK_REF_H
18 
19 #include "ecmascript/ecma_context.h"
20 #include "ecmascript/js_object.h"
21 #include "ecmascript/js_tagged_value-inl.h"
22 
23 namespace panda::ecmascript {
24 class JSWeakRef : public JSObject {
25 public:
Cast(TaggedObject *object)26     static JSWeakRef *Cast(TaggedObject *object)
27     {
28         ASSERT(JSTaggedValue(object).IsJSWeakRef());
29         return static_cast<JSWeakRef *>(object);
30     }
31 
32     // 26.1.4.1 WeakRefDeref ( weakRef )
WeakRefDeref(JSThread *thread, const JSHandle<JSWeakRef> &weakRef)33     static JSTaggedValue WeakRefDeref(JSThread *thread, const JSHandle<JSWeakRef> &weakRef)
34     {
35         // 1. Let target be weakRef.[[WeakRefTarget]].
36         // 2. If target is not empty, then
37         //     a. Perform ! AddToKeptObjects(target).
38         //     b. Return target.
39         // 3. Return undefined.
40         JSHandle<JSTaggedValue> target(thread, weakRef->GetFromWeak());
41         if (!target->IsUndefined()) {
42             thread->GetCurrentEcmaContext()->AddToKeptObjects(target);
43         }
44         return target.GetTaggedValue();
45     }
46 
SetToWeak(JSThread *thread, JSTaggedValue value)47     void SetToWeak(JSThread *thread, JSTaggedValue value)
48     {
49         ALLOW_LOCAL_TO_SHARE_WEAK_REF_HANDLE;
50         JSTaggedValue weakObj = JSTaggedValue(value.CreateAndGetWeakRef());
51         ASSERT(weakObj.IsWeak());
52         SetWeakObject(thread, weakObj);
53     }
54 
GetFromWeak() const55     JSTaggedValue GetFromWeak() const
56     {
57         JSTaggedValue weakObj = GetWeakObject();
58         if (!weakObj.IsUndefined()) {
59             return JSTaggedValue(weakObj.GetWeakReferent());
60         }
61         return weakObj;
62     }
63     static constexpr size_t WEAK_OBJECT_OFFSET = JSObject::SIZE;
64     ACCESSORS(WeakObject, WEAK_OBJECT_OFFSET, SIZE)
65 
66     DECL_VISIT_OBJECT_FOR_JS_OBJECT(JSObject, WEAK_OBJECT_OFFSET, SIZE)
67     DECL_DUMP()
68 };
69 } // namespace
70 #endif // ECMASCRIPT_JS_WEAK_REF_H