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_arraylist_iterator.h"
17
18 #include "ecmascript/containers/containers_errors.h"
19 #include "ecmascript/global_env.h"
20 #include "ecmascript/js_api/js_api_arraylist.h"
21
22 namespace panda::ecmascript {
23 using BuiltinsBase = base::BuiltinsBase;
24 using ContainerError = containers::ContainerError;
25 using ErrorFlag = containers::ErrorFlag;
26 // ArrayListIteratorPrototype%.next ( )
Next(EcmaRuntimeCallInfo * argv)27 JSTaggedValue JSAPIArrayListIterator::Next(EcmaRuntimeCallInfo *argv)
28 {
29 ASSERT(argv);
30 JSThread *thread = argv->GetThread();
31 [[maybe_unused]] EcmaHandleScope handleScope(thread);
32
33 JSHandle<JSTaggedValue> input(BuiltinsBase::GetThis(argv));
34 if (!input->IsJSAPIArrayListIterator()) {
35 JSTaggedValue error = ContainerError::BusinessError(thread, ErrorFlag::BIND_ERROR,
36 "The Symbol.iterator method cannot be bound");
37 THROW_NEW_ERROR_AND_RETURN_VALUE(thread, error, JSTaggedValue::Exception());
38 }
39 JSHandle<JSAPIArrayListIterator> iter(input);
40 JSHandle<JSTaggedValue> arrayList(thread, iter->GetIteratedArrayList(thread));
41
42 if (arrayList->IsUndefined()) {
43 JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
44 return env->GetUndefinedIteratorResult().GetTaggedValue();
45 }
46
47 uint32_t index = iter->GetNextIndex();
48 uint32_t length = 0;
49
50 if (arrayList->IsJSAPIArrayList()) {
51 length = JSHandle<JSAPIArrayList>(arrayList)->GetLength(thread).GetArrayLength();
52 }
53
54 if (index >= length) {
55 JSHandle<JSTaggedValue> undefinedHandle = thread->GlobalConstants()->GetHandledUndefined();
56 iter->SetIteratedArrayList(thread, undefinedHandle);
57 JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
58 return env->GetUndefinedIteratorResult().GetTaggedValue();
59 }
60
61 iter->SetNextIndex(index + 1);
62 JSHandle<JSTaggedValue> value(thread, JSHandle<JSAPIArrayList>::Cast(arrayList)->Get(thread, index));
63
64 return JSIterator::CreateIterResultObject(thread, value, false).GetTaggedValue();
65 }
66 } // namespace panda::ecmascript
67