1 /*
2 * Copyright (c) 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/js_api/js_api_stack_iterator.h"
17
18 #include "ecmascript/builtins/builtins_errors.h"
19 #include "ecmascript/base/typed_array_helper-inl.h"
20 #include "ecmascript/base/typed_array_helper.h"
21 #include "ecmascript/containers/containers_errors.h"
22 #include "ecmascript/global_env.h"
23 #include "ecmascript/js_api/js_api_stack.h"
24 #include "ecmascript/js_hclass.h"
25 #include "ecmascript/object_factory.h"
26
27 namespace panda::ecmascript {
28 using BuiltinsBase = base::BuiltinsBase;
29 using ContainerError = containers::ContainerError;
30 using ErrorFlag = containers::ErrorFlag;
31 // StackIteratorPrototype%.next()
Next(EcmaRuntimeCallInfo * argv)32 JSTaggedValue JSAPIStackIterator::Next(EcmaRuntimeCallInfo *argv)
33 {
34 ASSERT(argv);
35 JSThread *thread = argv->GetThread();
36 [[maybe_unused]] EcmaHandleScope handleScope(thread);
37 JSHandle<JSTaggedValue> input(BuiltinsBase::GetThis(argv));
38
39 if (!input->IsJSAPIStackIterator()) {
40 JSTaggedValue error = ContainerError::BusinessError(thread, ErrorFlag::BIND_ERROR,
41 "The Symbol.iterator method cannot be bound");
42 THROW_NEW_ERROR_AND_RETURN_VALUE(thread, error, JSTaggedValue::Exception());
43 }
44 JSHandle<JSAPIStackIterator> iter(input);
45 JSHandle<JSTaggedValue> stack(thread, iter->GetIteratedStack());
46 const GlobalEnvConstants *globalConst = thread->GlobalConstants();
47 if (stack->IsUndefined()) {
48 return globalConst->GetUndefinedIterResult();
49 }
50 uint32_t index = iter->GetNextIndex();
51
52 uint32_t length = static_cast<uint32_t>((JSHandle<JSAPIStack>::Cast(stack))->GetSize() + 1);
53
54 RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
55
56 if (index + 1 > length) {
57 JSHandle<JSTaggedValue> undefinedHandle = globalConst->GetHandledUndefined();
58 iter->SetIteratedStack(thread, undefinedHandle);
59 return globalConst->GetUndefinedIterResult();
60 }
61 iter->SetNextIndex(index + 1);
62 JSHandle<JSTaggedValue> key(thread, JSTaggedValue(index));
63 JSHandle<JSTaggedValue> value(thread, JSHandle<JSAPIStack>::Cast(stack)->Get(index));
64 return JSIterator::CreateIterResultObject(thread, value, false).GetTaggedValue();
65 }
66 } // namespace panda::ecmascript
67