1/*
2 * Copyright (c) 2021-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#include "ecmascript/builtins/builtins_weak_set.h"
17#include "ecmascript/interpreter/interpreter.h"
18#include "ecmascript/js_function.h"
19#include "ecmascript/js_set_iterator.h"
20#include "ecmascript/js_weak_container.h"
21#include "ecmascript/linked_hash_table.h"
22
23namespace panda::ecmascript::builtins {
24JSTaggedValue BuiltinsWeakSet::WeakSetConstructor(EcmaRuntimeCallInfo *argv)
25{
26    ASSERT(argv);
27    BUILTINS_API_TRACE(argv->GetThread(), WeakSet, Constructor);
28    JSThread *thread = argv->GetThread();
29    [[maybe_unused]] EcmaHandleScope handleScope(thread);
30    ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
31    // 1.If NewTarget is undefined, throw a TypeError exception
32    JSHandle<JSTaggedValue> newTarget = GetNewTarget(argv);
33    if (newTarget->IsUndefined()) {
34        // throw type error
35        THROW_TYPE_ERROR_AND_RETURN(thread, "new target can't be undefined", JSTaggedValue::Exception());
36    }
37    // 2.Let weakset be OrdinaryCreateFromConstructor(NewTarget, "%WeakSetPrototype%", «‍[[WeakSetData]]» ).
38    JSHandle<JSTaggedValue> constructor = GetConstructor(argv);
39    JSHandle<JSObject> obj = factory->NewJSObjectByConstructor(JSHandle<JSFunction>(constructor), newTarget);
40    // 3.returnIfAbrupt()
41    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
42    JSHandle<JSWeakSet> weakSet = JSHandle<JSWeakSet>::Cast(obj);
43    // 3.ReturnIfAbrupt(weakSet).
44    // 4.WeakSet set’s [[WeakSetData]] internal slot to a new empty List.
45    JSHandle<LinkedHashSet> linkedSet = LinkedHashSet::Create(thread);
46    weakSet->SetLinkedSet(thread, linkedSet);
47
48    // add data into weakset from iterable
49    // 5.If iterable is not present, let iterable be undefined.
50    // 6.If iterable is either undefined or null, let iter be undefined.
51    JSHandle<JSTaggedValue> iterable(GetCallArg(argv, 0));
52    // 8.If iter is undefined, return weakset
53    if (iterable->IsUndefined() || iterable->IsNull()) {
54        return weakSet.GetTaggedValue();
55    }
56    // Let adder be Get(weakset, "add").
57    JSHandle<JSTaggedValue> adderKey = thread->GlobalConstants()->GetHandledAddString();
58    JSHandle<JSTaggedValue> weakSetHandle(weakSet);
59    JSHandle<JSTaggedValue> adder = JSObject::GetProperty(thread, weakSetHandle, adderKey).GetValue();
60    // ReturnIfAbrupt(adder).
61    RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, adder.GetTaggedValue());
62    // If IsCallable(adder) is false, throw a TypeError exception
63    if (!adder->IsCallable()) {
64        THROW_TYPE_ERROR_AND_RETURN(thread, "adder is not callable", adder.GetTaggedValue());
65    }
66    // Let iter be GetIterator(iterable).
67    JSHandle<JSTaggedValue> iter(JSIterator::GetIterator(thread, iterable));
68
69    // ReturnIfAbrupt(iter).
70    RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, iter.GetTaggedValue());
71    // values in iterator_result may be a JSArray, values[0] = key values[1]=value, used valueIndex to get value from
72    // jsarray
73    JSHandle<JSTaggedValue> valueIndex(thread, JSTaggedValue(1));
74    JSHandle<JSTaggedValue> next = JSIterator::IteratorStep(thread, iter);
75    RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, next.GetTaggedValue());
76    JSMutableHandle<JSTaggedValue> status(thread, JSTaggedValue::Undefined());
77    JSHandle<JSTaggedValue> undefined = thread->GlobalConstants()->GetHandledUndefined();
78    while (!next->IsFalse()) {
79        // Let nextValue be IteratorValue(next).
80        JSHandle<JSTaggedValue> nextValue(JSIterator::IteratorValue(thread, next));
81        // ReturnIfAbrupt(nextValue).
82        RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, nextValue.GetTaggedValue());
83        EcmaRuntimeCallInfo *info =
84            EcmaInterpreter::NewRuntimeCallInfo(thread, adder, JSHandle<JSTaggedValue>(weakSet), undefined, 1);
85        RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
86        info->SetCallArg(nextValue.GetTaggedValue());
87        // Let status be Call(adder, weakset, «nextValue.[[value]]»).
88        JSFunction::Call(info);
89        // If status is an abrupt completion, return IteratorClose(iter, status).
90        if (thread->HasPendingException()) {
91            return JSIterator::IteratorCloseAndReturn(thread, iter);
92        }
93        // Let next be IteratorStep(iter).
94        next = JSIterator::IteratorStep(thread, iter);
95        // ReturnIfAbrupt(next).
96        RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, next.GetTaggedValue());
97    }
98    return weakSet.GetTaggedValue();
99}
100
101JSTaggedValue BuiltinsWeakSet::Add(EcmaRuntimeCallInfo *argv)
102{
103    ASSERT(argv);
104    BUILTINS_API_TRACE(argv->GetThread(), WeakSet, Add);
105    JSThread *thread = argv->GetThread();
106    [[maybe_unused]] EcmaHandleScope handleScope(thread);
107    JSHandle<JSTaggedValue> self = GetThis(argv);
108
109    // 2.If Type(S) is not Object, throw a TypeError exception.
110    // 3.If S does not have a [[WeakSetData]] internal slot, throw a TypeError exception.
111    if (!self->IsJSWeakSet()) {
112        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSWeakSet", JSTaggedValue::Exception());
113    }
114
115    JSHandle<JSTaggedValue> value(GetCallArg(argv, 0));
116    // 4.If CanBeHeldWeakly(value) is false, throw a TypeError exception.
117    if (!JSTaggedValue::CanBeHeldWeakly(thread, value)) {
118        THROW_TYPE_ERROR_AND_RETURN(thread, "invalid value used in weak set", JSTaggedValue::Exception());
119    }
120
121    JSHandle<JSWeakSet> weakSet(self);
122    JSWeakSet::Add(thread, weakSet, value);
123    return weakSet.GetTaggedValue();
124}
125
126JSTaggedValue BuiltinsWeakSet::Delete(EcmaRuntimeCallInfo *argv)
127{
128    ASSERT(argv);
129    BUILTINS_API_TRACE(argv->GetThread(), WeakSet, Delete);
130    JSThread *thread = argv->GetThread();
131    [[maybe_unused]] EcmaHandleScope handleScope(thread);
132    JSHandle<JSTaggedValue> self = GetThis(argv);
133    // 2.If Type(S) is not Object, throw a TypeError exception.
134    // 3.If S does not have a [[WeakSetData]] internal slot, throw a TypeError exception.
135    if (!self->IsJSWeakSet()) {
136        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSWeakSet", JSTaggedValue::Exception());
137    }
138
139    JSHandle<JSWeakSet> weakSet(self);
140    JSHandle<JSTaggedValue> value = GetCallArg(argv, 0);
141    // 4.If CanBeHeldWeakly(value) is false, return false.
142    if (!JSTaggedValue::CanBeHeldWeakly(thread, value)) {
143        GetTaggedBoolean(false);
144    }
145    return GetTaggedBoolean(JSWeakSet::Delete(thread, weakSet, value));
146}
147
148JSTaggedValue BuiltinsWeakSet::Has(EcmaRuntimeCallInfo *argv)
149{
150    ASSERT(argv);
151    BUILTINS_API_TRACE(argv->GetThread(), WeakSet, Has);
152    JSThread *thread = argv->GetThread();
153    [[maybe_unused]] EcmaHandleScope handleScope(thread);
154    JSHandle<JSTaggedValue> self = GetThis(argv);
155    // 2.If Type(S) is not Object, throw a TypeError exception.
156    // 3.If S does not have a [[SetData]] internal slot, throw a TypeError exception.
157    if (!self->IsJSWeakSet()) {
158        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSWeakSet", JSTaggedValue::Exception());
159    }
160    JSWeakSet *jsWeakSet = JSWeakSet::Cast(self.GetTaggedValue().GetTaggedObject());
161    JSHandle<JSTaggedValue> value = GetCallArg(argv, 0);
162    // 4.If CanBeHeldWeakly(value) is false, return false.
163    if (!JSTaggedValue::CanBeHeldWeakly(thread, value)) {
164        GetTaggedBoolean(false);
165    }
166    return GetTaggedBoolean(jsWeakSet->Has(thread, value.GetTaggedValue()));
167}
168}  // namespace panda::ecmascript::builtins
169