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 "plugins/ets/runtime/interop_js/interop_context.h"
17 #include "plugins/ets/runtime/interop_js/js_refconvert.h"
18
19 #include "plugins/ets/runtime/interop_js/js_refconvert_array.h"
20 #include "plugins/ets/runtime/interop_js/js_refconvert_function.h"
21
22 namespace ark::ets::interop::js {
23
IsFunctionClass(InteropCtx * ctx,Class * klass)24 static bool IsFunctionClass(InteropCtx *ctx, Class *klass)
25 {
26 if (ctx->IsFunctionalInterface(klass)) {
27 return true;
28 }
29 for (auto *itf : klass->GetInterfaces()) {
30 if (ctx->IsFunctionalInterface(itf)) {
31 return true;
32 }
33 }
34 return false;
35 }
36
JSRefConvertCreateImpl(InteropCtx * ctx,Class * klass)37 static std::unique_ptr<JSRefConvert> JSRefConvertCreateImpl(InteropCtx *ctx, Class *klass)
38 {
39 INTEROP_FATAL_IF(klass->IsClassClass());
40
41 if (klass->IsArrayClass()) {
42 auto type = klass->GetComponentType()->GetType().GetId();
43 if (type != panda_file::Type::TypeId::REFERENCE) {
44 ctx->Fatal(std::string("Unhandled primitive array: ") + utf::Mutf8AsCString(klass->GetDescriptor()));
45 }
46 return std::make_unique<JSRefConvertReftypeArray>(klass);
47 }
48
49 if (js_proxy::JSProxy::IsProxyClass(klass)) {
50 return ets_proxy::EtsClassWrapper::CreateJSRefConvertJSProxy(ctx, klass);
51 }
52
53 if (IsFunctionClass(ctx, klass)) {
54 return std::make_unique<JSRefConvertFunction>(klass);
55 }
56
57 return ets_proxy::EtsClassWrapper::CreateJSRefConvertEtsProxy(ctx, klass);
58 }
59
60 template <bool ALLOW_INIT>
JSRefConvertCreate(InteropCtx * ctx,Class * klass)61 JSRefConvert *JSRefConvertCreate(InteropCtx *ctx, Class *klass)
62 {
63 if (!CheckClassInitialized<ALLOW_INIT>(klass)) {
64 ASSERT(EtsCoroutine::GetCurrent()->HasPendingException());
65 return nullptr;
66 }
67 auto conv = JSRefConvertCreateImpl(ctx, klass);
68 if (UNLIKELY(conv == nullptr)) {
69 ctx->Fatal(std::string("Can't create convertor for ") + utf::Mutf8AsCString(klass->GetDescriptor()));
70 }
71 return ctx->GetRefConvertCache()->Insert(klass, std::move(conv));
72 }
73
74 template JSRefConvert *JSRefConvertCreate<false>(InteropCtx *ctx, Class *klass);
75 template JSRefConvert *JSRefConvertCreate<true>(InteropCtx *ctx, Class *klass);
76
77 } // namespace ark::ets::interop::js
78