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