From 02e4ae3c59cadd5f5ee2d69ea6c557cdc6a52d86 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Thu, 11 Sep 2025 17:33:07 +0300 Subject: [PATCH 01/14] Build scripts for libarkts Signed-off-by: Korobeinikov Evgeny Change-Id: I56f5a4b7be205e39fff6bb63257855a328f2aaa9 --- ets1.2/.gitignore | 5 +- ets1.2/BUILD.gn | 30 + ets1.2/common/package.json | 2 +- ets1.2/compat/package.json | 5 +- ets1.2/gn/command/npm_util.py | 17 +- ets1.2/gn/config/BUILDCONFIG.gn | 3 +- ets1.2/gn/script/npm.py | 14 +- ets1.2/interop/BUILD.gn | 40 +- ets1.2/interop/package.json | 9 +- ets1.2/interop/src/arkts/events.ts | 10 +- ets1.2/interop/src/cpp/DeserializerBase.h | 8 +- ets1.2/interop/src/cpp/SerializerBase.h | 369 +++--- ets1.2/interop/src/cpp/ani/convertors-ani.cc | 4 +- ets1.2/interop/src/cpp/common-interop.cc | 1060 +++++++++-------- ets1.2/interop/src/cpp/interop-logging.cc | 7 +- ets1.2/interop/src/cpp/jni/convertors-jni.cc | 9 +- ets1.2/interop/src/cpp/jsc/convertors-jsc.cc | 6 +- ets1.2/interop/src/cpp/napi/convertors-napi.h | 16 +- ets1.2/interop/src/cpp/ohos/hilog/log.h | 3 +- ets1.2/interop/src/cpp/ohos/oh_sk_log.cc | 5 +- ets1.2/interop/src/cpp/profiler.h | 5 +- ets1.2/interop/src/cpp/types/koala-types.h | 8 +- ets1.2/interop/src/cpp/vmloader.cc | 3 +- ets1.2/interop/src/interop/events.ts | 12 +- ets1.2/interop/tsconfig.json | 6 +- ets1.2/interop/ui2abcconfig.json | 4 +- ets1.2/libarkts/.clang-format | 107 -- ets1.2/libarkts/.mocharc.json | 2 +- ets1.2/libarkts/.prettierrc | 14 +- ets1.2/libarkts/BUILD.gn | 75 +- ets1.2/libarkts/arktsconfig-direct.json | 6 +- ets1.2/libarkts/gn/command/copy.py | 6 +- ets1.2/libarkts/gn/command/copy_file.py | 38 + ets1.2/libarkts/gn/command/copy_libs.py | 101 ++ ets1.2/libarkts/gn/command/gen_sdk.py | 120 ++ ets1.2/libarkts/gn/sdk_config.json | 69 ++ ets1.2/libarkts/native/meson_options.txt | 6 +- ets1.2/libarkts/native/src/bridges.cc | 116 +- ets1.2/libarkts/native/src/common.cc | 176 ++- ets1.2/libarkts/native/src/common.h | 41 +- ets1.2/libarkts/native/src/memoryTracker.cc | 67 +- ets1.2/libarkts/native/src/memoryTracker.h | 10 +- ets1.2/libarkts/package.json | 22 +- ets1.2/libarkts/playground/src/playground.cc | 152 --- ets1.2/libarkts/playground/src/util.h | 73 -- .../{rollup-lib.mjs => rollup.lib.mjs} | 0 ets1.2/package.json | 11 + ...a_integration.gni => koala_integration.gni | 4 +- 48 files changed, 1474 insertions(+), 1402 deletions(-) create mode 100644 ets1.2/BUILD.gn delete mode 100644 ets1.2/libarkts/.clang-format create mode 100755 ets1.2/libarkts/gn/command/copy_file.py create mode 100755 ets1.2/libarkts/gn/command/copy_libs.py create mode 100755 ets1.2/libarkts/gn/command/gen_sdk.py create mode 100644 ets1.2/libarkts/gn/sdk_config.json delete mode 100644 ets1.2/libarkts/playground/src/playground.cc delete mode 100644 ets1.2/libarkts/playground/src/util.h rename ets1.2/libarkts/{rollup-lib.mjs => rollup.lib.mjs} (100%) create mode 100644 ets1.2/package.json rename ets1.2/koala_integration.gni => koala_integration.gni (86%) diff --git a/ets1.2/.gitignore b/ets1.2/.gitignore index 652516b5c..332bff59d 100644 --- a/ets1.2/.gitignore +++ b/ets1.2/.gitignore @@ -24,7 +24,7 @@ cachegrind.out.* perf.data* /ui2abc/memo-plugin-ng/tests/out *.tsbuildinfo -ui2abc/libarkts/lib +libarkts/lib ui2abc/memo-plugin-ng/lib ui2abc/ui-plugins-ng/lib incremetal-cj/runtime/callsitekey @@ -34,7 +34,8 @@ tsconfig.tsbuildinfo .cache incremental/benchmarks/memo-benchmark/ets koala_mirror -koala_tools +ets1.2 out sdk koala_build.log +__pycache__ diff --git a/ets1.2/BUILD.gn b/ets1.2/BUILD.gn new file mode 100644 index 000000000..69adfae00 --- /dev/null +++ b/ets1.2/BUILD.gn @@ -0,0 +1,30 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (!defined(koala_mr)) { +# OHOS build tree workaround + import("../koala_integration.gni") +} +if (!koala_mr.is_rri) { + import("//build/ohos.gni") +} +import("${koala_mr.imports_prefix}/npm.gni") + +if (current_toolchain == host_toolchain) { + npm_install("install_all") { + outputs = [ + "$target_out_dir/install_all" + ] + project_path = rebase_path(".") + } +} \ No newline at end of file diff --git a/ets1.2/common/package.json b/ets1.2/common/package.json index 1f2687d5c..416d2f08b 100644 --- a/ets1.2/common/package.json +++ b/ets1.2/common/package.json @@ -26,7 +26,7 @@ "clean": "rimraf build", "test": "mocha", "test:coverage": "nyc mocha", - "build": "node ../../ui2abc/fast-arktsc --config ./ui2abcconfig.json --compiler ../tools/panda/arkts/ui2abc --link-name ./build/common.abc --simultaneous && PANDA_SDK_PATH=${PANDA_SDK_PATH:=../tools/panda/node_modules/@panda/sdk} ninja ${NINJA_OPTIONS} -f build/abc/build.ninja" + "build": "fast-arktsc --config ./ui2abcconfig.json --compiler ../incremental/tools/panda/arkts/ui2abc --link-name ./build/common.abc --simultaneous && PANDA_SDK_PATH=${PANDA_SDK_PATH:=../incremental/tools/panda/node_modules/@panda/sdk} ninja ${NINJA_OPTIONS} -f build/abc/build.ninja" }, "keywords": [], "dependencies": { diff --git a/ets1.2/compat/package.json b/ets1.2/compat/package.json index 3afa14ef6..ea5b824e7 100644 --- a/ets1.2/compat/package.json +++ b/ets1.2/compat/package.json @@ -25,10 +25,11 @@ "clean": "rimraf build dist", "compile": "ets-tsc -b .", "compile:release": "ets-tsc -b .", - "build": "node ../../ui2abc/fast-arktsc --config ./ui2abcconfig.json --compiler ../tools/panda/arkts/ui2abc --link-name ./build/compat.abc --simultaneous && PANDA_SDK_PATH=${PANDA_SDK_PATH:=../tools/panda/node_modules/@panda/sdk} ninja ${NINJA_OPTIONS} -f build/abc/build.ninja" + "build": "fast-arktsc --config ./ui2abcconfig.json --compiler ../incremental/tools/panda/arkts/ui2abc --link-name ./build/compat.abc --simultaneous && PANDA_SDK_PATH=${PANDA_SDK_PATH:=../incremental/tools/panda/node_modules/@panda/sdk} ninja ${NINJA_OPTIONS} -f build/abc/build.ninja" }, "keywords": [], - "dependencies": {}, + "dependencies": { + }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.20.0", "@typescript-eslint/parser": "^5.20.0", diff --git a/ets1.2/gn/command/npm_util.py b/ets1.2/gn/command/npm_util.py index c6b6809cf..ae7d0537c 100755 --- a/ets1.2/gn/command/npm_util.py +++ b/ets1.2/gn/command/npm_util.py @@ -51,20 +51,21 @@ if args.arklink_path: if args.stdlib_path: os.environ["ETS_STDLIB_PATH"] = args.stdlib_path -os.environ["PANDA_SDK_PATH"] = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../ui2abc/build/sdk") +os.environ["LIBARKTS_PATH"] = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../libarkts") +os.environ["PANDA_SDK_PATH"] = os.path.join(os.environ.get("LIBARKTS_PATH"), "sdk") -def run(npm_args, dir = None): +def run(args, dir = None): os.chdir(dir or project_path) if os.environ.get("KOALA_LOG_STDOUT"): - subprocess.run(["npm"] + npm_args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) + subprocess.run(["npm"] + args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) return - - result = subprocess.run(["npm"] + npm_args, capture_output=True, env=os.environ, text=True) - with open(koala_log, "a+") as f: - f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stdout) + result = subprocess.run(["npm"] + args, capture_output=True, env=os.environ, text=True) + with open(koala_log, "w+") as f: + f.write(f"npm args: {args}; project: {project_path}:\n" + result.stdout) if result.returncode != 0: - f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stderr) + f.write(f"npm args: {args}; project: {project_path}:\n" + result.stderr) + f.close() print(open(koala_log, "r").read()) raise Exception("npm failed") f.close() diff --git a/ets1.2/gn/config/BUILDCONFIG.gn b/ets1.2/gn/config/BUILDCONFIG.gn index 4497405f2..351a6601b 100644 --- a/ets1.2/gn/config/BUILDCONFIG.gn +++ b/ets1.2/gn/config/BUILDCONFIG.gn @@ -45,7 +45,8 @@ koala_mr = { scripts_path = "$root_path/gn/script" imports_prefix = "$root_path/gn/import" ui2abc_path = "$root_path/ui2abc" - libarkts_path = "$ui2abc_path/libarkts" + libarkts_path = "$root_path/libarkts" + fast_arktsc_path = "$root_path/fast-arktsc" incremental_path = "$root_path/incremental" panda_sdk_path = "$incremental_path/tools/panda/node_modules/@panda/sdk" es2panda_path = "$panda_sdk_path/ohos_arm64/include/tools/es2panda" diff --git a/ets1.2/gn/script/npm.py b/ets1.2/gn/script/npm.py index 09499e008..3d10297b7 100755 --- a/ets1.2/gn/script/npm.py +++ b/ets1.2/gn/script/npm.py @@ -54,18 +54,20 @@ if args.stdlib_path: os.environ["ETS_STDLIB_PATH"] = args.stdlib_path if args.panda_sdk_path: os.environ["PANDA_SDK_PATH"] = args.panda_sdk_path +# os.environ["PANDA_SDK_PATH"] = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../ui2abc/build/sdk") -def run(npm_args, dir = None): +def run(args, dir = None): os.chdir(dir or project_path) if os.environ.get("KOALA_LOG_STDOUT"): - subprocess.run(["npm"] + npm_args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) + subprocess.run(["npm"] + args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) return - result = subprocess.run(["npm"] + npm_args, capture_output=True, env=os.environ, text=True) - with open(koala_log, "a+") as f: - f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stdout) + result = subprocess.run(["npm"] + args, capture_output=True, env=os.environ, text=True) + with open(koala_log, "w+") as f: + f.write(f"npm args: {args}; project: {project_path}:\n" + result.stdout) if result.returncode != 0: - f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stderr) + f.write(f"npm args: {args}; project: {project_path}:\n" + result.stderr) + f.close() print(open(koala_log, "r").read()) raise Exception("npm failed") f.close() diff --git a/ets1.2/interop/BUILD.gn b/ets1.2/interop/BUILD.gn index c9d60bc58..578461acc 100644 --- a/ets1.2/interop/BUILD.gn +++ b/ets1.2/interop/BUILD.gn @@ -18,40 +18,38 @@ if (!defined(koala_mr)) { if (!koala_mr.is_rri) { import("//build/config/components/ets_frontend/ets2abc_config.gni") import("//build/ohos.gni") - import("//foundation/arkui/ace_engine/ace_config.gni") } import("${koala_mr.imports_prefix}/npm.gni") -if (current_toolchain == host_toolchain) { - npm_install("interop_install") { +if (defined(koala_mr.ui2abc_path)) { + npm_cmd("interop_abc") { outputs = [ - "$target_out_dir/interop_install" + "$target_out_dir/interop.abc" ] project_path = rebase_path(".") + run_tasks = [ "build" ] + + deps = [ + "${koala_mr.ui2abc_path}:ui2abc_base" + ] + + if (!koala_mr.is_rri) { + external_deps = [ + ets2abc_build_deps, + static_linker_build_deps + ] + } } } -npm_cmd("interop.abc") { +npm_cmd("interop_compile") { outputs = [ - "$target_out_dir/interop.abc" + "$target_out_dir/interop_compile" ] project_path = rebase_path(".") - run_tasks = [ "build" ] - - deps = [ - "${koala_mr.ui2abc_path}:ui2abc" - ] - - if (!koala_mr.is_rri) { - external_deps = [ - ets2abc_build_deps, - static_linker_build_deps - ] - } -} + run_tasks = [ "compile" ] -group("interop") { deps = [ - "${koala_mr.interop_path}:interop.abc" + "${koala_mr.root_path}:install_all(${host_toolchain})" ] } \ No newline at end of file diff --git a/ets1.2/interop/package.json b/ets1.2/interop/package.json index ba1d33e3d..5b756a4a5 100644 --- a/ets1.2/interop/package.json +++ b/ets1.2/interop/package.json @@ -6,7 +6,7 @@ "../incremental/build-common", "../incremental/compat", "../incremental/common", - "../ui2abc/fast-arktsc" + "../fast-arktsc" ], "files": [ "build/lib/src/**/*.js", @@ -43,7 +43,7 @@ "clean": "rimraf dist build types", "compile": "ets-tsc -b .", "compile:release": "ets-tsc -b .", - "build": "node ../ui2abc/fast-arktsc --config ./ui2abcconfig.json --compiler ../incremental/tools/panda/arkts/ui2abc --link-name ./build/interop.abc --simultaneous && ninja ${NINJA_OPTIONS} -f build/abc/build.ninja", + "build": "node ../fast-arktsc --config ./ui2abcconfig.json --compiler ../incremental/tools/panda/arkts/ui2abc --link-name ./build/interop.abc --simultaneous && ninja ${NINJA_OPTIONS} -f build/abc/build.ninja", "lint": "eslint src test components", "test:wasm:coverage": "NODE_OPTIONS='--conditions browser --no-experimental-fetch' nyc mocha", "test:wasm": "NODE_OPTIONS='--conditions browser --no-experimental-fetch' mocha", @@ -93,8 +93,7 @@ "compile:native-panda-with-hzvm-ohos-arm32": "npm run configure:native-panda-with-hzvm-ohos-arm32 && npm run compile:native-panda-ohos-arm32 && meson compile -C build-hzvm-ohos-arm32-vmloader && meson install -C build-hzvm-ohos-arm32-vmloader", "compile:kotlin:cinterop": "cd src/cpp/kotlin && cinterop -def cinterop-interop_native_module.def -pkg cinterop.interop_native_module -compiler-option -I. -o ../../../build/kotlin-interop/cinterop.interop_native_module", "compile:kotlin:kt": "konanc ./src/kotlin/*.kt -l ./build/kotlin-interop/cinterop.interop_native_module.klib -p library -o ./build/kotlin-interop/interop", - "compile:kotlin:interop": "rm -rf build/kotlin-interop && npm run compile:kotlin:cinterop && npm run compile:kotlin:kt", - "format:src:ts": "npx prettier --config .prettierrc --write \"./src/**/*.ts\"" + "compile:kotlin:interop": "rm -rf build/kotlin-interop && npm run compile:kotlin:cinterop && npm run compile:kotlin:kt" }, "keywords": [], "dependencies": { @@ -111,4 +110,4 @@ "source-map-support": "^0.5.21", "@koalaui/ets-tsc": "4.9.5-r5" } -} +} \ No newline at end of file diff --git a/ets1.2/interop/src/arkts/events.ts b/ets1.2/interop/src/arkts/events.ts index c6b3eddc3..2d57f84a0 100644 --- a/ets1.2/interop/src/arkts/events.ts +++ b/ets1.2/interop/src/arkts/events.ts @@ -76,17 +76,17 @@ function checkSingleEvent(): boolean { return true; } case CallbackEventKind.Event_HoldManagedResource: { - const resourceId = deserializer.readInt32() - ResourceHolder.instance().hold(resourceId) + const resourceId = deserializer.readInt32(); + ResourceHolder.instance().hold(resourceId); return true; } case CallbackEventKind.Event_ReleaseManagedResource: { - const resourceId = deserializer.readInt32() - ResourceHolder.instance().release(resourceId) + const resourceId = deserializer.readInt32(); + ResourceHolder.instance().release(resourceId); return true; } default: { - throw new Error(`Unknown callback event kind ${eventKind}`) + throw new Error(`Unknown callback event kind ${eventKind}`); } } } diff --git a/ets1.2/interop/src/cpp/DeserializerBase.h b/ets1.2/interop/src/cpp/DeserializerBase.h index 3c0119355..360ccaea6 100644 --- a/ets1.2/interop/src/cpp/DeserializerBase.h +++ b/ets1.2/interop/src/cpp/DeserializerBase.h @@ -541,9 +541,7 @@ inline void WriteToString(std::string* result, InteropFloat32 value) result->append(buf); #else std::string storage; - constexpr auto BUF_SIZE{20}; - static_assert(BUF_SIZE >= std::numeric_limits::max_digits10, "O-ou!"); - storage.resize(BUF_SIZE); + storage.resize(20); // We use to_chars() to avoid locale issues. auto rc = std::to_chars(storage.data(), storage.data() + storage.size(), value); storage.resize(rc.ptr - storage.data()); @@ -560,9 +558,7 @@ inline void WriteToString(std::string* result, InteropFloat64 value) result->append(buf); #else std::string storage; - constexpr auto BUF_SIZE{20}; - static_assert(BUF_SIZE >= std::numeric_limits::max_digits10, "O-ou!"); - storage.resize(BUF_SIZE); + storage.resize(20); // We use to_chars() to avoid locale issues. auto rc = std::to_chars(storage.data(), storage.data() + storage.size(), value); storage.resize(rc.ptr - storage.data()); diff --git a/ets1.2/interop/src/cpp/SerializerBase.h b/ets1.2/interop/src/cpp/SerializerBase.h index 52e2c942e..2b9e484e1 100644 --- a/ets1.2/interop/src/cpp/SerializerBase.h +++ b/ets1.2/interop/src/cpp/SerializerBase.h @@ -34,210 +34,235 @@ #define KOALA_NO_UNALIGNED_ACCESS 1 #endif -template -inline InteropRuntimeType runtimeType(const T &value) = delete; +template +inline InteropRuntimeType runtimeType(const T& value) = delete; -template <> -inline InteropRuntimeType runtimeType(const InteropCustomObject &value) { - return INTEROP_RUNTIME_OBJECT; +template<> +inline InteropRuntimeType runtimeType(const InteropCustomObject& value) +{ + return INTEROP_RUNTIME_OBJECT; } -template <> -inline InteropRuntimeType runtimeType(const InteropMaterialized &value) { - return INTEROP_RUNTIME_OBJECT; +template<> +inline InteropRuntimeType runtimeType(const InteropMaterialized& value) +{ + return INTEROP_RUNTIME_OBJECT; } -template <> inline InteropRuntimeType runtimeType(const InteropObject &value) { - return INTEROP_RUNTIME_OBJECT; +template<> +inline InteropRuntimeType runtimeType(const InteropObject& value) +{ + return INTEROP_RUNTIME_OBJECT; } class SerializerBase { private: - uint8_t *data; - uint32_t dataLength; - uint32_t position; - bool ownData; - CallbackResourceHolder *resourceHolder; - void resize(uint32_t newLength) { - ASSERT(ownData); - ASSERT(newLength > dataLength); - auto *newData = reinterpret_cast(malloc(newLength)); - if (!newData) { - INTEROP_FATAL("Cannot allocate memory"); - } - interop_memcpy(newData, newLength, data, position); - free(data); - data = newData; - dataLength = newLength; - } + uint8_t* data; + uint32_t dataLength; + uint32_t position; + bool ownData; + CallbackResourceHolder* resourceHolder; + void resize(uint32_t newLength) + { + ASSERT(ownData); + ASSERT(newLength > dataLength); + auto* newData = reinterpret_cast(malloc(newLength)); + if (!newData) { + INTEROP_FATAL("Cannot allocate memory"); + } + interop_memcpy(newData, newLength, data, position); + free(data); + data = newData; + dataLength = newLength; + } public: - SerializerBase(CallbackResourceHolder *resourceHolder = nullptr) - : position(0), ownData(true), resourceHolder(resourceHolder) { - constexpr auto DEFAULT_INITIAL_DATA_SIZE{256}; - this->dataLength = DEFAULT_INITIAL_DATA_SIZE; - this->data = reinterpret_cast(malloc(this->dataLength)); - if (!this->data) { - INTEROP_FATAL("Cannot allocate memory"); - } - } - - SerializerBase(uint8_t *data, uint32_t dataLength, - CallbackResourceHolder *resourceHolder = nullptr) - : data(data), dataLength(dataLength), position(0), ownData(false), - resourceHolder(resourceHolder) {} - - SerializerBase(KSerializerBuffer data, uint32_t dataLength, - CallbackResourceHolder *resourceHolder = nullptr) - : data(reinterpret_cast(data)), dataLength(dataLength), - position(0), ownData(false), resourceHolder(resourceHolder) {} - - virtual ~SerializerBase() { - if (ownData) { - free(data); - } - } - - SerializerBase(const SerializerBase &) = delete; - SerializerBase &operator=(const SerializerBase &) = delete; - - void *release() { - ownData = false; - return data; - } - int length() { return position; } - - inline void check(int more) { - if (position + more > dataLength) { - if (ownData) { - constexpr auto NUM_2{2}; - constexpr auto NUM_3{3}; - resize((position + more) * NUM_3 / NUM_2 + NUM_2); - } else { - INTEROP_FATAL("Buffer overrun: %d > %d\n", position + more, dataLength); - } - } - } - - void writeInt8(InteropInt8 value) { - check(1); - *(reinterpret_cast(data + position)) = value; - position += sizeof(value); - } - - void writeInt32(InteropInt32 value) { - check(sizeof(value)); + SerializerBase(CallbackResourceHolder* resourceHolder = nullptr) + : position(0), ownData(true), resourceHolder(resourceHolder) + { + this->dataLength = 256; + this->data = reinterpret_cast(malloc(this->dataLength)); + if (!this->data) { + INTEROP_FATAL("Cannot allocate memory"); + } + } + + SerializerBase(uint8_t* data, uint32_t dataLength, CallbackResourceHolder* resourceHolder = nullptr) + : data(data), dataLength(dataLength), position(0), ownData(false), resourceHolder(resourceHolder) + {} + + SerializerBase(KSerializerBuffer data, uint32_t dataLength, CallbackResourceHolder* resourceHolder = nullptr) + : data(reinterpret_cast(data)), dataLength(dataLength), position(0), ownData(false), + resourceHolder(resourceHolder) + {} + + virtual ~SerializerBase() + { + if (ownData) { + free(data); + } + } + + SerializerBase(const SerializerBase&) = delete; + SerializerBase& operator=(const SerializerBase&) = delete; + + void* release() + { + ownData = false; + return data; + } + int length() + { + return position; + } + + inline void check(int more) + { + if (position + more > dataLength) { + if (ownData) { + resize((position + more) * 3 / 2 + 2); + } else { + INTEROP_FATAL("Buffer overrun: %d > %d\n", position + more, dataLength); + } + } + } + + void writeInt8(InteropInt8 value) + { + check(1); + *(reinterpret_cast(data + position)) = value; + position += sizeof(value); + } + + void writeInt32(InteropInt32 value) + { + check(sizeof(value)); #ifdef KOALA_NO_UNALIGNED_ACCESS - interop_memcpy(data + position, dataLength, &value, sizeof(value)); + interop_memcpy(data + position, dataLength, &value, sizeof(value)); #else - *(reinterpret_cast(data + position)) = value; + *(reinterpret_cast(data + position)) = value; #endif - position += sizeof(value); - } + position += sizeof(value); + } - void writeInt64(InteropInt64 value) { - check(sizeof(value)); + void writeInt64(InteropInt64 value) + { + check(sizeof(value)); #ifdef KOALA_NO_UNALIGNED_ACCESS - interop_memcpy(data + position, dataLength, &value, sizeof(value)); + interop_memcpy(data + position, dataLength, &value, sizeof(value)); #else - *(reinterpret_cast(data + position)) = value; + *(reinterpret_cast(data + position)) = value; #endif - position += sizeof(value); - } + position += sizeof(value); + } - void writeUInt64(InteropUInt64 value) { - check(sizeof(value)); + void writeUInt64(InteropUInt64 value) + { + check(sizeof(value)); #ifdef KOALA_NO_UNALIGNED_ACCESS - interop_memcpy(data + position, dataLength, &value, sizeof(value)); + interop_memcpy(data + position, dataLength, &value, sizeof(value)); #else - *(reinterpret_cast(data + position)) = value; + *(reinterpret_cast(data + position)) = value; #endif - position += sizeof(value); - } + position += sizeof(value); + } - void writeFloat32(InteropFloat32 value) { - check(sizeof(value)); + void writeFloat32(InteropFloat32 value) + { + check(sizeof(value)); #ifdef KOALA_NO_UNALIGNED_ACCESS - interop_memcpy(data + position, dataLength, &value, sizeof(value)); + interop_memcpy(data + position, dataLength, &value, sizeof(value)); #else - *(reinterpret_cast(data + position)) = value; + *(reinterpret_cast(data + position)) = value; #endif - position += sizeof(value); - } + position += sizeof(value); + } - void writeFloat64(InteropFloat64 value) { - check(sizeof(value)); + void writeFloat64(InteropFloat64 value) + { + check(sizeof(value)); #ifdef KOALA_NO_UNALIGNED_ACCESS - interop_memcpy(data + position, dataLength, &value, sizeof(value)); + interop_memcpy(data + position, dataLength, &value, sizeof(value)); #else - *(reinterpret_cast(data + position)) = value; + *(reinterpret_cast(data + position)) = value; #endif - position += sizeof(value); - } + position += sizeof(value); + } - void writePointer(InteropNativePointer value) { - int64_t value64 = static_cast(reinterpret_cast(value)); - check(sizeof(value64)); + void writePointer(InteropNativePointer value) + { + int64_t value64 = static_cast(reinterpret_cast(value)); + check(sizeof(value64)); #ifdef KOALA_NO_UNALIGNED_ACCESS - interop_memcpy(data + position, dataLength, &value64, sizeof(value64)); + interop_memcpy(data + position, dataLength, &value64, sizeof(value64)); #else - *(reinterpret_cast(data + position)) = value64; + *(reinterpret_cast(data + position)) = value64; #endif - position += sizeof(value64); - } - - void writeNumber(InteropNumber value) { - writeInt8(value.tag); - if (value.tag == InteropTag::INTEROP_TAG_INT32) { - writeInt32(value.i32); - } else if (value.tag == InteropTag::INTEROP_TAG_FLOAT32) { - writeFloat32(value.f32); - } else { - INTEROP_FATAL("Unknown tag number"); - } - } - - void writeString(InteropString value) { - writeInt32(value.length + 1); - check(value.length + 1); - interop_strcpy(reinterpret_cast(data + position), dataLength, - value.chars); - position += value.length + 1; - } - - void writeBoolean(InteropBoolean value) { writeInt8(value); } - - void writeCallbackResource(const InteropCallbackResource resource) { - writeInt32(resource.resourceId); - writePointer(reinterpret_cast(resource.hold)); - writePointer(reinterpret_cast(resource.release)); - if (this->resourceHolder != nullptr) { - this->resourceHolder->holdCallbackResource(&resource); - } - } - - void writeObject(InteropObject any) { writeCallbackResource(any.resource); } - - void writeCustomObject(std::string type, InteropCustomObject value) { - // Improve: implement - } - - void writeBuffer(InteropBuffer interopBuffer) { - writeCallbackResource(interopBuffer.resource); - writePointer(static_cast(interopBuffer.data)); - writeInt64(interopBuffer.length); - } - - KInteropReturnBuffer toReturnBuffer() { - if (this->ownData) { - KInteropReturnBuffer buffer{ - this->length(), this->release(), - [](KNativePointer data, KInt length) { free(data); }}; - // Improve: fix memory issues - return buffer; - } else { - return {this->length(), this->data, nullptr}; - } - } + position += sizeof(value64); + } + + void writeNumber(InteropNumber value) + { + writeInt8(value.tag); + if (value.tag == InteropTag::INTEROP_TAG_INT32) { + writeInt32(value.i32); + } else if (value.tag == InteropTag::INTEROP_TAG_FLOAT32) { + writeFloat32(value.f32); + } else { + INTEROP_FATAL("Unknown tag number"); + } + } + + void writeString(InteropString value) + { + writeInt32(value.length + 1); + check(value.length + 1); + interop_strcpy(reinterpret_cast(data + position), dataLength, value.chars); + position += value.length + 1; + } + + void writeBoolean(InteropBoolean value) + { + writeInt8(value); + } + + void writeCallbackResource(const InteropCallbackResource resource) + { + writeInt32(resource.resourceId); + writePointer(reinterpret_cast(resource.hold)); + writePointer(reinterpret_cast(resource.release)); + if (this->resourceHolder != nullptr) { + this->resourceHolder->holdCallbackResource(&resource); + } + } + + void writeObject(InteropObject any) + { + writeCallbackResource(any.resource); + } + + void writeCustomObject(std::string type, InteropCustomObject value) + { + // Improve: implement + } + + void writeBuffer(InteropBuffer interopBuffer) + { + writeCallbackResource(interopBuffer.resource); + writePointer((void*)interopBuffer.data); + writeInt64(interopBuffer.length); + } + + KInteropReturnBuffer toReturnBuffer() + { + if (this->ownData) { + KInteropReturnBuffer buffer { this->length(), this->release(), + [](KNativePointer data, KInt length) { free(data); } }; + // Improve: fix memory issues + return buffer; + } else { + return { this->length(), this->data, nullptr }; + } + } }; -#endif // _SERIALIZER_BASE_H +#endif // _SERIALIZER_BASE_H \ No newline at end of file diff --git a/ets1.2/interop/src/cpp/ani/convertors-ani.cc b/ets1.2/interop/src/cpp/ani/convertors-ani.cc index e0a605744..c9ece6e17 100644 --- a/ets1.2/interop/src/cpp/ani/convertors-ani.cc +++ b/ets1.2/interop/src/cpp/ani/convertors-ani.cc @@ -15,7 +15,7 @@ #include "convertors-ani.h" #include -#include +#include #include "interop-types.h" #include "signatures.h" @@ -210,4 +210,4 @@ ani_env* getKoalaANIContext(void* hint) } else { return reinterpret_cast(hint); } -} +} \ No newline at end of file diff --git a/ets1.2/interop/src/cpp/common-interop.cc b/ets1.2/interop/src/cpp/common-interop.cc index ce615df1a..b367d4f6d 100644 --- a/ets1.2/interop/src/cpp/common-interop.cc +++ b/ets1.2/interop/src/cpp/common-interop.cc @@ -42,14 +42,14 @@ #if KOALA_INTEROP_PROFILER #include "profiler.h" -InteropProfiler *InteropProfiler::_instance = nullptr; +InteropProfiler* InteropProfiler::_instance = nullptr; #endif using std::string; #ifndef KOALA_INTEROP_MEM_ANALYZER -static std::atomic mallocCounter{0}; +static std::atomic mallocCounter { 0 }; #endif #if defined(KOALA_NAPI) || defined(KOALA_ANI) @@ -58,19 +58,19 @@ static std::atomic mallocCounter{0}; typedef void (*hold_t)(KInt); -KInteropBuffer impl_MaterializeBuffer(KNativePointer data, KLong length, - KInt resourceId, KNativePointer holdPtr, - KNativePointer releasePtr) { - auto hold = reinterpret_cast(holdPtr); - auto release = reinterpret_cast(releasePtr); - hold(resourceId); - return KInteropBuffer{length, data, resourceId, release}; +KInteropBuffer impl_MaterializeBuffer( + KNativePointer data, KLong length, KInt resourceId, KNativePointer holdPtr, KNativePointer releasePtr) +{ + auto hold = reinterpret_cast(holdPtr); + auto release = reinterpret_cast(releasePtr); + hold(resourceId); + return KInteropBuffer { length, data, resourceId, release }; } -KOALA_INTEROP_5(MaterializeBuffer, KInteropBuffer, KNativePointer, KLong, KInt, - KNativePointer, KNativePointer) +KOALA_INTEROP_5(MaterializeBuffer, KInteropBuffer, KNativePointer, KLong, KInt, KNativePointer, KNativePointer) -KNativePointer impl_GetNativeBufferPointer(KInteropBuffer buffer) { - return buffer.data; +KNativePointer impl_GetNativeBufferPointer(KInteropBuffer buffer) +{ + return buffer.data; } KOALA_INTEROP_1(GetNativeBufferPointer, KNativePointer, KInteropBuffer) @@ -80,27 +80,27 @@ KOALA_INTEROP_1(GetNativeBufferPointer, KNativePointer, KInteropBuffer) #include "etsapi.h" static struct { - ets_class clazz = nullptr; - ets_method method = nullptr; + ets_class clazz = nullptr; + ets_method method = nullptr; } g_koalaEtsNapiCallbackDispatcher; -bool setKoalaEtsNapiCallbackDispatcher(EtsEnv *etsEnv, ets_class clazz, - const char *dispatcherMethodName, - const char *dispactherMethodSig) { - g_koalaEtsNapiCallbackDispatcher.clazz = clazz; - etsEnv->NewGlobalRef(clazz); - ets_method method = etsEnv->GetStaticp_method(clazz, dispatcherMethodName, - dispactherMethodSig); - if (method == nullptr) { - return false; - } - g_koalaEtsNapiCallbackDispatcher.method = method; - return true; +bool setKoalaEtsNapiCallbackDispatcher( + EtsEnv* etsEnv, ets_class clazz, const char* dispatcherMethodName, const char* dispactherMethodSig) +{ + g_koalaEtsNapiCallbackDispatcher.clazz = clazz; + etsEnv->NewGlobalRef(clazz); + ets_method method = etsEnv->GetStaticp_method(clazz, dispatcherMethodName, dispactherMethodSig); + if (method == nullptr) { + return false; + } + g_koalaEtsNapiCallbackDispatcher.method = method; + return true; } -void getKoalaEtsNapiCallbackDispatcher(ets_class *clazz, ets_method *method) { - *clazz = g_koalaEtsNapiCallbackDispatcher.clazz; - *method = g_koalaEtsNapiCallbackDispatcher.method; +void getKoalaEtsNapiCallbackDispatcher(ets_class* clazz, ets_method* method) +{ + *clazz = g_koalaEtsNapiCallbackDispatcher.clazz; + *method = g_koalaEtsNapiCallbackDispatcher.method; } #endif @@ -108,717 +108,737 @@ void getKoalaEtsNapiCallbackDispatcher(ets_class *clazz, ets_method *method) { #ifdef KOALA_JNI #include "jni.h" static struct { - jclass clazz = nullptr; - jmethodID method = nullptr; + jclass clazz = nullptr; + jmethodID method = nullptr; } g_koalaJniCallbackDispatcher; -bool setKoalaJniCallbackDispatcher(JNIEnv *jniEnv, jclass clazz, - const char *dispatcherMethodName, - const char *dispactherMethodSig) { - g_koalaJniCallbackDispatcher.clazz = clazz; - jniEnv->NewGlobalRef(clazz); - jmethodID method = jniEnv->GetStaticMethodID(clazz, dispatcherMethodName, - dispactherMethodSig); - if (method == nullptr) { - return false; - } - g_koalaJniCallbackDispatcher.method = method; - return true; +bool setKoalaJniCallbackDispatcher( + JNIEnv* jniEnv, jclass clazz, const char* dispatcherMethodName, const char* dispactherMethodSig) +{ + g_koalaJniCallbackDispatcher.clazz = clazz; + jniEnv->NewGlobalRef(clazz); + jmethodID method = jniEnv->GetStaticMethodID(clazz, dispatcherMethodName, dispactherMethodSig); + if (method == nullptr) { + return false; + } + g_koalaJniCallbackDispatcher.method = method; + return true; } -void getKoalaJniCallbackDispatcher(jclass *clazz, jmethodID *method) { - *clazz = g_koalaJniCallbackDispatcher.clazz; - *method = g_koalaJniCallbackDispatcher.method; +void getKoalaJniCallbackDispatcher(jclass* clazz, jmethodID* method) +{ + *clazz = g_koalaJniCallbackDispatcher.clazz; + *method = g_koalaJniCallbackDispatcher.method; } #endif -KInt impl_StringLength(KNativePointer ptr) { - string *s = reinterpret_cast(ptr); - return s->length(); +KInt impl_StringLength(KNativePointer ptr) +{ + string* s = reinterpret_cast(ptr); + return s->length(); } KOALA_INTEROP_1(StringLength, KInt, KNativePointer) -void impl_StringData(KNativePointer ptr, KByte *bytes, KInt size) { - string *s = reinterpret_cast(ptr); - if (s) { - interop_memcpy(bytes, size, s->c_str(), size); - } +void impl_StringData(KNativePointer ptr, KByte* bytes, KInt size) +{ + string* s = reinterpret_cast(ptr); + if (s) { + interop_memcpy(bytes, size, s->c_str(), size); + } } -KOALA_INTEROP_V3(StringData, KNativePointer, KByte *, KInt) +KOALA_INTEROP_V3(StringData, KNativePointer, KByte*, KInt) #ifdef KOALA_JNI // For Java only yet. -KInteropBuffer impl_StringDataBytes(KVMContext vmContext, KNativePointer ptr) { - string *s = reinterpret_cast(ptr); - KInteropBuffer result = {(int32_t)s->length(), (void *)s->c_str()}; - return result; +KInteropBuffer impl_StringDataBytes(KVMContext vmContext, KNativePointer ptr) +{ + string* s = reinterpret_cast(ptr); + KInteropBuffer result = { (int32_t)s->length(), (void*)s->c_str() }; + return result; } KOALA_INTEROP_CTX_1(StringDataBytes, KInteropBuffer, KNativePointer) #endif -KNativePointer impl_StringMake(const KStringPtr &str) { - return new string(str.c_str()); +KNativePointer impl_StringMake(const KStringPtr& str) +{ + return new string(str.c_str()); } KOALA_INTEROP_1(StringMake, KNativePointer, KStringPtr) // For slow runtimes w/o fast encoders. -KInt impl_ManagedStringWrite(const KStringPtr &string, KSerializerBuffer buffer, - KInt bufferSize, KInt offset) { - interop_memcpy((uint8_t *)buffer + offset, bufferSize, string.c_str(), - string.length() + 1); - return string.length() + 1; +KInt impl_ManagedStringWrite(const KStringPtr& string, KSerializerBuffer buffer, KInt bufferSize, KInt offset) +{ + interop_memcpy((uint8_t*)buffer + offset, bufferSize, string.c_str(), string.length() + 1); + return string.length() + 1; } -KOALA_INTEROP_4(ManagedStringWrite, KInt, KStringPtr, KSerializerBuffer, KInt, - KInt) +KOALA_INTEROP_4(ManagedStringWrite, KInt, KStringPtr, KSerializerBuffer, KInt, KInt) -void stringFinalizer(string *ptr) { delete ptr; } -KNativePointer impl_GetStringFinalizer() { - return fnPtr(stringFinalizer); +void stringFinalizer(string* ptr) +{ + delete ptr; +} +KNativePointer impl_GetStringFinalizer() +{ + return fnPtr(stringFinalizer); } KOALA_INTEROP_0(GetStringFinalizer, KNativePointer) -void impl_InvokeFinalizer(KNativePointer obj, KNativePointer finalizer) { - auto finalizer_f = reinterpret_cast(finalizer); - finalizer_f(obj); +void impl_InvokeFinalizer(KNativePointer obj, KNativePointer finalizer) +{ + auto finalizer_f = reinterpret_cast(finalizer); + finalizer_f(obj); } KOALA_INTEROP_V2(InvokeFinalizer, KNativePointer, KNativePointer) -KInteropReturnBuffer impl_GetPtrVector(KNativePointer ptr) { - auto vector = reinterpret_cast *>(ptr); - return KInteropReturnBuffer::from(*vector, nullptr); +KInteropReturnBuffer impl_GetPtrVector(KNativePointer ptr) +{ + auto vector = reinterpret_cast*>(ptr); + return KInteropReturnBuffer::from(*vector, nullptr); } KOALA_INTEROP_1(GetPtrVector, KInteropReturnBuffer, KNativePointer) -KInt impl_GetPtrVectorSize(KNativePointer ptr) { - return reinterpret_cast *>(ptr)->size(); +KInt impl_GetPtrVectorSize(KNativePointer ptr) +{ + return reinterpret_cast*>(ptr)->size(); } KOALA_INTEROP_1(GetPtrVectorSize, KInt, KNativePointer) -KNativePointer impl_GetPtrVectorElement(KNativePointer ptr, KInt index) { - auto vector = reinterpret_cast *>(ptr); - auto element = vector->at(index); - return nativePtr(element); +KNativePointer impl_GetPtrVectorElement(KNativePointer ptr, KInt index) +{ + auto vector = reinterpret_cast*>(ptr); + auto element = vector->at(index); + return nativePtr(element); } KOALA_INTEROP_2(GetPtrVectorElement, KNativePointer, KNativePointer, KInt) -inline KUInt unpackUInt(const KByte *bytes) { - return (bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); +inline KUInt unpackUInt(const KByte* bytes) +{ + return (bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); } -KNativePointer impl_GetGroupedLog(KInt index) { - return new std::string(GetDefaultLogger()->getGroupedLog(index)); +KNativePointer impl_GetGroupedLog(KInt index) +{ + return new std::string(GetDefaultLogger()->getGroupedLog(index)); } KOALA_INTEROP_1(GetGroupedLog, KNativePointer, KInt) -void impl_StartGroupedLog(KInt index) { - GetDefaultLogger()->startGroupedLog(index); +void impl_StartGroupedLog(KInt index) +{ + GetDefaultLogger()->startGroupedLog(index); } KOALA_INTEROP_V1(StartGroupedLog, KInt) -void impl_StopGroupedLog(KInt index) { - GetDefaultLogger()->stopGroupedLog(index); +void impl_StopGroupedLog(KInt index) +{ + GetDefaultLogger()->stopGroupedLog(index); } KOALA_INTEROP_V1(StopGroupedLog, KInt) -void impl_AppendGroupedLog(KInt index, const KStringPtr &message) { - if (GetDefaultLogger()->needGroupedLog(index)) - GetDefaultLogger()->appendGroupedLog(index, message.c_str()); +void impl_AppendGroupedLog(KInt index, const KStringPtr& message) +{ + if (GetDefaultLogger()->needGroupedLog(index)) + GetDefaultLogger()->appendGroupedLog(index, message.c_str()); } KOALA_INTEROP_V2(AppendGroupedLog, KInt, KStringPtr) -void impl_PrintGroupedLog(KInt index) { +void impl_PrintGroupedLog(KInt index) +{ #ifdef KOALA_OHOS - LOGI("%" LOG_PUBLIC "s", GetDefaultLogger()->getGroupedLog(index)); + LOGI("%" LOG_PUBLIC "s", GetDefaultLogger()->getGroupedLog(index)); #else - fprintf(stdout, "%s\n", GetDefaultLogger()->getGroupedLog(index)); - fflush(stdout); + fprintf(stdout, "%s\n", GetDefaultLogger()->getGroupedLog(index)); + fflush(stdout); #endif } KOALA_INTEROP_V1(PrintGroupedLog, KInt) -int32_t callCallback(KVMContext context, int32_t methodId, uint8_t *argsData, - int32_t argsLength) { -#if KOALA_USE_NODE_VM || KOALA_USE_HZ_VM || KOALA_USE_PANDA_VM || \ - KOALA_USE_JAVA_VM || KOALA_CJ - KOALA_INTEROP_CALL_INT(context, methodId, argsLength, argsData); - return 0; +int32_t callCallback(KVMContext context, int32_t methodId, uint8_t* argsData, int32_t argsLength) +{ +#if KOALA_USE_NODE_VM || KOALA_USE_HZ_VM || KOALA_USE_PANDA_VM || KOALA_USE_JAVA_VM || KOALA_CJ + KOALA_INTEROP_CALL_INT(context, methodId, argsLength, argsData); + return 0; #else - return 0; + return 0; #endif } struct ForeignVMContext { - KVMContext vmContext; - int32_t (*callSync)(KVMContext vmContext, int32_t callback, uint8_t *data, - int32_t length); + KVMContext vmContext; + int32_t (*callSync)(KVMContext vmContext, int32_t callback, uint8_t* data, int32_t length); }; -typedef KInt (*LoadVirtualMachine_t)(KInt vmKind, const char *bootFiles, - const char *userFiles, - const char *libraryPath, - const struct ForeignVMContext *foreignVM); -typedef KNativePointer (*StartApplication_t)(const char *appUrl, - const char *appParams, - int32_t loopIterationr); +typedef KInt (*LoadVirtualMachine_t)(KInt vmKind, const char* bootFiles, const char* userFiles, const char* libraryPath, + const struct ForeignVMContext* foreignVM); +typedef KNativePointer (*StartApplication_t)(const char* appUrl, const char* appParams, int32_t loopIterationr); typedef KBoolean (*RunApplication_t)(const KInt arg0, const KInt arg1); -typedef const char *(*EmitEvent_t)(const KInt type, const KInt target, - const KInt arg0, const KInt arg1); -typedef void (*RestartWith_t)(const char *page); -typedef const char *(*LoadView_t)(const char *className, const char *params); - -void *getImpl(const char *path, const char *name) { - static void *lib = nullptr; - if (!lib && name) { - auto name = +typedef const char* (*EmitEvent_t)(const KInt type, const KInt target, const KInt arg0, const KInt arg1); +typedef void (*RestartWith_t)(const char* page); +typedef const char* (*LoadView_t)(const char* className, const char* params); + +void* getImpl(const char* path, const char* name) +{ + static void* lib = nullptr; + if (!lib && name) { + auto name = #ifndef KOALA_OHOS // dlopen on OHOS doesn't like paths - std::string(path) + "/" + + std::string(path) + "/" + #endif - libName("vmloader"); - lib = loadLibrary(name); - if (!lib) { - fprintf(stderr, "Ensure vmloader library %s was built\n", name.c_str()); + libName("vmloader"); + lib = loadLibrary(name); + if (!lib) { + fprintf(stderr, "Ensure vmloader library %s was built\n", name.c_str()); + } } - } - return findSymbol(lib, name); -} - -KInt impl_LoadVirtualMachine(KVMContext vmContext, KInt vmKind, - const KStringPtr &bootFiles, - const KStringPtr &userFiles, - const KStringPtr &libraryPath) { - const char *envClassPath = std::getenv("PANDA_CLASS_PATH"); - if (envClassPath) { - LOGI("CLASS PATH updated from env var PANDA_CLASS_PATH, %" LOG_PUBLIC "s", - envClassPath); - } - const char *bootFilesPath = envClassPath ? envClassPath : bootFiles.c_str(); - const char *nativeLibPath = envClassPath ? envClassPath : libraryPath.c_str(); - - static LoadVirtualMachine_t impl = nullptr; - if (!impl) - impl = reinterpret_cast( - getImpl(nativeLibPath, "LoadVirtualMachine")); - if (!impl) - KOALA_INTEROP_THROW_STRING(vmContext, "Cannot load VM", -1); - const ForeignVMContext foreignVM = {vmContext, &callCallback}; - return impl(vmKind, bootFilesPath, userFiles.c_str(), nativeLibPath, - &foreignVM); -} -KOALA_INTEROP_CTX_4(LoadVirtualMachine, KInt, KInt, KStringPtr, KStringPtr, - KStringPtr) - -KNativePointer impl_StartApplication(const KStringPtr &appUrl, - const KStringPtr &appParams, - KInt loopIterations) { - static StartApplication_t impl = nullptr; - if (!impl) - impl = reinterpret_cast( - getImpl(nullptr, "StartApplication")); - return impl(appUrl.c_str(), appParams.c_str(), loopIterations); + return findSymbol(lib, name); +} + +KInt impl_LoadVirtualMachine(KVMContext vmContext, KInt vmKind, const KStringPtr& bootFiles, + const KStringPtr& userFiles, const KStringPtr& libraryPath) +{ + const char* envClassPath = std::getenv("PANDA_CLASS_PATH"); + if (envClassPath) { + LOGI("CLASS PATH updated from env var PANDA_CLASS_PATH, %" LOG_PUBLIC "s", envClassPath); + } + const char* bootFilesPath = envClassPath ? envClassPath : bootFiles.c_str(); + const char* nativeLibPath = envClassPath ? envClassPath : libraryPath.c_str(); + + static LoadVirtualMachine_t impl = nullptr; + if (!impl) + impl = reinterpret_cast(getImpl(nativeLibPath, "LoadVirtualMachine")); + if (!impl) + KOALA_INTEROP_THROW_STRING(vmContext, "Cannot load VM", -1); + const ForeignVMContext foreignVM = { vmContext, &callCallback }; + return impl(vmKind, bootFilesPath, userFiles.c_str(), nativeLibPath, &foreignVM); +} +KOALA_INTEROP_CTX_4(LoadVirtualMachine, KInt, KInt, KStringPtr, KStringPtr, KStringPtr) + +KNativePointer impl_StartApplication(const KStringPtr& appUrl, const KStringPtr& appParams, KInt loopIterations) +{ + static StartApplication_t impl = nullptr; + if (!impl) + impl = reinterpret_cast(getImpl(nullptr, "StartApplication")); + return impl(appUrl.c_str(), appParams.c_str(), loopIterations); } KOALA_INTEROP_3(StartApplication, KNativePointer, KStringPtr, KStringPtr, KInt) -KBoolean impl_RunApplication(const KInt arg0, const KInt arg1) { - static RunApplication_t impl = nullptr; - if (!impl) - impl = - reinterpret_cast(getImpl(nullptr, "RunApplication")); - return impl(arg0, arg1); +KBoolean impl_RunApplication(const KInt arg0, const KInt arg1) +{ + static RunApplication_t impl = nullptr; + if (!impl) + impl = reinterpret_cast(getImpl(nullptr, "RunApplication")); + return impl(arg0, arg1); } KOALA_INTEROP_2(RunApplication, KBoolean, KInt, KInt) -KStringPtr impl_EmitEvent(KVMContext vmContext, KInt type, KInt target, - KInt arg0, KInt arg1) { - static EmitEvent_t impl = nullptr; - if (!impl) - impl = reinterpret_cast(getImpl(nullptr, "EmitEvent")); - const char *out = impl(type, target, arg0, arg1); - auto size = std::string(out).size(); - KStringPtr result(out, size, true); - return result; +KStringPtr impl_EmitEvent(KVMContext vmContext, KInt type, KInt target, KInt arg0, KInt arg1) +{ + static EmitEvent_t impl = nullptr; + if (!impl) + impl = reinterpret_cast(getImpl(nullptr, "EmitEvent")); + const char* out = impl(type, target, arg0, arg1); + auto size = std::string(out).size(); + KStringPtr result(out, size, true); + return result; } KOALA_INTEROP_CTX_4(EmitEvent, KStringPtr, KInt, KInt, KInt, KInt) -void impl_RestartWith(const KStringPtr &page) { - static RestartWith_t impl = nullptr; - if (!impl) - impl = reinterpret_cast(getImpl(nullptr, "RestartWith")); - impl(page.c_str()); +void impl_RestartWith(const KStringPtr& page) +{ + static RestartWith_t impl = nullptr; + if (!impl) + impl = reinterpret_cast(getImpl(nullptr, "RestartWith")); + impl(page.c_str()); } KOALA_INTEROP_V1(RestartWith, KStringPtr) #ifdef KOALA_ANI -KStringPtr impl_LoadView(const KStringPtr &className, - const KStringPtr ¶ms) { - static LoadView_t impl = nullptr; - if (!impl) - impl = reinterpret_cast(getImpl(nullptr, "LoadView")); - const char *result = impl(className.c_str(), params.c_str()); - return KStringPtr(result, interop_strlen(result), true); +KStringPtr impl_LoadView(const KStringPtr& className, const KStringPtr& params) +{ + static LoadView_t impl = nullptr; + if (!impl) + impl = reinterpret_cast(getImpl(nullptr, "LoadView")); + const char* result = impl(className.c_str(), params.c_str()); + return KStringPtr(result, interop_strlen(result), true); } KOALA_INTEROP_2(LoadView, KStringPtr, KStringPtr, KStringPtr) #endif // KOALA_ANI -KNativePointer impl_Malloc(KLong length) { - const auto ptr = static_cast(malloc(length)); - if (ptr == nullptr) { - INTEROP_FATAL("Memory allocation failed!"); - } +KNativePointer impl_Malloc(KLong length) +{ + const auto ptr = static_cast(malloc(length)); + if (ptr == nullptr) { + INTEROP_FATAL("Memory allocation failed!"); + } #ifndef KOALA_INTEROP_MEM_ANALYZER - mallocCounter.fetch_add(1, std::memory_order_release); + mallocCounter.fetch_add(1, std::memory_order_release); #endif - return ptr; + return ptr; } KOALA_INTEROP_DIRECT_1(Malloc, KNativePointer, KLong) -void malloc_finalize(KNativePointer data) { - if (data) { - free(data); +void malloc_finalize(KNativePointer data) +{ + if (data) { + free(data); #ifndef KOALA_INTEROP_MEM_ANALYZER - if (mallocCounter.fetch_sub(1, std::memory_order_release) == 0) { - INTEROP_FATAL("Double-free detected!"); - } + if (mallocCounter.fetch_sub(1, std::memory_order_release) == 0) { + INTEROP_FATAL("Double-free detected!"); + } #endif - } + } } -KNativePointer impl_GetMallocFinalizer() { - return reinterpret_cast(malloc_finalize); +KNativePointer impl_GetMallocFinalizer() +{ + return reinterpret_cast(malloc_finalize); } KOALA_INTEROP_DIRECT_0(GetMallocFinalizer, KNativePointer) -void impl_Free(KNativePointer data) { malloc_finalize(data); } +void impl_Free(KNativePointer data) +{ + malloc_finalize(data); +} KOALA_INTEROP_DIRECT_V1(Free, KNativePointer) -KInt impl_ReadByte(KNativePointer data, KLong index, KLong length) { - if (index >= length) - INTEROP_FATAL( - "impl_ReadByte: index %lld is equal or greater than length %lld", - (long long)index, (long long)length); - uint8_t *ptr = reinterpret_cast(data); - return ptr[index]; +KInt impl_ReadByte(KNativePointer data, KLong index, KLong length) +{ + if (index >= length) + INTEROP_FATAL( + "impl_ReadByte: index %lld is equal or greater than length %lld", (long long)index, (long long)length); + uint8_t* ptr = reinterpret_cast(data); + return ptr[index]; } KOALA_INTEROP_DIRECT_3(ReadByte, KInt, KNativePointer, KLong, KLong) -void impl_WriteByte(KNativePointer data, KInt index, KLong length, KInt value) { - if (index >= length) - INTEROP_FATAL( - "impl_WriteByte: index %lld is equal or greater than length %lld", - (long long)index, (long long)length); - uint8_t *ptr = reinterpret_cast(data); - ptr[index] = value; +void impl_WriteByte(KNativePointer data, KInt index, KLong length, KInt value) +{ + if (index >= length) + INTEROP_FATAL( + "impl_WriteByte: index %lld is equal or greater than length %lld", (long long)index, (long long)length); + uint8_t* ptr = reinterpret_cast(data); + ptr[index] = value; } KOALA_INTEROP_DIRECT_V4(WriteByte, KNativePointer, KLong, KLong, KInt) -void impl_CopyArray(KNativePointer data, KLong length, KByte *array) { - if (!array || !data) { - INTEROP_FATAL( - "CopyArray called with incorrect nullptr args (array, data):(%p, %p)", - array, data); - } +void impl_CopyArray(KNativePointer data, KLong length, KByte* array) +{ + if (!array || !data) { + INTEROP_FATAL("CopyArray called with incorrect nullptr args (array, data):(%p, %p)", array, data); + } - interop_memcpy(data, length, array, length); + interop_memcpy(data, length, array, length); } -KOALA_INTEROP_V3(CopyArray, KNativePointer, KLong, KByte *) +KOALA_INTEROP_V3(CopyArray, KNativePointer, KLong, KByte*) static const int API_KIND_MAX = 100; -static Callback_Caller_t g_callbackCaller[API_KIND_MAX] = {0}; -static Callback_Caller_Sync_t g_callbackCallerSync[API_KIND_MAX] = {0}; - -#define CHECK_VALID_API_KIND(apiKind) \ - if ((apiKind) < 0 || (apiKind) > API_KIND_MAX) \ - INTEROP_FATAL("Maximum api kind is %d, received %d", API_KIND_MAX, apiKind); -#define CHECK_HAS_CALLBACK_CALLER(apiKind, callbackCallers) \ - CHECK_VALID_API_KIND(apiKind); \ - if ((callbackCallers)[apiKind] == nullptr) \ - INTEROP_FATAL("Callback caller for api kind %d was not set", apiKind) -#define CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, callbackCallers) \ - CHECK_VALID_API_KIND(apiKind); \ - if ((callbackCallers)[apiKind] != nullptr) \ - INTEROP_FATAL("Callback caller for api kind %d already was set", apiKind); - -void setCallbackCaller(int apiKind, Callback_Caller_t callbackCaller) { - CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, g_callbackCaller); - g_callbackCaller[apiKind] = callbackCaller; -} - -void impl_CallCallback(KInt apiKind, KInt callbackKind, KSerializerBuffer args, - KInt argsSize) { - CHECK_HAS_CALLBACK_CALLER(apiKind, g_callbackCaller); - g_callbackCaller[apiKind](callbackKind, args, argsSize); +static Callback_Caller_t g_callbackCaller[API_KIND_MAX] = { 0 }; +static Callback_Caller_Sync_t g_callbackCallerSync[API_KIND_MAX] = { 0 }; + +#define CHECK_VALID_API_KIND(apiKind) \ + if ((apiKind) < 0 || (apiKind) > API_KIND_MAX) \ + INTEROP_FATAL("Maximum api kind is %d, received %d", API_KIND_MAX, apiKind); +#define CHECK_HAS_CALLBACK_CALLER(apiKind, callbackCallers) \ + CHECK_VALID_API_KIND(apiKind); \ + if ((callbackCallers)[apiKind] == nullptr) \ + INTEROP_FATAL("Callback caller for api kind %d was not set", apiKind) +#define CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, callbackCallers) \ + CHECK_VALID_API_KIND(apiKind); \ + if ((callbackCallers)[apiKind] != nullptr) \ + INTEROP_FATAL("Callback caller for api kind %d already was set", apiKind); + +void setCallbackCaller(int apiKind, Callback_Caller_t callbackCaller) +{ + CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, g_callbackCaller); + g_callbackCaller[apiKind] = callbackCaller; +} + +void impl_CallCallback(KInt apiKind, KInt callbackKind, KSerializerBuffer args, KInt argsSize) +{ + CHECK_HAS_CALLBACK_CALLER(apiKind, g_callbackCaller); + g_callbackCaller[apiKind](callbackKind, args, argsSize); } KOALA_INTEROP_V4(CallCallback, KInt, KInt, KSerializerBuffer, KInt) -void setCallbackCallerSync(int apiKind, - Callback_Caller_Sync_t callbackCallerSync) { - CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, g_callbackCallerSync); - g_callbackCallerSync[apiKind] = callbackCallerSync; +void setCallbackCallerSync(int apiKind, Callback_Caller_Sync_t callbackCallerSync) +{ + CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, g_callbackCallerSync); + g_callbackCallerSync[apiKind] = callbackCallerSync; } -void impl_CallCallbackSync(KVMContext vmContext, KInt apiKind, - KInt callbackKind, KSerializerBuffer args, - KInt argsSize) { - CHECK_HAS_CALLBACK_CALLER(apiKind, g_callbackCallerSync); - g_callbackCallerSync[apiKind](vmContext, callbackKind, args, argsSize); +void impl_CallCallbackSync(KVMContext vmContext, KInt apiKind, KInt callbackKind, KSerializerBuffer args, KInt argsSize) +{ + CHECK_HAS_CALLBACK_CALLER(apiKind, g_callbackCallerSync); + g_callbackCallerSync[apiKind](vmContext, callbackKind, args, argsSize); } KOALA_INTEROP_CTX_V4(CallCallbackSync, KInt, KInt, KSerializerBuffer, KInt) -void impl_CallCallbackResourceHolder(KNativePointer holder, KInt resourceId) { - reinterpret_cast(holder)(resourceId); +void impl_CallCallbackResourceHolder(KNativePointer holder, KInt resourceId) +{ + reinterpret_cast(holder)(resourceId); } KOALA_INTEROP_V2(CallCallbackResourceHolder, KNativePointer, KInt) -void impl_CallCallbackResourceReleaser(KNativePointer releaser, - KInt resourceId) { - reinterpret_cast(releaser)(resourceId); +void impl_CallCallbackResourceReleaser(KNativePointer releaser, KInt resourceId) +{ + reinterpret_cast(releaser)(resourceId); } KOALA_INTEROP_V2(CallCallbackResourceReleaser, KNativePointer, KInt) -KInt impl_CallForeignVM(KNativePointer foreignContextRaw, KInt function, - KSerializerBuffer data, KInt length) { - const ForeignVMContext *foreignContext = - (const ForeignVMContext *)foreignContextRaw; - // Improve: set actuall callbacks caller/holder/releaser. - /* - *(int64_t*)(data + 8) = impl_CallCallbackSync; - *(int64_t*)(data + 16) = 0; - *(int64_t*)(data + 24) = 0; */ - return foreignContext->callSync(foreignContext->vmContext, function, - reinterpret_cast(data), length); -} -KOALA_INTEROP_4(CallForeignVM, KInt, KNativePointer, KInt, KSerializerBuffer, - KInt) +KInt impl_CallForeignVM(KNativePointer foreignContextRaw, KInt function, KSerializerBuffer data, KInt length) +{ + const ForeignVMContext* foreignContext = (const ForeignVMContext*)foreignContextRaw; + // Improve: set actuall callbacks caller/holder/releaser. + /* + *(int64_t*)(data + 8) = impl_CallCallbackSync; + *(int64_t*)(data + 16) = 0; + *(int64_t*)(data + 24) = 0; */ + return foreignContext->callSync(foreignContext->vmContext, function, reinterpret_cast(data), length); +} +KOALA_INTEROP_4(CallForeignVM, KInt, KNativePointer, KInt, KSerializerBuffer, KInt) #ifdef KOALA_FOREIGN_NAPI KVMContext g_foreignVMContext = nullptr; #endif -void impl_SetForeignVMContext(KNativePointer foreignVMContextRaw) { +void impl_SetForeignVMContext(KNativePointer foreignVMContextRaw) +{ #ifdef KOALA_FOREIGN_NAPI - if (foreignVMContextRaw == nullptr) { - g_foreignVMContext = nullptr; - } else { - auto foreignContext = (const ForeignVMContext *)foreignVMContextRaw; - g_foreignVMContext = foreignContext->vmContext; - } + if (foreignVMContextRaw == nullptr) { + g_foreignVMContext = nullptr; + } else { + auto foreignContext = (const ForeignVMContext*)foreignVMContextRaw; + g_foreignVMContext = foreignContext->vmContext; + } #endif - /* supress unused private fields */ - (void)foreignVMContextRaw; + /* supress unused private fields */ + (void)foreignVMContextRaw; } KOALA_INTEROP_V1(SetForeignVMContext, KNativePointer) -#define QUOTE2(x) #x +#ifndef __QUOTE +#define __QUOTE(x) #x +#endif -#define QUOTE(x) QUOTE2(x) +#define QUOTE(x) __QUOTE(x) -void impl_NativeLog(const KStringPtr &str) { +void impl_NativeLog(const KStringPtr& str) +{ #ifdef KOALA_OHOS - LOGI("%{public}s: %{public}s", QUOTE(INTEROP_LIBRARY_NAME), str.c_str()); + LOGI("%{public}s: %{public}s", QUOTE(INTEROP_LIBRARY_NAME), str.c_str()); #else - fprintf(stdout, "%s: %s\n", QUOTE(INTEROP_LIBRARY_NAME), str.c_str()); - fflush(stdout); + fprintf(stdout, "%s: %s\n", QUOTE(INTEROP_LIBRARY_NAME), str.c_str()); + fflush(stdout); #endif } KOALA_INTEROP_V1(NativeLog, KStringPtr) -void resolveDeferred(KVMDeferred *deferred, uint8_t *argsData, - int32_t argsLength) { +void resolveDeferred(KVMDeferred* deferred, uint8_t* argsData, int32_t argsLength) +{ #ifdef KOALA_NAPI - auto status = - napi_call_threadsafe_function((napi_threadsafe_function)deferred->handler, - deferred, napi_tsfn_nonblocking); - if (status != napi_ok) - LOGE("cannot call thread-safe function; status=%d", status); - if (deferred->handler) { - napi_release_threadsafe_function( - (napi_threadsafe_function)deferred->handler, napi_tsfn_release); - deferred->handler = nullptr; - } + auto status = + napi_call_threadsafe_function((napi_threadsafe_function)deferred->handler, deferred, napi_tsfn_nonblocking); + if (status != napi_ok) + LOGE("cannot call thread-safe function; status=%d", status); + if (deferred->handler) { + napi_release_threadsafe_function((napi_threadsafe_function)deferred->handler, napi_tsfn_release); + deferred->handler = nullptr; + } #endif #ifdef KOALA_ANI - ani_vm *vm = (ani_vm *)deferred->context; - ani_env *env = nullptr; - ani_status status = vm->GetEnv(ANI_VERSION_1, &env); - if (env == nullptr || status != ANI_OK) { - status = vm->AttachCurrentThread(nullptr, ANI_VERSION_1, &env); + ani_vm* vm = (ani_vm*)deferred->context; + ani_env* env = nullptr; + ani_status status = vm->GetEnv(ANI_VERSION_1, &env); + if (env == nullptr || status != ANI_OK) { + status = vm->AttachCurrentThread(nullptr, ANI_VERSION_1, &env); + CHECK_ANI_FATAL(status); + } + ani_ref undef = nullptr; + status = env->GetUndefined(&undef); + CHECK_ANI_FATAL(status); + status = env->PromiseResolver_Resolve((ani_resolver)deferred->handler, undef); CHECK_ANI_FATAL(status); - } - ani_ref undef = nullptr; - status = env->GetUndefined(&undef); - CHECK_ANI_FATAL(status); - status = env->PromiseResolver_Resolve((ani_resolver)deferred->handler, undef); - CHECK_ANI_FATAL(status); #endif } -void rejectDeferred(KVMDeferred *deferred, const char *message) { +void rejectDeferred(KVMDeferred* deferred, const char* message) +{ #ifdef KOALA_NAPI - if (deferred->handler) { - napi_release_threadsafe_function( - (napi_threadsafe_function)deferred->handler, napi_tsfn_release); - deferred->handler = nullptr; - } + if (deferred->handler) { + napi_release_threadsafe_function((napi_threadsafe_function)deferred->handler, napi_tsfn_release); + deferred->handler = nullptr; + } #endif #ifdef KOALA_ANI - if (deferred->handler) { - ani_vm *vm = (ani_vm *)deferred->context; - ani_env *env = nullptr; - ani_status status = vm->GetEnv(ANI_VERSION_1, &env); - if (env == nullptr || status != ANI_OK) { - status = vm->AttachCurrentThread(nullptr, ANI_VERSION_1, &env); - CHECK_ANI_FATAL(status); + if (deferred->handler) { + ani_vm* vm = (ani_vm*)deferred->context; + ani_env* env = nullptr; + ani_status status = vm->GetEnv(ANI_VERSION_1, &env); + if (env == nullptr || status != ANI_OK) { + status = vm->AttachCurrentThread(nullptr, ANI_VERSION_1, &env); + CHECK_ANI_FATAL(status); + } + status = env->PromiseResolver_Reject((ani_resolver)deferred->handler, nullptr); + CHECK_ANI_FATAL(status); + deferred->handler = nullptr; } - status = - env->PromiseResolver_Reject((ani_resolver)deferred->handler, nullptr); - CHECK_ANI_FATAL(status); - deferred->handler = nullptr; - } #endif } #ifdef KOALA_NAPI -void resolveDeferredImpl(napi_env env, napi_value js_callback, - KVMDeferred *deferred, void *data) { - napi_value undefined = nullptr; - napi_get_undefined(env, &undefined); - auto status = - napi_resolve_deferred(env, (napi_deferred)deferred->context, undefined); - if (status != napi_ok) - LOGE("cannot resolve deferred; status=%d", status); - delete deferred; -} -#endif - -KVMDeferred *CreateDeferred(KVMContext vmContext, - KVMObjectHandle *promiseHandle) { - KVMDeferred *deferred = new KVMDeferred(); - deferred->resolve = resolveDeferred; - deferred->reject = rejectDeferred; +void resolveDeferredImpl(napi_env env, napi_value js_callback, KVMDeferred* deferred, void* data) +{ + napi_value undefined = nullptr; + napi_get_undefined(env, &undefined); + auto status = napi_resolve_deferred(env, (napi_deferred)deferred->context, undefined); + if (status != napi_ok) + LOGE("cannot resolve deferred; status=%d", status); + delete deferred; +} +#endif + +KVMDeferred* CreateDeferred(KVMContext vmContext, KVMObjectHandle* promiseHandle) +{ + KVMDeferred* deferred = new KVMDeferred(); + deferred->resolve = resolveDeferred; + deferred->reject = rejectDeferred; #ifdef KOALA_NAPI - // Improve: move to interop! - napi_env env = (napi_env)vmContext; - napi_value promise; - napi_value resourceName; - napi_create_string_utf8(env, "Async", sizeof("Async"), &resourceName); - auto status = - napi_create_promise(env, (napi_deferred *)&deferred->context, &promise); - if (status != napi_ok) - LOGE("cannot make a promise; status=%d", status); - status = napi_create_threadsafe_function( - env, nullptr, nullptr, resourceName, 0, 1, nullptr, nullptr, deferred, - (napi_threadsafe_function_call_js)resolveDeferredImpl, - (napi_threadsafe_function *)&deferred->handler); - if (status != napi_ok) - LOGE("cannot make threadsafe function; status=%d", status); - *promiseHandle = (KVMObjectHandle)promise; + // Improve: move to interop! + napi_env env = (napi_env)vmContext; + napi_value promise; + napi_value resourceName; + napi_create_string_utf8(env, "Async", sizeof("Async"), &resourceName); + auto status = napi_create_promise(env, (napi_deferred*)&deferred->context, &promise); + if (status != napi_ok) + LOGE("cannot make a promise; status=%d", status); + status = napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, nullptr, nullptr, deferred, + (napi_threadsafe_function_call_js)resolveDeferredImpl, (napi_threadsafe_function*)&deferred->handler); + if (status != napi_ok) + LOGE("cannot make threadsafe function; status=%d", status); + *promiseHandle = (KVMObjectHandle)promise; #endif #ifdef KOALA_ANI - ani_env *env = (ani_env *)vmContext; - ani_object promise = nullptr; - ani_resolver resolver = nullptr; - ani_status status = env->Promise_New(&resolver, &promise); - deferred->handler = resolver; - CHECK_ANI_FATAL(status); - *promiseHandle = (KVMObjectHandle)promise; - ani_vm *vm = nullptr; - status = env->GetVM(&vm); - CHECK_ANI_FATAL(status); - deferred->context = vm; + ani_env* env = (ani_env*)vmContext; + ani_object promise = nullptr; + ani_resolver resolver = nullptr; + ani_status status = env->Promise_New(&resolver, &promise); + deferred->handler = resolver; + CHECK_ANI_FATAL(status); + *promiseHandle = (KVMObjectHandle)promise; + ani_vm* vm = nullptr; + status = env->GetVM(&vm); + CHECK_ANI_FATAL(status); + deferred->context = vm; #endif - return deferred; + return deferred; } class KoalaWork { protected: - InteropVMContext vmContext; + InteropVMContext vmContext; #ifdef KOALA_FOREIGN_NAPI - KVMContext foreignVMContext; + KVMContext foreignVMContext; #endif - void *vmWork; - void *handle; - void (*execute)(void *handle); - void (*complete)(void *handle); + void* vmWork; + void* handle; + void (*execute)(void* handle); + void (*complete)(void* handle); public: - KoalaWork(InteropVMContext vmContext, InteropNativePointer handle, - void (*execute)(InteropNativePointer handle), - void (*complete)(InteropNativePointer handle)); - void Queue(); - void Execute(); - void Cancel(); - void Complete(); + KoalaWork(InteropVMContext vmContext, InteropNativePointer handle, void (*execute)(InteropNativePointer handle), + void (*complete)(InteropNativePointer handle)); + void Queue(); + void Execute(); + void Cancel(); + void Complete(); }; -static void DoQueue(void *handle) { ((KoalaWork *)handle)->Queue(); } -static void DoCancel(void *handle) { ((KoalaWork *)handle)->Cancel(); } +static void DoQueue(void* handle) +{ + ((KoalaWork*)handle)->Queue(); +} +static void DoCancel(void* handle) +{ + ((KoalaWork*)handle)->Cancel(); +} -InteropAsyncWork -koalaCreateWork(InteropVMContext vmContext, InteropNativePointer handle, - void (*execute)(InteropNativePointer handle), - void (*complete)(InteropNativePointer handle)) { - return { - new KoalaWork(vmContext, handle, execute, complete), - DoQueue, - DoCancel, - }; +InteropAsyncWork koalaCreateWork(InteropVMContext vmContext, InteropNativePointer handle, + void (*execute)(InteropNativePointer handle), void (*complete)(InteropNativePointer handle)) +{ + return { + new KoalaWork(vmContext, handle, execute, complete), + DoQueue, + DoCancel, + }; } -const InteropAsyncWorker *GetAsyncWorker() { - static InteropAsyncWorker worker = {koalaCreateWork}; - return &worker; +const InteropAsyncWorker* GetAsyncWorker() +{ + static InteropAsyncWorker worker = { koalaCreateWork }; + return &worker; } #if defined(KOALA_NAPI) -static void DoExecute(napi_env env, void *handle) { - ((KoalaWork *)handle)->Execute(); +static void DoExecute(napi_env env, void* handle) +{ + ((KoalaWork*)handle)->Execute(); } -static void DoComplete(napi_env env, napi_status status, void *handle) { - ((KoalaWork *)handle)->Complete(); +static void DoComplete(napi_env env, napi_status status, void* handle) +{ + ((KoalaWork*)handle)->Complete(); } KoalaWork::KoalaWork(InteropVMContext vmContext, InteropNativePointer handle, - void (*execute)(InteropNativePointer handle), - void (*complete)(InteropNativePointer handle)) - : vmContext(vmContext), handle(handle), execute(execute), - complete(complete) { - napi_env env = (napi_env)vmContext; - napi_value resourceName = nullptr; - napi_create_string_utf8(env, "KoalaAsyncOperation", NAPI_AUTO_LENGTH, - &resourceName); - napi_create_async_work(env, nullptr, resourceName, DoExecute, DoComplete, - this, (napi_async_work *)&vmWork); - /* supress unused private fields */ - (void)vmContext; - (void)vmWork; -} -void KoalaWork::Queue() { - napi_env env = (napi_env)vmContext; - napi_queue_async_work(env, (napi_async_work)vmWork); -} -void KoalaWork::Execute() { execute(handle); } -void KoalaWork::Cancel() { - napi_env env = (napi_env)vmContext; - napi_cancel_async_work(env, (napi_async_work)vmWork); -} -void KoalaWork::Complete() { - complete(handle); - delete this; + void (*execute)(InteropNativePointer handle), void (*complete)(InteropNativePointer handle)) + : vmContext(vmContext), handle(handle), execute(execute), complete(complete) +{ + napi_env env = (napi_env)vmContext; + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "KoalaAsyncOperation", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work(env, nullptr, resourceName, DoExecute, DoComplete, this, (napi_async_work*)&vmWork); + /* supress unused private fields */ + (void)vmContext; + (void)vmWork; +} +void KoalaWork::Queue() +{ + napi_env env = (napi_env)vmContext; + napi_queue_async_work(env, (napi_async_work)vmWork); +} +void KoalaWork::Execute() +{ + execute(handle); +} +void KoalaWork::Cancel() +{ + napi_env env = (napi_env)vmContext; + napi_cancel_async_work(env, (napi_async_work)vmWork); +} +void KoalaWork::Complete() +{ + complete(handle); + delete this; } #else #ifdef KOALA_FOREIGN_NAPI -static void DoExecute(napi_env env, void *handle) { - ((KoalaWork *)handle)->Execute(); +static void DoExecute(napi_env env, void* handle) +{ + ((KoalaWork*)handle)->Execute(); } -static void DoComplete(napi_env env, napi_status status, void *handle) { - ((KoalaWork *)handle)->Complete(); +static void DoComplete(napi_env env, napi_status status, void* handle) +{ + ((KoalaWork*)handle)->Complete(); } #endif KoalaWork::KoalaWork(InteropVMContext vmContext, InteropNativePointer handle, - void (*execute)(InteropNativePointer handle), - void (*complete)(InteropNativePointer handle)) - : vmContext(vmContext), handle(handle), execute(execute), - complete(complete) { + void (*execute)(InteropNativePointer handle), void (*complete)(InteropNativePointer handle)) + : vmContext(vmContext), handle(handle), execute(execute), complete(complete) +{ #ifdef KOALA_FOREIGN_NAPI - if (g_foreignVMContext == nullptr) - INTEROP_FATAL("Can not launch async work while foreign VM context is not " - "available. Please ensure you have " - "called SetForeignVMContext"); - foreignVMContext = g_foreignVMContext; - napi_env env = (napi_env)foreignVMContext; - napi_value resourceName = nullptr; - napi_create_string_utf8(env, "KoalaAsyncOperation", NAPI_AUTO_LENGTH, - &resourceName); - napi_create_async_work(env, nullptr, resourceName, DoExecute, DoComplete, - this, (napi_async_work *)&vmWork); -#endif - /* supress unused private fields */ - (void)vmContext; - (void)vmWork; -} -void KoalaWork::Queue() { + if (g_foreignVMContext == nullptr) + INTEROP_FATAL("Can not launch async work while foreign VM context is not available. Please ensure you have " + "called SetForeignVMContext"); + foreignVMContext = g_foreignVMContext; + napi_env env = (napi_env)foreignVMContext; + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "KoalaAsyncOperation", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work(env, nullptr, resourceName, DoExecute, DoComplete, this, (napi_async_work*)&vmWork); +#endif + /* supress unused private fields */ + (void)vmContext; + (void)vmWork; +} +void KoalaWork::Queue() +{ #ifdef KOALA_FOREIGN_NAPI - napi_env env = (napi_env)foreignVMContext; - napi_queue_async_work(env, (napi_async_work)vmWork); + napi_env env = (napi_env)foreignVMContext; + napi_queue_async_work(env, (napi_async_work)vmWork); #else - Execute(); - Complete(); + Execute(); + Complete(); #endif } -void KoalaWork::Execute() { execute(handle); } -void KoalaWork::Cancel() { +void KoalaWork::Execute() +{ + execute(handle); +} +void KoalaWork::Cancel() +{ #ifdef KOALA_FOREIGN_NAPI - napi_env env = (napi_env)foreignVMContext; - napi_cancel_async_work(env, (napi_async_work)vmWork); + napi_env env = (napi_env)foreignVMContext; + napi_cancel_async_work(env, (napi_async_work)vmWork); #else - INTEROP_FATAL("Cancelling async work is disabled for any VM except of Node"); + INTEROP_FATAL("Cancelling async work is disabled for any VM except of Node"); #endif } -void KoalaWork::Complete() { - complete(handle); - delete this; +void KoalaWork::Complete() +{ + complete(handle); + delete this; } #endif #if defined(KOALA_ETS_NAPI) || defined(KOALA_ANI) -KStringPtr impl_Utf8ToString(KVMContext vmContext, KNativePointer data, - KInt offset, KInt length) { - KStringPtr result((const char *)data + offset, length, false); - return result; +KStringPtr impl_Utf8ToString(KVMContext vmContext, KNativePointer data, KInt offset, KInt length) +{ + KStringPtr result((const char*)data + offset, length, false); + return result; } KOALA_INTEROP_CTX_3(Utf8ToString, KStringPtr, KNativePointer, KInt, KInt) #elif defined(KOALA_NAPI) || defined(KOALA_JNI) || defined(KOALA_CJ) // Allocate, so CTX versions. -KStringPtr impl_Utf8ToString(KVMContext vmContext, KByte *data, KInt offset, - KInt length) { - KStringPtr result((const char *)(data + offset), length, false); - return result; +KStringPtr impl_Utf8ToString(KVMContext vmContext, KByte* data, KInt offset, KInt length) +{ + KStringPtr result((const char*)(data + offset), length, false); + return result; } -KOALA_INTEROP_CTX_3(Utf8ToString, KStringPtr, KByte *, KInt, KInt) +KOALA_INTEROP_CTX_3(Utf8ToString, KStringPtr, KByte*, KInt, KInt) #endif #if defined(KOALA_NAPI) || defined(KOALA_ANI) -KStringPtr impl_RawUtf8ToString(KVMContext vmContext, KNativePointer data) { - auto string = (const char *)data; - KStringPtr result(string, interop_strlen(string), false); - return result; +KStringPtr impl_RawUtf8ToString(KVMContext vmContext, KNativePointer data) +{ + auto string = (const char*)data; + KStringPtr result(string, interop_strlen(string), false); + return result; } KOALA_INTEROP_CTX_1(RawUtf8ToString, KStringPtr, KNativePointer) #endif -#if defined(KOALA_NAPI) || defined(KOALA_JNI) || defined(KOALA_CJ) || \ - defined(KOALA_ETS_NAPI) || defined(KOALA_ANI) || defined(KOALA_KOTLIN) -KStringPtr impl_StdStringToString(KVMContext vmContext, - KNativePointer stringPtr) { - std::string *string = reinterpret_cast(stringPtr); - KStringPtr result(string->c_str(), string->size(), false); - return result; +#if defined(KOALA_NAPI) || defined(KOALA_JNI) || defined(KOALA_CJ) || defined(KOALA_ETS_NAPI) || defined(KOALA_ANI) || \ + defined(KOALA_KOTLIN) +KStringPtr impl_StdStringToString(KVMContext vmContext, KNativePointer stringPtr) +{ + std::string* string = reinterpret_cast(stringPtr); + KStringPtr result(string->c_str(), string->size(), false); + return result; } KOALA_INTEROP_CTX_1(StdStringToString, KStringPtr, KNativePointer) -KInteropReturnBuffer impl_RawReturnData(KVMContext vmContext, KInt v1, - KInt v2) { - void *data = new int8_t[v1]; - interop_memset(data, v1, v2, v1); - KInteropReturnBuffer buffer = { - v1, data, [](KNativePointer ptr, KInt) { delete[] (int8_t *)ptr; }}; - return buffer; +KInteropReturnBuffer impl_RawReturnData(KVMContext vmContext, KInt v1, KInt v2) +{ + void* data = new int8_t[v1]; + interop_memset(data, v1, v2, v1); + KInteropReturnBuffer buffer = { v1, data, [](KNativePointer ptr, KInt) { delete[](int8_t*) ptr; } }; + return buffer; } KOALA_INTEROP_CTX_2(RawReturnData, KInteropReturnBuffer, KInt, KInt) -KInteropNumber impl_IncrementNumber(KInteropNumber number) { - if (number.tag == 102) - number.i32++; - else - number.f32 += 1.f; - return number; +KInteropNumber impl_IncrementNumber(KInteropNumber number) +{ + if (number.tag == 102) + number.i32++; + else + number.f32 += 1.f; + return number; } KOALA_INTEROP_1(IncrementNumber, KInteropNumber, KInteropNumber) -void impl_ReportMemLeaks() { +void impl_ReportMemLeaks() +{ #ifndef KOALA_INTEROP_MEM_ANALYZER - const auto count = mallocCounter.load(std::memory_order_acquire); - if (count > 0) { - fprintf(stderr, "Memory leaks detected: %d blocks\n", count); - } else { - fprintf(stderr, "No memory leaks\n"); - } + const auto count = mallocCounter.load(std::memory_order_acquire); + if (count > 0) { + fprintf(stderr, "Memory leaks detected: %d blocks\n", count); + } else { + fprintf(stderr, "No memory leaks\n"); + } #endif } KOALA_INTEROP_V0(ReportMemLeaks) diff --git a/ets1.2/interop/src/cpp/interop-logging.cc b/ets1.2/interop/src/cpp/interop-logging.cc index cf8f809ba..4fb30b938 100644 --- a/ets1.2/interop/src/cpp/interop-logging.cc +++ b/ets1.2/interop/src/cpp/interop-logging.cc @@ -14,7 +14,7 @@ */ #include "interop-logging.h" -#include +#include #include #include @@ -59,8 +59,7 @@ void appendGroupedLog(int index, const char* str) const char* getGroupedLog(int index) { if (index < static_cast(groupedLogs.size())) { - // G.STD.04-CPP: Do not hold pointer returned from std::string c_str() method. - return std::move(groupedLogs[index]->log.c_str()); + return groupedLogs[index]->log.c_str(); } return ""; } @@ -97,4 +96,4 @@ extern "C" [[noreturn]] void InteropLogFatal(const char* format, ...) LOGE("FATAL: %s", buffer); va_end(args); abort(); -} +} \ No newline at end of file diff --git a/ets1.2/interop/src/cpp/jni/convertors-jni.cc b/ets1.2/interop/src/cpp/jni/convertors-jni.cc index 38071548f..7918b9721 100644 --- a/ets1.2/interop/src/cpp/jni/convertors-jni.cc +++ b/ets1.2/interop/src/cpp/jni/convertors-jni.cc @@ -30,16 +30,13 @@ const bool registerByOne = true; static bool registerNatives( JNIEnv* env, jclass clazz, const std::vector> impls) { - constexpr auto NUM_0{0}; - constexpr auto NUM_1{1}; - constexpr auto NUM_2{2}; size_t numMethods = impls.size(); JNINativeMethod* methods = new JNINativeMethod[numMethods]; bool result = true; for (size_t i = 0; i < numMethods; i++) { - methods[i].name = (char*)std::get(impls[i]).c_str(); - methods[i].signature = (char*)std::get(impls[i]).c_str(); - methods[i].fnPtr = std::get(impls[i]); + methods[i].name = (char*)std::get<0>(impls[i]).c_str(); + methods[i].signature = (char*)std::get<1>(impls[i]).c_str(); + methods[i].fnPtr = std::get<2>(impls[i]); if (registerByOne) { result &= (env->RegisterNatives(clazz, methods + i, 1) >= 0); if (env->ExceptionCheck()) { diff --git a/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc b/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc index 0c0b56f14..98d3a994e 100644 --- a/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc +++ b/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc @@ -156,14 +156,12 @@ static JSValueRef u64ToBigInt(JSContextRef context, uint64_t value) JSValueMakeNumber(context, (double)(value >> 32)), JSValueMakeNumber(context, (double)(value & 0xFFFFFFFF)), }; - contexpr auto ARGUMENT_COUNT{sizeof(parts)/sizeof(parts[0])}; - bigint = JSObjectCallAsFunction(context, bigIntFromParts, nullptr, ARGUMENT_COUNT, parts, nullptr); + bigint = JSObjectCallAsFunction(context, bigIntFromParts, nullptr, 2, parts, nullptr); #else char buffer[128] = { 0 }; interop_snprintf(buffer, sizeof(buffer) - 1, "%zun", static_cast(value)); JSStringRef script = JSStringCreateWithUTF8CString(buffer); - contexpr auto ARGUMENT_COUNT{0}; - bigint = JSEvaluateScript(context, script, nullptr, nullptr, ARGUMENT_COUNT, nullptr); + bigint = JSEvaluateScript(context, script, nullptr, nullptr, 0, nullptr); JSStringRelease(script); #endif return bigint; diff --git a/ets1.2/interop/src/cpp/napi/convertors-napi.h b/ets1.2/interop/src/cpp/napi/convertors-napi.h index 4e7518381..1bbd236c9 100644 --- a/ets1.2/interop/src/cpp/napi/convertors-napi.h +++ b/ets1.2/interop/src/cpp/napi/convertors-napi.h @@ -204,18 +204,14 @@ struct InteropTypeConverter { inline napi_typedarray_type getNapiType(KInt size) { - constexpr auto NUM_1{1}; - constexpr auto NUM_2{2}; - constexpr auto NUM_3{3}; - constexpr auto NUM_4{4}; switch (size) { - case NUM_1: + case 1: return napi_uint8_array; - case NUM_2: + case 2: return napi_uint16_array; - case NUM_4: + case 4: return napi_uint32_array; - case NUM_8: + case 8: return napi_biguint64_array; default: break; @@ -764,8 +760,8 @@ public: const std::vector>& getMethods(const std::string& module); }; -#define QUOTE2(x) #x -#define QUOTE(x) QUOTE2(x) +#define __QUOTE(x) #x +#define QUOTE(x) __QUOTE(x) #ifdef _MSC_VER #define MAKE_NODE_EXPORT(module, name) \ diff --git a/ets1.2/interop/src/cpp/ohos/hilog/log.h b/ets1.2/interop/src/cpp/ohos/hilog/log.h index 385385521..058d09e26 100644 --- a/ets1.2/interop/src/cpp/ohos/hilog/log.h +++ b/ets1.2/interop/src/cpp/ohos/hilog/log.h @@ -58,7 +58,8 @@ * * @since 8 */ -#include +#include +#include #ifdef __cplusplus extern "C" { diff --git a/ets1.2/interop/src/cpp/ohos/oh_sk_log.cc b/ets1.2/interop/src/cpp/ohos/oh_sk_log.cc index 254feea6b..c17e605f7 100644 --- a/ets1.2/interop/src/cpp/ohos/oh_sk_log.cc +++ b/ets1.2/interop/src/cpp/ohos/oh_sk_log.cc @@ -59,16 +59,15 @@ void oh_sk_file_log(oh_sk_log_type type, const char* msg, ...) size_t len = interop_strlen(KOALAUI_OHOS_LOG_ROOT) + 100; path = new char[len]; APPLY_LOG_FILE_PATTERN(path, len, lt, ms, getpid()); - mkdir(KOALAUI_OHOS_LOG_ROOT, ACCESSPERMS); + mkdir(KOALAUI_OHOS_LOG_ROOT, 0777); } std::unique_ptr file(fopen(path, "a"), fclose); if (!file) return; - constexpr auto US_IN_MS{1000}; fprintf(file.get(), "%02d-%02d %02d:%02d:%02d.%03lld %s koala: ", lt.tm_mon + 1, lt.tm_mday, lt.tm_hour, lt.tm_min, - lt.tm_sec, static_cast(ms.tv_usec / US_IN_MS), oh_sk_log_type_str(type)); + lt.tm_sec, ms.tv_usec / 1000, oh_sk_log_type_str(type)); va_list args; va_start(args, msg); diff --git a/ets1.2/interop/src/cpp/profiler.h b/ets1.2/interop/src/cpp/profiler.h index a99c8173d..2946c5d0e 100644 --- a/ets1.2/interop/src/cpp/profiler.h +++ b/ets1.2/interop/src/cpp/profiler.h @@ -72,9 +72,8 @@ public: auto ns = a.second.time; auto count = a.second.count; char buffer[1024]; - constexpr auto PERCENT_100{100}; interop_snprintf(buffer, sizeof buffer, "for %s[%lld]: %.01f%% (%lld)\n", a.first.c_str(), - (long long)count, (double)ns / total * PERCENT_100, (long long)ns); + (long long)count, (double)ns / total * 100.0, (long long)ns); result += buffer; }); return result; @@ -104,4 +103,4 @@ public: } }; -#endif // _KOALA_PROFILER_ +#endif // _KOALA_PROFILER_ \ No newline at end of file diff --git a/ets1.2/interop/src/cpp/types/koala-types.h b/ets1.2/interop/src/cpp/types/koala-types.h index 6cb7f2685..dc9102cd2 100644 --- a/ets1.2/interop/src/cpp/types/koala-types.h +++ b/ets1.2/interop/src/cpp/types/koala-types.h @@ -112,12 +112,11 @@ struct KStringPtrImpl { // Ignore old content. if (_value && _owned) free(_value); - auto memSize{static_cast(std::max(0, length + 1))}; - _value = reinterpret_cast(malloc(memSize)); + _value = reinterpret_cast(malloc(size + 1)); if (!_value) { INTEROP_FATAL("Cannot allocate memory"); } - _value[length] = 0; + _value[size] = 0; } void assign(const char* data) @@ -131,8 +130,7 @@ struct KStringPtrImpl { free(_value); if (data) { if (_owned) { - auto memSize{static_cast(std::max(0, length + 1))}; - _value = reinterpret_cast(malloc(memSize)); + _value = reinterpret_cast(malloc(length + 1)); if (!_value) { INTEROP_FATAL("Cannot allocate memory"); } diff --git a/ets1.2/interop/src/cpp/vmloader.cc b/ets1.2/interop/src/cpp/vmloader.cc index e9693e89d..e9f002aa1 100644 --- a/ets1.2/interop/src/cpp/vmloader.cc +++ b/ets1.2/interop/src/cpp/vmloader.cc @@ -309,8 +309,7 @@ static bool ResetErrorIfExists(ani_env* env) std::string makeLibPath(const char* sdkPath, const char* platform, const char* lib) { std::string result; - constexpr auto RESERVE_SIZE{255}; - result.reserve(RESERVE_SIZE); + result.reserve(255); if (sdkPath) { result.append(sdkPath).append("/"); } diff --git a/ets1.2/interop/src/interop/events.ts b/ets1.2/interop/src/interop/events.ts index 3f1096066..a1d12f6ec 100644 --- a/ets1.2/interop/src/interop/events.ts +++ b/ets1.2/interop/src/interop/events.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -75,17 +75,17 @@ function checkSingleEvent(): boolean { return true; } case CallbackEventKind.Event_HoldManagedResource: { - const resourceId = deserializer.readInt32() - ResourceHolder.instance().hold(resourceId) + const resourceId = deserializer.readInt32(); + ResourceHolder.instance().hold(resourceId); return true; } case CallbackEventKind.Event_ReleaseManagedResource: { - const resourceId = deserializer.readInt32() - ResourceHolder.instance().release(resourceId) + const resourceId = deserializer.readInt32(); + ResourceHolder.instance().release(resourceId); return true; } default: { - throw new Error(`Unknown callback event kind ${eventKind}`) + throw new Error(`Unknown callback event kind ${eventKind}`); } } } diff --git a/ets1.2/interop/tsconfig.json b/ets1.2/interop/tsconfig.json index afe382db7..5b4db2c9b 100644 --- a/ets1.2/interop/tsconfig.json +++ b/ets1.2/interop/tsconfig.json @@ -18,13 +18,13 @@ "baseUrl": ".", "types": ["node"], "paths": { - "@koalaui/common": ["../incremental/common/src"], + "@koalaui/common": ["../common/src"], "#common/wrappers/*": ["./src/napi/wrappers/*", "./src/wasm/wrappers/*"] } }, "include": ["src/interop/**/*", "src/napi/**/*", "src/wasm/**/*", "src/arkts/ResourceManager.ts"], "references": [ - { "path": "../incremental/compat" }, - { "path": "../incremental/common" } + { "path": "../compat" }, + { "path": "../common" } ] } diff --git a/ets1.2/interop/ui2abcconfig.json b/ets1.2/interop/ui2abcconfig.json index 68085b0e5..c5ca37908 100644 --- a/ets1.2/interop/ui2abcconfig.json +++ b/ets1.2/interop/ui2abcconfig.json @@ -4,8 +4,8 @@ "outDir": "./build/abc", "baseUrl": "./src/arkts", "paths": { - "@koalaui/compat": ["../../../incremental/compat/src/arkts"], - "@koalaui/common": ["../../../incremental/common/src"] + "@koalaui/compat": ["../../../compat/src/arkts"], + "@koalaui/common": ["../../../common/src"] } }, "include": ["./src/arkts/*.ts"] diff --git a/ets1.2/libarkts/.clang-format b/ets1.2/libarkts/.clang-format deleted file mode 100644 index 35740da59..000000000 --- a/ets1.2/libarkts/.clang-format +++ /dev/null @@ -1,107 +0,0 @@ ---- -Language: Cpp -AccessModifierOffset: -4 -AlignAfterOpenBracket: DontAlign -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false -AlignEscapedNewlines: Left -AlignOperands: true -AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: Empty -AllowShortIfStatementsOnASingleLine: Never -AllowShortLoopsOnASingleLine: false -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: Yes -BinPackArguments: true -BinPackParameters: true -BreakBeforeBraces: Custom -BraceWrapping: - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: true - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - AfterExternBlock: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false - SplitEmptyFunction: false - SplitEmptyRecord: false - SplitEmptyNamespace: false -BreakBeforeBinaryOperators: None -BreakBeforeInheritanceComma: false -BreakBeforeTernaryOperators: true -BreakConstructorInitializers: BeforeColon -BreakInheritanceList: BeforeColon -BreakStringLiterals: true -BreakAfterJavaFieldAnnotations: true -ColumnLimit: 120 -CommentPragmas: '^ IWYU pragma:' -QualifierAlignment: Leave -ReflowComments: true -CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: false -ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: false -DerivePointerAlignment: false -DisableFormat: false -FixNamespaceComments: true -ForEachMacros: - - foreach - - Q_FOREACH - - BOOST_FOREACH -IncludeBlocks: Regroup -IncludeCategories: - - Regex: '^"(base|core|elements|rendering|adapter|dsl|frameworks|resource|accessibility|bridge)/' - Priority: 3 - - Regex: '<*>' - Priority: 1 - - Regex: '.*' - Priority: 2 -IndentCaseLabels: true -IndentPPDirectives: None -IndentWidth: 4 -IndentWrappedFunctionNames: false -JavaScriptQuotes: Leave -JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: false -MacroBlockBegin: '' -MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -PenaltyBreakAssignment: 2 -PenaltyBreakBeforeFirstCallParameter: 39 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakString: 1000 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 80 -PointerAlignment: Left -SortIncludes: true -SortUsingDeclarations: true -SpaceAfterCStyleCast: false -SpaceAfterTemplateKeyword: false -SpaceBeforeAssignmentOperators: true -SpaceBeforeCpp11BracedList: true -SpaceBeforeCtorInitializerColon: true -SpaceBeforeParens: ControlStatements -SpaceBeforeRangeBasedForLoopColon: true -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 1 -SpacesInAngles: false -SpacesInCStyleCastParentheses: false -SpacesInContainerLiterals: true -SpacesInParentheses: false -SpacesInSquareBrackets: false -Standard: Cpp11 -TabWidth: 4 -UseTab: Never -... diff --git a/ets1.2/libarkts/.mocharc.json b/ets1.2/libarkts/.mocharc.json index 35222a70d..0753e33c1 100644 --- a/ets1.2/libarkts/.mocharc.json +++ b/ets1.2/libarkts/.mocharc.json @@ -5,7 +5,7 @@ "ts" ], "require": [ - "../../incremental/test-utils/scripts/register" + "../incremental/test-utils/scripts/register" ], "timeout": 20000 } diff --git a/ets1.2/libarkts/.prettierrc b/ets1.2/libarkts/.prettierrc index 0ac1c2234..e9e9c6fdb 100644 --- a/ets1.2/libarkts/.prettierrc +++ b/ets1.2/libarkts/.prettierrc @@ -1,8 +1,8 @@ -{ - "semi": true, - "singleQuote": true, - "tabWidth": 4, - "trailingComma": "es5", - "bracketSpacing": true, - "printWidth": 120 +{ + "semi": true, + "singleQuote": true, + "tabWidth": 4, + "trailingComma": "es5", + "bracketSpacing": true, + "printWidth": 120 } \ No newline at end of file diff --git a/ets1.2/libarkts/BUILD.gn b/ets1.2/libarkts/BUILD.gn index e7e7c8f3d..e2d1ce84b 100644 --- a/ets1.2/libarkts/BUILD.gn +++ b/ets1.2/libarkts/BUILD.gn @@ -13,14 +13,38 @@ if (!defined(koala_mr)) { # OHOS build tree workaround - import("../../../koala_integration.gni") + import("../../koala_integration.gni") } if (!koala_mr.is_rri) { import("//build/ohos.gni") + import("//build/config/components/ets_frontend/ets2abc_config.gni") } import("${koala_mr.imports_prefix}/npm.gni") -ws_node_modules_dir = koala_mr.ui2abc_path + "/node_modules" +ws_node_modules_dir = koala_mr.root_path + "/node_modules" + +if (!koala_mr.is_rri) { + action("ui2abc_panda_sdk") { + script = "gn/command/gen_sdk.py" + + outputs = [ + "$target_out_dir/panda-sdk" + ] + + external_deps = [ ets2abc_build_deps ] + external_deps += [ static_linker_build_deps ] + external_deps += [ "ets_frontend:libes2panda_public(${host_toolchain})" ] + + args = [ + "--config", rebase_path("gn/sdk_config.json"), + "--src", rebase_path("//"), + "--dist", rebase_path("./sdk"), + "--out-root", rebase_path(root_out_dir), + "--current-os", current_os, + "--current-cpu", current_cpu + ] + } +} if (koala_mr.is_rri) { npm_cmd("panda_sdk_reinstall") { @@ -28,13 +52,10 @@ if (koala_mr.is_rri) { run_tasks = [ "panda:sdk:reinstall" ] - deps = [ - ":libarkts_install" - ] } } else { - # Use from OHOS-SDK build (//build/ohos/sdk/ohos_sdk_description_std.json) +# Use from OHOS-SDK build (//build/ohos/sdk/ohos_sdk_description_std.json) ohos_copy("libarkts-sdk") { deps = [ ":libarkts_sdk_copy" ] @@ -42,8 +63,8 @@ if (koala_mr.is_rri) { outputs = [ target_out_dir + "/$target_name" ] module_source_dir = target_out_dir + "/$target_name" module_install_name = "" - subsystem_name = "arkui" - part_name = "ace_engine" + subsystem_name = "developtools" + part_name = "ace_ets2bundle" } } @@ -54,24 +75,22 @@ if (current_toolchain == host_toolchain) { assert(current_toolchain == host_toolchain, "must be executed with host_toolchain") if (koala_mr.is_rri) { deps = [ - ":libarkts_install", ":panda_sdk_reinstall" ] } else { deps = [ - "${koala_mr.ui2abc_path}:ui2abc_install_all(${host_toolchain})", - "${koala_mr.ui2abc_path}:ui2abc_panda_sdk" + ":ui2abc_panda_sdk" ] } + deps += [ + "${koala_mr.root_path}:install_all(${host_toolchain})" + ] + project_path = rebase_path(".") run_tasks = [ "regenerate" ] } - - npm_install("libarkts_install") { - project_path = rebase_path(".") - } } shared_library("es2panda_lib") { @@ -110,11 +129,10 @@ shared_library("es2panda_lib") { deps = [ ":regenerate_and_copy", ] - #sources += get_target_outputs(deps[1]) // FIXME: cannot find target - sources += [ "$target_out_dir/generated/native/bridges.cc" ] + #sources += get_target_outputs(deps[0]) // FIXME: cannot find target + sources += [ "$target_out_dir/bridges.cc" ] if (!koala_mr.is_rri) { - deps += [ "${koala_mr.ui2abc_path}:ui2abc_install($host_toolchain)" ] configs -= [ "//build/config/compiler:compiler" ] } @@ -260,24 +278,27 @@ action("es2panda_lib_copy") { # The generated bridges.cc doesn't exist at configure step and # should be linked with a target that creates it. As outputs cannot # point outside target_out_dir - make a copy target. -copy("regenerate_and_copy") { - sources = [ "${koala_mr.libarkts_path}/generated/native/bridges.cc", ] - outputs = [ "$target_out_dir/generated/native/bridges.cc", ] +action("regenerate_and_copy") { + script = "gn/command/copy_file.py" + outputs = [ "$target_out_dir/bridges.cc", ] + args = [ + rebase_path("generated/native/bridges.cc", root_build_dir), + rebase_path(outputs[0], root_build_dir) + ] deps = [ ":regenerate(${host_toolchain})", ] } # for //developtools/ace_ets2bundle npm_cmd("libarkts_compile") { deps = [ - "${koala_mr.interop_path}:interop_install(${host_toolchain})", - "${koala_mr.incremental_path}:incremental_install(${host_toolchain})", + "${koala_mr.interop_path}:interop_compile", ":regenerate(${host_toolchain})" ] outputs = [ "$target_out_dir/libarkts.js" ] project_path = rebase_path(".") - run_tasks = [ "compile:koala:interop", "compile:js" ] + run_tasks = [ "compile:js" ] } group("es2panda") { @@ -295,14 +316,16 @@ group("libarkts") { } action("libarkts_sdk_copy") { - script = "../gn/command/copy_libs.py" + script = "./gn/command/copy_libs.py" args = [ "--source_path", rebase_path(get_path_info(".", "abspath")), "--output_path", rebase_path("$target_gen_dir"), "--root_out_dir", rebase_path(root_out_dir), + "--current-os", current_os, + "--current-cpu", current_cpu ] outputs = [ "$target_gen_dir" ] deps = [ - "${koala_mr.ui2abc_path}:ui2abc" + ":es2panda" ] } diff --git a/ets1.2/libarkts/arktsconfig-direct.json b/ets1.2/libarkts/arktsconfig-direct.json index 4c082ac14..b75cdd434 100644 --- a/ets1.2/libarkts/arktsconfig-direct.json +++ b/ets1.2/libarkts/arktsconfig-direct.json @@ -3,9 +3,9 @@ "outDir": "./build/abc", "baseUrl": ".", "paths": { - "@koalaui/compat": [ "../../incremental/compat/src/arkts" ], - "#platform": [ "../../incremental/compat/src/arkts" ], - "@koalaui/common": [ "../../incremental/common/src" ], + "@koalaui/compat": [ "../../compat/src/arkts" ], + "#platform": [ "../../compat/src/arkts" ], + "@koalaui/common": [ "../../common/src" ], "@koalaui/runtime": [ "../../incremental/runtime/ets" ], "@koalaui/runtime/annotations": [ "../../incremental/runtime/annotations" ] }, diff --git a/ets1.2/libarkts/gn/command/copy.py b/ets1.2/libarkts/gn/command/copy.py index 54ac0975b..c42c37f14 100755 --- a/ets1.2/libarkts/gn/command/copy.py +++ b/ets1.2/libarkts/gn/command/copy.py @@ -19,8 +19,8 @@ import shutil import subprocess import sys -def library_ext(os_name, cpu_name): - if (os_name == 'mingw' and cpu_name == 'x86_64'): +def library_ext(os, cpu): + if (os == 'mingw' and cpu == 'x86_64'): return 'dll' return 'node' @@ -74,4 +74,4 @@ def main(): if __name__ == '__main__': - sys.exit(main()) + sys.exit(main()) \ No newline at end of file diff --git a/ets1.2/libarkts/gn/command/copy_file.py b/ets1.2/libarkts/gn/command/copy_file.py new file mode 100755 index 000000000..2bf645cfc --- /dev/null +++ b/ets1.2/libarkts/gn/command/copy_file.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import sys +import shutil + +def copy_files(source_path, dest_path): + try: + if not os.path.isdir(source_path): + os.makedirs(os.path.dirname(dest_path), exist_ok=True) + shutil.copy(source_path, dest_path) + else: + shutil.copytree(source_path, dest_path, dirs_exist_ok=True, symlinks=True) + except Exception as err: + raise Exception("Copy files failed. Error: " + str(err)) from err + +def main(): + dst = sys.argv[-1] + srcs = sys.argv[1:-1] + + for src in srcs: + copy_files(src, dst) + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/ets1.2/libarkts/gn/command/copy_libs.py b/ets1.2/libarkts/gn/command/copy_libs.py new file mode 100755 index 000000000..d9940ea79 --- /dev/null +++ b/ets1.2/libarkts/gn/command/copy_libs.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import shutil +import subprocess +import sys + +def get_compiler_name(os, cpu): + if (os == 'mingw' and cpu == 'x86_64'): + return 'mingw_x86_64' + return 'clang_x64' + +def library_ext(os, cpu): + if (os == 'mingw' and cpu == 'x86_64'): + return 'dll' + return 'node' + + +def copy_files(source_path, dest_path, is_file=False, throw_if_error=True): + if not os.path.exists(source_path): + if throw_if_error: + raise Exception(f"The path '{source_path}' does not exist.") + else: + print(f"The path '{source_path}' does not exist.") + return + + try: + if is_file: + os.makedirs(os.path.dirname(dest_path), exist_ok=True) + shutil.copy(source_path, dest_path) + else: + shutil.copytree(source_path, dest_path, dirs_exist_ok=True, + symlinks=True) + except Exception as err: + raise Exception("Copy files failed. Error: " + str(err)) from err + + +def run_cmd(cmd, execution_path=None): + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=execution_path) + stdout, stderr = proc.communicate(timeout=1000) + if proc.returncode != 0: + raise Exception(stderr.decode()) + + + +def copy_output(options): + + compiler = get_compiler_name(options.current_os, options.current_cpu) + library_extention = library_ext(options.current_os, options.current_cpu) + + from_path = options.root_out_dir + to_path = options.output_path + + head_dir, tail_dir = os.path.split(from_path) + if (tail_dir == compiler): + from_path = head_dir + + shutil.rmtree(to_path) + copy_files(os.path.join(options.source_path, 'lib'), + os.path.join(to_path, 'lib')) + + copy_files(os.path.join(from_path, f'{compiler}/libes2panda.{library_extention}'), + os.path.join(to_path, 'build/native/es2panda.node'), True) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--source_path', help='path to build system source') + parser.add_argument('--output_path', help='path to output') + parser.add_argument('--root_out_dir', help='path to root out') + parser.add_argument('--current-os', help='current OS') + parser.add_argument('--current-cpu', help='current CPU') + + options = parser.parse_args() + return options + + +def main(): + options = parse_args() + copy_output(options) + + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/ets1.2/libarkts/gn/command/gen_sdk.py b/ets1.2/libarkts/gn/command/gen_sdk.py new file mode 100755 index 000000000..f9bb97ea2 --- /dev/null +++ b/ets1.2/libarkts/gn/command/gen_sdk.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import shutil +import json +import argparse + +def load_config(config_file): + """Load the configuration file.""" + with open(config_file, 'r') as f: + config = json.load(f) + return config + +def get_compiler_type(os, cpu): + if (os == 'mingw' and cpu == 'x86_64'): + return 'mingw_x86_64' + return 'clang_x64' + +def replace_out_root(value, out_root, compiler_type): + """Replace $out_root in the string with the actual value.""" + return value.replace("$out_root", out_root).replace("$compiler_type", compiler_type) + +def validate_out_root(out_root, compiler_type): + head_out_root, tail_out_root = os.path.split(out_root) + if (tail_out_root == compiler_type): + return head_out_root + return out_root + + +def copy_files(config, src_base, dist_base, out_root, compiler_type, substitutions): + """Copy files or directories based on the configuration.""" + for mapping in config['file_mappings']: + # Replace $out_root + source = replace_out_root(mapping['source'], out_root, compiler_type) + destination = replace_out_root(mapping['destination'], out_root, compiler_type) + + if substitutions: + for key, val in substitutions.items(): + source = source.replace(key, val) + destination = destination.replace(key, val) + + # Build full paths + source = os.path.join(src_base, source) + destination = os.path.join(dist_base, destination) + + if not os.path.exists(source): + print(f"Source path does not exist: {source}") + continue + + # Create the destination directory if it doesn't exist + dest_dir = os.path.dirname(destination) if os.path.isfile(source) else destination + os.makedirs(dest_dir, exist_ok=True) + + # If it's a file, copy the file + if os.path.isfile(source): + try: + shutil.copy2(source, destination) + print(f"File copied: {source} -> {destination}") + except Exception as e: + print(f"Failed to copy file: {source} -> {destination}, error: {e}") + # If it's a directory, recursively copy the directory + elif os.path.isdir(source): + try: + shutil.copytree(source, destination, dirs_exist_ok=True) + print(f"Directory copied: {source} -> {destination}") + except Exception as e: + print(f"Failed to copy directory: {source} -> {destination}, error: {e}") + +def main(): + # Parse command-line arguments + parser = argparse.ArgumentParser(description="Copy files or directories.") + parser.add_argument("--config", required=True, help="Path to the configuration file.") + parser.add_argument("--src", required=True, help="Base source path.") + parser.add_argument("--dist", required=True, help="Base destination path.") + parser.add_argument("--out-root", required=True, help="Relative out directory to src, used to replace $out_root.") + parser.add_argument('--current-os', required=True, help='current OS') + parser.add_argument('--current-cpu', required=True, help='current CPU') + args = parser.parse_args() + + print(f"gen_sdk: current-cpu={args.current_cpu} current-os={args.current_os} out-root={args.out_root}") + + # Load the configuration + config = load_config(args.config) + + compiler_type = get_compiler_type(args.current_os, args.current_cpu) + + out_root = validate_out_root(args.out_root, compiler_type) + + substitutions = config.get('substitutions') + + if substitutions: + substitutions = substitutions.get(args.current_os) + if not substitutions: + raise Exception(f'Substitutions not found for current_os "{args.current_os}".') + + # Copy files or directories + copy_files(config, args.src, args.dist, out_root, compiler_type, substitutions) + + # Create package.json to pass SDK validation + content = """{ + "name": "@panda/sdk", + "version": "1.0.0" +}""" + with open(os.path.join(args.dist, "package.json"), "w") as file: + file.write(content) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/ets1.2/libarkts/gn/sdk_config.json b/ets1.2/libarkts/gn/sdk_config.json new file mode 100644 index 000000000..4ea6f1bca --- /dev/null +++ b/ets1.2/libarkts/gn/sdk_config.json @@ -0,0 +1,69 @@ +{ + + "substitutions": { + "linux": + { + "$host_tools": "linux_host_tools", + "$.exe": "", + "$.lib": ".so" + }, + "ohos": + { + "$host_tools": "linux_host_tools", + "$.exe": "", + "$.lib": ".so" + }, + "mingw": + { + "$host_tools": "windows_host_tools", + "$.exe": ".exe", + "$.lib": ".dll" + } + }, + "file_mappings": [ + { + "source": "$out_root/$compiler_type/arkcompiler/ets_frontend/es2panda$.exe", + "destination": "$host_tools/bin/es2panda$.exe" + }, + { + "source": "$out_root/$compiler_type/arkcompiler/ets_frontend/libes2panda_public$.lib", + "destination": "$host_tools/lib/libes2panda-public$.lib" + }, + { + "source": "$out_root/$compiler_type/arkcompiler/runtime_core/ark_link$.exe", + "destination": "$host_tools/bin/ark_link$.exe" + }, + { + "source": "$out_root/$compiler_type/arkcompiler/runtime_core/libarktsbase$.lib", + "destination": "$host_tools/lib/libarktsbase$.lib" + }, + { + "source": "arkcompiler/runtime_core/static_core/plugins/ets/stdlib/escompat", + "destination": "ets/stdlib/escompat" + }, + { + "source": "arkcompiler/runtime_core/static_core/plugins/ets/stdlib/std", + "destination": "ets/stdlib/std" + }, + { + "source": "arkcompiler/ets_frontend/ets2panda/public/es2panda_lib.h", + "destination": "$host_tools/include/tools/es2panda/public/es2panda_lib.h" + }, + { + "source": "$out_root/$compiler_type/gen/arkcompiler/ets_frontend/ets2panda/generated/es2panda_lib", + "destination": "$host_tools/include/tools/es2panda/generated/es2panda_lib" + }, + { + "source": "arkcompiler/ets_frontend/ets2panda/public/es2panda_lib.h", + "destination": "ohos_arm64/include/tools/es2panda/public/es2panda_lib.h" + }, + { + "source": "$out_root/$compiler_type/gen/arkcompiler/ets_frontend/ets2panda/generated/es2panda_lib", + "destination": "ohos_arm64/include/tools/es2panda/generated/es2panda_lib" + }, + { + "source": "$out_root/$compiler_type/gen/arkcompiler/runtime_core/static_core/plugins/ets/etsstdlib.abc", + "destination": "ets/etsstdlib.abc" + } + ] +} \ No newline at end of file diff --git a/ets1.2/libarkts/native/meson_options.txt b/ets1.2/libarkts/native/meson_options.txt index a59bde5ec..3ac86e9f8 100644 --- a/ets1.2/libarkts/native/meson_options.txt +++ b/ets1.2/libarkts/native/meson_options.txt @@ -14,19 +14,19 @@ option( 'node_modules_dir', type : 'string', - value : '../../node_modules/', + value : '../node_modules/', description : 'path to node_modules' ) option( 'interop_src_dir', type : 'string', - value : '../../../interop/src/cpp/', + value : '../../interop/src/cpp/', description : 'path to koala interop cpp files' ) option( 'panda_sdk_dir', type : 'string', - value : '../../../incremental/tools/panda/node_modules/@panda/sdk/', + value : '../../incremental/tools/panda/node_modules/@panda/sdk/', description : 'path to panda sdk' ) option( diff --git a/ets1.2/libarkts/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index d19ed1a88..63989bb45 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -13,11 +13,11 @@ * limitations under the License. */ -#include +#include "common.h" + #include #include - -#include "common.h" +#include /** XXX: If you add or remove methods that exist in C API, * please change generator/options.json5 accordingly. @@ -32,8 +32,7 @@ KNativePointer impl_AstNodeRebind(KNativePointer contextPtr, KNativePointer node } KOALA_INTEROP_2(AstNodeRebind, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_AnnotationAllowedAnnotations( - KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer returnLen) +KNativePointer impl_AnnotationAllowedAnnotations(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer returnLen) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -43,8 +42,7 @@ KNativePointer impl_AnnotationAllowedAnnotations( } KOALA_INTEROP_3(AnnotationAllowedAnnotations, KNativePointer, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_AnnotationAllowedAnnotationsConst( - KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer returnLen) +KNativePointer impl_AnnotationAllowedAnnotationsConst(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer returnLen) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -117,7 +115,7 @@ KOALA_INTEROP_2(SignatureFunction, KNativePointer, KNativePointer, KNativePointe static KNativePointer impl_ProgramExternalSources(KNativePointer contextPtr, KNativePointer instancePtr) { auto context = reinterpret_cast(contextPtr); - auto&& instance = reinterpret_cast(instancePtr); + auto&& instance = reinterpret_cast(instancePtr); std::size_t source_len = 0; auto external_sources = GetImpl()->ProgramExternalSources(context, instance, &source_len); return StageArena::cloneVector(external_sources, source_len); @@ -127,7 +125,7 @@ KOALA_INTEROP_2(ProgramExternalSources, KNativePointer, KNativePointer, KNativeP static KNativePointer impl_ProgramDirectExternalSources(KNativePointer contextPtr, KNativePointer instancePtr) { auto context = reinterpret_cast(contextPtr); - auto&& instance = reinterpret_cast(instancePtr); + auto&& instance = reinterpret_cast(instancePtr); std::size_t sourceLen = 0; auto externalSources = GetImpl()->ProgramDirectExternalSources(context, instance, &sourceLen); return new std::vector(externalSources, externalSources + sourceLen); @@ -137,7 +135,7 @@ KOALA_INTEROP_2(ProgramDirectExternalSources, KNativePointer, KNativePointer, KN static KNativePointer impl_ProgramSourceFilePath(KNativePointer contextPtr, KNativePointer instancePtr) { auto context = reinterpret_cast(contextPtr); - auto&& instance = reinterpret_cast(instancePtr); + auto&& instance = reinterpret_cast(instancePtr); auto&& result = GetImpl()->ProgramSourceFilePathConst(context, instance); return StageArena::strdup(result); } @@ -145,7 +143,7 @@ KOALA_INTEROP_2(ProgramSourceFilePath, KNativePointer, KNativePointer, KNativePo static KNativePointer impl_ExternalSourceName(KNativePointer instance) { - auto&& _instance_ = reinterpret_cast(instance); + auto&& _instance_ = reinterpret_cast(instance); auto&& result = GetImpl()->ExternalSourceName(_instance_); return StageArena::strdup(result); } @@ -153,16 +151,14 @@ KOALA_INTEROP_1(ExternalSourceName, KNativePointer, KNativePointer); static KNativePointer impl_ExternalSourcePrograms(KNativePointer instance) { - auto&& _instance_ = reinterpret_cast(instance); + auto&& _instance_ = reinterpret_cast(instance); std::size_t program_len = 0; auto programs = GetImpl()->ExternalSourcePrograms(_instance_, &program_len); return StageArena::cloneVector(programs, program_len); } KOALA_INTEROP_1(ExternalSourcePrograms, KNativePointer, KNativePointer); -KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, KInt importKinds, - KNativePointerArray specifiers, KUInt specifiersSequenceLength, KNativePointer source, KNativePointer program, - KInt importFlag) +KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, KInt importKinds, KNativePointerArray specifiers, KUInt specifiersSequenceLength, KNativePointer source, KNativePointer program, KInt importFlag) { const auto _context = reinterpret_cast(context); const auto _kinds = static_cast(importKinds); @@ -172,11 +168,9 @@ KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, KInt const auto _program = reinterpret_cast(program); const auto _importFlag = static_cast(importFlag); - return GetImpl()->ETSParserBuildImportDeclaration( - _context, _kinds, _specifiers, _specifiersSequenceLength, _source, _program, _importFlag); + return GetImpl()->ETSParserBuildImportDeclaration(_context, _kinds, _specifiers, _specifiersSequenceLength, _source, _program, _importFlag); } -KOALA_INTEROP_7(ETSParserBuildImportDeclaration, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt, - KNativePointer, KNativePointer, KInt) +KOALA_INTEROP_7(ETSParserBuildImportDeclaration, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt, KNativePointer, KNativePointer, KInt) KNativePointer impl_ETSParserGetImportPathManager(KNativePointer contextPtr) { @@ -187,15 +181,15 @@ KOALA_INTEROP_1(ETSParserGetImportPathManager, KNativePointer, KNativePointer); KInt impl_SourcePositionCol(KNativePointer context, KNativePointer instance) { - auto&& _context_ = reinterpret_cast(context); - auto&& _instance_ = reinterpret_cast(instance); + auto&& _context_ = reinterpret_cast(context); + auto&& _instance_ = reinterpret_cast(instance); return GetImpl()->SourcePositionCol(_context_, _instance_); } KOALA_INTEROP_2(SourcePositionCol, KInt, KNativePointer, KNativePointer); KNativePointer impl_ConfigGetOptions(KNativePointer config) { - const auto _config = reinterpret_cast(config); + const auto _config = reinterpret_cast(config); auto result = GetImpl()->ConfigGetOptions(_config); return (void*)result; } @@ -203,25 +197,21 @@ KOALA_INTEROP_1(ConfigGetOptions, KNativePointer, KNativePointer) KNativePointer impl_OptionsArkTsConfig(KNativePointer context, KNativePointer options) { - const auto _context = reinterpret_cast(context); - const auto _options = reinterpret_cast(options); + const auto _context = reinterpret_cast(context); + const auto _options = reinterpret_cast(options); auto result = GetImpl()->OptionsUtilArkTSConfigConst(_context, _options); return (void*)result; } KOALA_INTEROP_2(OptionsArkTsConfig, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_CreateCacheContextFromFile( - KNativePointer configPtr, KStringPtr& source_file_namePtr, KNativePointer globalContextPtr, KBoolean isExternal) -{ +KNativePointer impl_CreateCacheContextFromFile(KNativePointer configPtr, KStringPtr& source_file_namePtr, KNativePointer globalContextPtr, KBoolean isExternal) { auto config = reinterpret_cast(configPtr); auto globalContext = reinterpret_cast(globalContextPtr); return GetImpl()->CreateCacheContextFromFile(config, getStringCopy(source_file_namePtr), globalContext, isExternal); } KOALA_INTEROP_4(CreateCacheContextFromFile, KNativePointer, KNativePointer, KStringPtr, KNativePointer, KBoolean) -KNativePointer impl_CreateGlobalContext( - KNativePointer configPtr, KStringArray externalFileListPtr, KUInt fileNum, KBoolean LspUsage) -{ +KNativePointer impl_CreateGlobalContext(KNativePointer configPtr, KStringArray externalFileListPtr, KUInt fileNum, KBoolean LspUsage) { auto config = reinterpret_cast(configPtr); const int headerLen = 4; const char** files = StageArena::allocArray(fileNum); @@ -238,8 +228,7 @@ KNativePointer impl_CreateGlobalContext( } KOALA_INTEROP_4(CreateGlobalContext, KNativePointer, KNativePointer, KStringArray, KUInt, KBoolean) -void impl_DestroyGlobalContext(KNativePointer globalContextPtr) -{ +void impl_DestroyGlobalContext(KNativePointer globalContextPtr) { auto globalContext = reinterpret_cast(globalContextPtr); GetImpl()->DestroyGlobalContext(globalContext); } @@ -422,16 +411,16 @@ KNativePointer impl_CreateDiagnosticKind(KNativePointer context, KStringPtr& mes const auto _context = reinterpret_cast(context); const auto _message = getStringCopy(message); const auto _type = static_cast(type); - return const_cast(GetImpl()->CreateDiagnosticKind(_context, _message, _type)); + return const_cast(GetImpl()->CreateDiagnosticKind(_context, _message, _type)); } KOALA_INTEROP_3(CreateDiagnosticKind, KNativePointer, KNativePointer, KStringPtr, KInt) -KNativePointer impl_CreateDiagnosticInfo( - KNativePointer context, KNativePointer kind, KStringArray argsPtr, KInt argc, KNativePointer pos) +KNativePointer impl_CreateDiagnosticInfo(KNativePointer context, KNativePointer kind, KStringArray argsPtr, + KInt argc, KNativePointer pos) { const auto _context = reinterpret_cast(context); const auto _kind = reinterpret_cast(kind); - const auto _pos = reinterpret_cast(pos); + const auto _pos = reinterpret_cast(pos); const std::size_t headerLen = 4; const char** _args = new const char*[argc]; std::size_t position = headerLen; @@ -444,16 +433,16 @@ KNativePointer impl_CreateDiagnosticInfo( } return GetImpl()->CreateDiagnosticInfo(_context, _kind, _args, argc, _pos); } -KOALA_INTEROP_5( - CreateDiagnosticInfo, KNativePointer, KNativePointer, KNativePointer, KStringArray, KInt, KNativePointer) +KOALA_INTEROP_5(CreateDiagnosticInfo, KNativePointer, KNativePointer, KNativePointer, + KStringArray, KInt, KNativePointer) -KNativePointer impl_CreateSuggestionInfo(KNativePointer context, KNativePointer kind, KStringArray argsPtr, KInt argc, - KStringPtr& substitutionCode, KStringPtr& title, KNativePointer range) +KNativePointer impl_CreateSuggestionInfo(KNativePointer context, KNativePointer kind, KStringArray argsPtr, + KInt argc, KStringPtr& substitutionCode, KStringPtr& title, KNativePointer range) { const auto _context = reinterpret_cast(context); - const auto _kind = reinterpret_cast(kind); + const auto _kind = reinterpret_cast(kind); const auto _title = getStringCopy(title); - const auto _range = reinterpret_cast(range); + const auto _range = reinterpret_cast(range); const std::size_t headerLen = 4; const char** _args = new const char*[argc]; std::size_t position = headerLen; @@ -467,15 +456,15 @@ KNativePointer impl_CreateSuggestionInfo(KNativePointer context, KNativePointer const auto _substitutionCode = getStringCopy(substitutionCode); return GetImpl()->CreateSuggestionInfo(_context, _kind, _args, argc, _substitutionCode, _title, _range); } -KOALA_INTEROP_7(CreateSuggestionInfo, KNativePointer, KNativePointer, KNativePointer, KStringArray, KInt, KStringPtr, - KStringPtr, KNativePointer) +KOALA_INTEROP_7(CreateSuggestionInfo, KNativePointer, KNativePointer, KNativePointer, KStringArray, KInt, + KStringPtr, KStringPtr, KNativePointer) -void impl_LogDiagnostic( - KNativePointer context, KNativePointer kind, KStringArray argvPtr, KInt argc, KNativePointer pos) +void impl_LogDiagnostic(KNativePointer context, KNativePointer kind, KStringArray argvPtr, + KInt argc, KNativePointer pos) { - auto&& _context_ = reinterpret_cast(context); - auto&& _kind_ = reinterpret_cast(kind); - auto&& _pos_ = reinterpret_cast(pos); + auto&& _context_ = reinterpret_cast(context); + auto&& _kind_ = reinterpret_cast(kind); + auto&& _pos_ = reinterpret_cast(pos); const std::size_t headerLen = 4; const char** argv = new const char*[argc]; std::size_t position = headerLen; @@ -500,39 +489,42 @@ KNativePointer impl_AnnotationUsageIrPropertiesPtrConst(KNativePointer context, } KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); -KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr& outputDeclEts, KStringPtr& outputEts, - KBoolean exportAll, KBoolean isolated, KStringPtr& recordFile, KBoolean genAnnotations) +KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr &outputDeclEts, KStringPtr &outputEts, + KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations) { - auto context = reinterpret_cast(contextPtr); - return GetImpl()->GenerateTsDeclarationsFromContext( - context, outputDeclEts.data(), outputEts.data(), exportAll, isolated, recordFile.data(), genAnnotations); + auto context = reinterpret_cast(contextPtr); + return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), exportAll, isolated, recordFile.data(), genAnnotations); } -KOALA_INTEROP_7(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean, KBoolean, - KStringPtr, KBoolean) +KOALA_INTEROP_7(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean, KBoolean, KStringPtr, KBoolean) // Improve: simplify KNativePointer impl_CreateContextGenerateAbcForExternalSourceFiles( KNativePointer configPtr, KInt fileNamesCount, KStringArray fileNames) { - auto config = reinterpret_cast(configPtr); + auto config = reinterpret_cast(configPtr); const std::size_t headerLen = 4; - const char** argv = new const char*[static_cast(fileNamesCount)]; + const char **argv = + new const char *[static_cast(fileNamesCount)]; std::size_t position = headerLen; std::size_t strLen; for (std::size_t i = 0; i < static_cast(fileNamesCount); ++i) { strLen = unpackUInt(fileNames + position); position += headerLen; - argv[i] = strdup(std::string(reinterpret_cast(fileNames + position), strLen).c_str()); + argv[i] = strdup( + std::string(reinterpret_cast(fileNames + position), + strLen) + .c_str()); position += strLen; } - return GetImpl()->CreateContextGenerateAbcForExternalSourceFiles(config, fileNamesCount, argv); + return GetImpl()->CreateContextGenerateAbcForExternalSourceFiles( + config, fileNamesCount, argv); } KOALA_INTEROP_3(CreateContextGenerateAbcForExternalSourceFiles, KNativePointer, KNativePointer, KInt, KStringArray) KInt impl_GetCompilationMode(KNativePointer configPtr) { - auto _config = reinterpret_cast(configPtr); - auto _options = const_cast(GetImpl()->ConfigGetOptions(_config)); + auto _config = reinterpret_cast(configPtr); + auto _options = const_cast(GetImpl()->ConfigGetOptions(_config)); return GetImpl()->OptionsUtilGetCompilationModeConst(nullptr, _options); } KOALA_INTEROP_1(GetCompilationMode, KInt, KNativePointer) diff --git a/ets1.2/libarkts/native/src/common.cc b/ets1.2/libarkts/native/src/common.cc index 116fb4612..ec02f466b 100644 --- a/ets1.2/libarkts/native/src/common.cc +++ b/ets1.2/libarkts/native/src/common.cc @@ -14,17 +14,16 @@ */ #include -#include -#include -#include #include +#include #include +#include #include "interop-types.h" using std::string, std::cout, std::endl, std::vector; -es2panda_Impl* es2pandaImplementation = nullptr; +es2panda_Impl *es2pandaImplementation = nullptr; static thread_local StageArena currentArena; StageArena* StageArena::instance() @@ -80,26 +79,26 @@ void* StageArena::alloc(size_t size) } #ifdef KOALA_WINDOWS -#include -#define PLUGIN_DIR "windows_host_tools" -#define LIB_PREFIX "lib" -#define LIB_SUFFIX ".dll" + #include + #define PLUGIN_DIR "windows_host_tools" + #define LIB_PREFIX "lib" + #define LIB_SUFFIX ".dll" #endif #if defined(KOALA_LINUX) || defined(KOALA_MACOS) -#include + #include -#ifdef __x86_64__ -#define PLUGIN_DIR "linux_host_tools" -#else -#define PLUGIN_DIR "linux_arm64_host_tools" -#endif + #ifdef __x86_64__ + #define PLUGIN_DIR "linux_host_tools" + #else + #define PLUGIN_DIR "linux_arm64_host_tools" + #endif -#define LIB_PREFIX "lib" -#define LIB_SUFFIX ".so" + #define LIB_PREFIX "lib" + #define LIB_SUFFIX ".so" #endif -const char* DEFAULT_SDK_PATH = "../../../incremental/tools/panda/node_modules/@panda/sdk"; +const char* DEFAULT_SDK_PATH = "../../incremental/tools/panda/node_modules/@panda/sdk" ; const char* NAME = LIB_PREFIX "es2panda-public" LIB_SUFFIX; const char* LIB_ES2PANDA_PUBLIC = LIB_PREFIX "es2panda_public" LIB_SUFFIX; @@ -109,15 +108,15 @@ const string MODULE_SUFFIX = ".d.ets"; const string ARKUI = "arkui"; #ifdef KOALA_WINDOWS -const char* SEPARATOR = "\\"; + const char *SEPARATOR = "\\"; #else -const char* SEPARATOR = "/"; + const char *SEPARATOR = "/"; #endif -const char* LIB_DIR = "lib"; +const char *LIB_DIR = "lib"; static std::string ES2PANDA_LIB_PATH = ""; -std::string joinPath(vector& paths) +std::string joinPath(vector &paths) { std::string res; for (std::size_t i = 0; i < paths.size(); ++i) { @@ -130,21 +129,20 @@ std::string joinPath(vector& paths) return res; } -void impl_SetUpSoPath(KStringPtr& soPath) +void impl_SetUpSoPath(KStringPtr &soPath) { ES2PANDA_LIB_PATH = std::string(soPath.c_str()); } KOALA_INTEROP_V1(SetUpSoPath, KStringPtr); // Improve: simplify this -void* FindLibrary() -{ - void* res = nullptr; +void* FindLibrary() { + void *res = nullptr; std::vector pathArray; // find by SetUpSoPath if (!ES2PANDA_LIB_PATH.empty()) { - pathArray = { ES2PANDA_LIB_PATH, LIB_DIR, LIB_ES2PANDA_PUBLIC }; + pathArray = {ES2PANDA_LIB_PATH, LIB_DIR, LIB_ES2PANDA_PUBLIC}; res = loadLibrary(joinPath(pathArray)); if (res) { return res; @@ -154,7 +152,7 @@ void* FindLibrary() // find by set PANDA_SDK_PATH char* envValue = getenv("PANDA_SDK_PATH"); if (envValue) { - pathArray = { envValue, PLUGIN_DIR, LIB_DIR, NAME }; + pathArray = {envValue, PLUGIN_DIR, LIB_DIR, NAME}; res = loadLibrary(joinPath(pathArray)); if (res) { return res; @@ -162,14 +160,14 @@ void* FindLibrary() } // find by set LD_LIBRARY_PATH - pathArray = { LIB_ES2PANDA_PUBLIC }; + pathArray = {LIB_ES2PANDA_PUBLIC}; res = loadLibrary(joinPath(pathArray)); if (res) { return res; } // find by DEFAULT_SDK_PATH - pathArray = { DEFAULT_SDK_PATH, PLUGIN_DIR, LIB_DIR, NAME }; + pathArray = {DEFAULT_SDK_PATH, PLUGIN_DIR, LIB_DIR, NAME}; res = loadLibrary(joinPath(pathArray)); if (res) { return res; @@ -178,7 +176,7 @@ void* FindLibrary() return nullptr; } -es2panda_Impl* GetImplSlow() +es2panda_Impl *GetImplSlow() { if (es2pandaImplementation) { return es2pandaImplementation; @@ -193,7 +191,7 @@ es2panda_Impl* GetImplSlow() printf("no entry point"); abort(); } - es2pandaImplementation = reinterpret_cast(symbol)(ES2PANDA_LIB_VERSION); + es2pandaImplementation = reinterpret_cast(symbol)(ES2PANDA_LIB_VERSION); return es2pandaImplementation; } @@ -207,8 +205,7 @@ char* getStringCopy(KStringPtr& ptr) return StageArena::strdup(ptr.c_str() ? ptr.c_str() : ""); } -KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr) -{ +KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr) { const std::size_t headerLen = 4; const char** argv = StageArena::allocArray(argc); @@ -224,26 +221,30 @@ KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr) } KOALA_INTEROP_2(CreateConfig, KNativePointer, KInt, KStringArray) -KNativePointer impl_DestroyConfig(KNativePointer configPtr) -{ +KNativePointer impl_DestroyConfig(KNativePointer configPtr) { auto config = reinterpret_cast(configPtr); GetImpl()->DestroyConfig(config); return nullptr; } KOALA_INTEROP_1(DestroyConfig, KNativePointer, KNativePointer) -void impl_DestroyContext(KNativePointer contextPtr) -{ +void impl_DestroyContext(KNativePointer contextPtr) { auto context = reinterpret_cast(contextPtr); GetImpl()->DestroyContext(context); StageArena::instance()->cleanup(); } KOALA_INTEROP_V1(DestroyContext, KNativePointer) -KNativePointer impl_UpdateCallExpression(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer calleePtr, - KNativePointerArray argumentsPtr, KInt argumentsLen, KNativePointer typeParamsPtr, KBoolean optionalT, - KBoolean trailingCommaT) -{ +KNativePointer impl_UpdateCallExpression( + KNativePointer contextPtr, + KNativePointer nodePtr, + KNativePointer calleePtr, + KNativePointerArray argumentsPtr, + KInt argumentsLen, + KNativePointer typeParamsPtr, + KBoolean optionalT, + KBoolean trailingCommaT +) { auto node = reinterpret_cast(nodePtr); auto context = reinterpret_cast(contextPtr); auto callee = reinterpret_cast(calleePtr); @@ -252,28 +253,26 @@ KNativePointer impl_UpdateCallExpression(KNativePointer contextPtr, KNativePoint auto optional = static_cast(optionalT); auto trailingComma = static_cast(trailingCommaT); - auto nn = - GetImpl()->CreateCallExpression(context, callee, arguments, argumentsLen, typeParams, optional, trailingComma); + auto nn = GetImpl()->CreateCallExpression( + context, callee, arguments, argumentsLen, typeParams, optional, trailingComma + ); GetImpl()->AstNodeSetOriginalNode(context, nn, node); return nn; } -KOALA_INTEROP_8(UpdateCallExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, - KNativePointerArray, KInt, KNativePointer, KBoolean, KBoolean) +KOALA_INTEROP_8(UpdateCallExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KNativePointer, KBoolean, KBoolean) -KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer nodePtr) -{ +KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); - return (GetImpl()->IdentifierIsOptionalConst(context, node) ? (1 << 0) : 0) | - (GetImpl()->IdentifierIsReferenceConst(context, node) ? (1 << 1) : 0) | - (GetImpl()->IdentifierIsTdzConst(context, node) ? (1 << 2) : 0); + return + (GetImpl()->IdentifierIsOptionalConst(context, node) ? (1 << 0) : 0) | + (GetImpl()->IdentifierIsReferenceConst(context, node) ? (1 << 1) : 0) | + (GetImpl()->IdentifierIsTdzConst(context, node) ? (1 << 2) : 0); } KOALA_INTEROP_2(IdentifierIdentifierFlags, KInt, KNativePointer, KNativePointer) -void impl_ClassDefinitionSetBody( - KNativePointer context, KNativePointer receiver, KNativePointerArray body, KUInt bodyLength) -{ +void impl_ClassDefinitionSetBody(KNativePointer context, KNativePointer receiver, KNativePointerArray body, KUInt bodyLength) { const auto _context = reinterpret_cast(context); const auto _receiver = reinterpret_cast(receiver); const auto _body = reinterpret_cast(body); @@ -290,25 +289,24 @@ Improve: NOT FROM API (shouldn't be there) ----------------------------------------------------------------------------------------------------------------------------- */ -es2panda_AstNode* cachedParentNode; -es2panda_Context* cachedContext; +es2panda_AstNode * cachedParentNode; +es2panda_Context * cachedContext; -static void changeParent(es2panda_AstNode* child) +static void changeParent(es2panda_AstNode *child) { GetImpl()->AstNodeSetParent(cachedContext, child, cachedParentNode); } -static void SetRightParent(es2panda_AstNode* node, void* arg) +static void SetRightParent(es2panda_AstNode *node, void *arg) { - es2panda_Context* ctx = static_cast(arg); + es2panda_Context *ctx = static_cast(arg); cachedContext = ctx; cachedParentNode = node; GetImpl()->AstNodeIterateConst(ctx, node, changeParent); } -KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer programPtr) -{ +KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer programPtr) { auto context = reinterpret_cast(contextPtr); auto program = reinterpret_cast(programPtr); @@ -317,8 +315,7 @@ KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer p } KOALA_INTEROP_2(AstNodeUpdateAll, KNativePointer, KNativePointer, KNativePointer) -void impl_AstNodeSetChildrenParentPtr(KNativePointer contextPtr, KNativePointer nodePtr) -{ +void impl_AstNodeSetChildrenParentPtr(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); cachedParentNode = node; @@ -327,8 +324,7 @@ void impl_AstNodeSetChildrenParentPtr(KNativePointer contextPtr, KNativePointer } KOALA_INTEROP_V2(AstNodeSetChildrenParentPtr, KNativePointer, KNativePointer) -void impl_AstNodeOnUpdate(KNativePointer context, KNativePointer newNode, KNativePointer replacedNode) -{ +void impl_AstNodeOnUpdate(KNativePointer context, KNativePointer newNode, KNativePointer replacedNode) { auto _context = reinterpret_cast(context); auto _newNode = reinterpret_cast(newNode); auto _replacedNode = reinterpret_cast(replacedNode); @@ -353,13 +349,15 @@ KOALA_INTEROP_V3(AstNodeOnUpdate, KNativePointer, KNativePointer, KNativePointer static thread_local std::vector cachedChildren; -static void visitChild(es2panda_AstNode* node) +static void visitChild(es2panda_AstNode *node) { cachedChildren.emplace_back(node); } -KNativePointer impl_AstNodeChildren(KNativePointer contextPtr, KNativePointer nodePtr) -{ +KNativePointer impl_AstNodeChildren( + KNativePointer contextPtr, + KNativePointer nodePtr +) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); cachedContext = context; @@ -376,20 +374,16 @@ struct Pattern { std::string value; es2panda_Impl* impl; - Pattern(es2panda_Context* context, const std::string& part) : context(context), impl(GetImpl()) - { + Pattern(es2panda_Context* context, const std::string& part): context(context), impl(GetImpl()){ std::istringstream stream(part); std::getline(stream, key, '='); std::getline(stream, value, '='); } - bool match(es2panda_AstNode* node) - { + bool match(es2panda_AstNode* node) { if (key == "type") { auto type = impl->AstNodeTypeConst(context, node); switch (type) { case Es2pandaAstNodeType::AST_NODE_TYPE_METHOD_DEFINITION: - case Es2pandaAstNodeType::AST_NODE_TYPE_SCRIPT_FUNCTION: - return value == "method"; case Es2pandaAstNodeType::AST_NODE_TYPE_STRUCT_DECLARATION: return value == "struct"; @@ -410,11 +404,6 @@ struct Pattern { case Es2pandaAstNodeType::AST_NODE_TYPE_FUNCTION_DECLARATION: result = impl->FunctionDeclarationAnnotations(context, node, &length); break; - case AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION: { - auto function = impl->ArrowFunctionExpressionFunction(context, node); - result = impl->FunctionDeclarationAnnotations(context, function, &length); - break; - } case Es2pandaAstNodeType::AST_NODE_TYPE_CLASS_PROPERTY: result = impl->ClassPropertyAnnotations(context, node, &length); break; @@ -425,23 +414,12 @@ struct Pattern { for (std::size_t i = 0; i < length && result; i++) { es2panda_AstNode* ident = impl->AnnotationUsageIrGetBaseNameConst(context, result[i]); const char* name = impl->IdentifierNameConst(context, ident); - found |= matchWildcard(value, name); + found |= (value == name); } return found; } return false; } - - bool matchWildcard(const std::string& pattern, const char* valueArg) - { - if (pattern.find('*') == std::string::npos) { - return pattern == valueArg; - } - regex_t regex; - regmatch_t match[1]; - regcomp(®ex, pattern.c_str(), REG_NEWLINE); - return regexec(®ex, valueArg, 1, match, 0) != REG_NOMATCH; - } }; struct Matcher { @@ -449,18 +427,16 @@ struct Matcher { const char* query; std::vector patterns; es2panda_Impl* impl; - Matcher(es2panda_Context* context, const char* query) : context(context), query(query), impl(GetImpl()) - { + Matcher(es2panda_Context* context, const char* query) : context(context), query(query), impl(GetImpl()) { std::istringstream stream(query); std::string item; while (std::getline(stream, item, ';')) { patterns.emplace_back(Pattern(context, item)); } } - bool match(es2panda_AstNode* node) - { + bool match(es2panda_AstNode* node) { bool result = true; - for (auto pattern : patterns) { + for (auto pattern: patterns) { result &= pattern.match(node); } return result; @@ -521,9 +497,9 @@ static bool isUIHeaderFile(es2panda_Context* context, es2panda_Program* program) result = GetImpl()->ProgramModuleNameConst(context, program); string moduleName(result); - return fileNameWithExtension.length() >= MODULE_SUFFIX.length() && - fileNameWithExtension.substr(fileNameWithExtension.length() - MODULE_SUFFIX.length()) == MODULE_SUFFIX && - moduleName.find(ARKUI) != std::string::npos; + return fileNameWithExtension.length() >= MODULE_SUFFIX.length() + && fileNameWithExtension.substr(fileNameWithExtension.length() - MODULE_SUFFIX.length()) == MODULE_SUFFIX + && moduleName.find(ARKUI) != std::string::npos; } KBoolean impl_ProgramCanSkipPhases(KNativePointer context, KNativePointer program) @@ -536,8 +512,8 @@ KBoolean impl_ProgramCanSkipPhases(KNativePointer context, KNativePointer progra return false; } std::size_t sourceLen; - const auto externalSources = - reinterpret_cast(GetImpl()->ProgramExternalSources(_context, _program, &sourceLen)); + const auto externalSources = reinterpret_cast + (GetImpl()->ProgramExternalSources(_context, _program, &sourceLen)); for (std::size_t i = 0; i < sourceLen; ++i) { std::size_t programLen; auto programs = GetImpl()->ExternalSourcePrograms(externalSources[i], &programLen); diff --git a/ets1.2/libarkts/native/src/common.h b/ets1.2/libarkts/native/src/common.h index f2eeeb0e7..0ee7cd1d7 100644 --- a/ets1.2/libarkts/native/src/common.h +++ b/ets1.2/libarkts/native/src/common.h @@ -31,23 +31,21 @@ * limitations under the License. */ -#include -#include -#include - -#include "common-interop.h" #include "dynamic-loader.h" #include "es2panda_lib.h" -#include "interop-utils.h" +#include "common-interop.h" #include "stdexcept" +#include "interop-utils.h" +#include +#include +#include using std::string, std::cout, std::endl, std::vector; -extern es2panda_Impl* es2pandaImplementation; +extern es2panda_Impl *es2pandaImplementation; -es2panda_Impl* GetImplSlow(); -inline es2panda_Impl* GetImpl() -{ +es2panda_Impl *GetImplSlow(); +inline es2panda_Impl *GetImpl() { if (es2pandaImplementation) { return es2pandaImplementation; } @@ -68,8 +66,12 @@ inline KUInt unpackUInt(const KByte* bytes) const KUInt BYTE_1_SHIFT = 8; const KUInt BYTE_2_SHIFT = 16; const KUInt BYTE_3_SHIFT = 24; - return (bytes[BYTE_0] | (bytes[BYTE_1] << BYTE_1_SHIFT) | (bytes[BYTE_2] << BYTE_2_SHIFT) | - (bytes[BYTE_3] << BYTE_3_SHIFT)); + return ( + bytes[BYTE_0] + | (bytes[BYTE_1] << BYTE_1_SHIFT) + | (bytes[BYTE_2] << BYTE_2_SHIFT) + | (bytes[BYTE_3] << BYTE_3_SHIFT) + ); } es2panda_ContextState intToState(KInt state); @@ -77,33 +79,32 @@ es2panda_ContextState intToState(KInt state); class StageArena { std::vector allocated; size_t totalSize; - -public: + public: StageArena(); ~StageArena(); static StageArena* instance(); - template + template static T* alloc() { auto* arena = StageArena::instance(); void* memory = arena->alloc(sizeof(T)); return new (memory) T(); } - template + template static T* alloc(T1 arg1) { auto* arena = StageArena::instance(); void* memory = arena->alloc(sizeof(T)); return new (memory) T(std::forward(arg1)); } - template + template static T* alloc(T1 arg1, T2 arg2) { auto* arena = StageArena::instance(); void* memory = arena->alloc(sizeof(T)); return new (memory) T(arg1, arg2); } - template + template static T* allocArray(size_t count) { auto* arena = StageArena::instance(); @@ -111,14 +112,14 @@ public: void* memory = arena->alloc(sizeof(T) * count); return new (memory) T(); } - template + template static T* clone(const T& arg) { auto* arena = StageArena::instance(); void* memory = arena->alloc(sizeof(T)); return new (memory) T(arg); } - template + template static std::vector* cloneVector(const T* arg, size_t count) { return alloc, const T*, const T*>(arg, arg + count); diff --git a/ets1.2/libarkts/native/src/memoryTracker.cc b/ets1.2/libarkts/native/src/memoryTracker.cc index 024a056c6..c12fcd248 100644 --- a/ets1.2/libarkts/native/src/memoryTracker.cc +++ b/ets1.2/libarkts/native/src/memoryTracker.cc @@ -18,29 +18,29 @@ #include #include #include -#include #include #include #include +#include #ifdef _WIN32 -#include -#include + #include + #include #elif defined(__APPLE__) -#include -#include + #include + #include #elif defined(__linux__) -#include -#include + #include + #include #endif constexpr const char* UNIT_K = "kB"; constexpr size_t BYTES_PER_KB = 1024; constexpr const char* MEMORY_STATUS_FILE = "/proc/self/status"; -const std::regex VM_RSS_REGEX( - R"#(VmRSS:\s*(\d+)\s*([kKmMgG]?B))#", std::regex_constants::ECMAScript | std::regex_constants::icase); -const std::regex VM_SIZE_REGEX( - R"#(VmSize:\s*(\d+)\s*([kKmMgG]?B))#", std::regex_constants::ECMAScript | std::regex_constants::icase); +const std::regex VM_RSS_REGEX(R"#(VmRSS:\s*(\d+)\s*([kKmMgG]?B))#", + std::regex_constants::ECMAScript | std::regex_constants::icase); +const std::regex VM_SIZE_REGEX(R"#(VmSize:\s*(\d+)\s*([kKmMgG]?B))#", + std::regex_constants::ECMAScript | std::regex_constants::icase); constexpr int MATCH_GROUP_VALUE = 1; constexpr int MATCH_GROUP_UNIT = 2; @@ -49,9 +49,10 @@ constexpr int MATCH_GROUP_SIZE = 3; #if defined(_WIN32) MemoryStats GetMemoryStats() { - MemoryStats stats = { 0, 0, 0, 0, 0 }; + MemoryStats stats = {0, 0, 0, 0, 0}; PROCESS_MEMORY_COUNTERS_EX pmc; - if (GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&pmc), sizeof(pmc))) { + if (GetProcessMemoryInfo(GetCurrentProcess(), + reinterpret_cast(&pmc), sizeof(pmc))) { stats.currentRss = pmc.WorkingSetSize; stats.peakRss = pmc.PeakWorkingSetSize; stats.currentVss = pmc.PrivateUsage; // 私有内存使用量 @@ -65,18 +66,19 @@ MemoryStats GetMemoryStats() #elif defined(__APPLE__) MemoryStats GetMemoryStats() { - MemoryStats stats = { 0, 0, 0, 0, 0 }; + MemoryStats stats = {0, 0, 0, 0, 0}; struct rusage ru; if (getrusage(RUSAGE_SELF, &ru) == 0) { - stats.currentRss = 0; // macOS需要专用API获取当前内存 + stats.currentRss = 0; // macOS需要专用API获取当前内存 stats.peakRss = ru.ru_maxrss; // macOS返回字节 stats.pageFaultsMinor = ru.ru_minflt; stats.pageFaultsMajor = ru.ru_majflt; - + // 获取当前内存使用 (macOS专用API) task_basic_info info; mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT; - if (task_info(mach_task_self(), TASK_BASIC_INFO_64, (task_info_t)&info, &count) == KERN_SUCCESS) { + if (task_info(mach_task_self(), TASK_BASIC_INFO_64, + (task_info_t)&info, &count) == KERN_SUCCESS) { stats.currentRss = info.resident_size; // 物理内存使用量 stats.currentVss = info.virtual_size; // 虚拟内存总量 } @@ -87,7 +89,7 @@ MemoryStats GetMemoryStats() #elif defined(__linux__) MemoryStats GetMemoryStats() { - MemoryStats stats = { 0, 0, 0, 0, 0 }; + MemoryStats stats = {0, 0, 0, 0, 0}; struct rusage ru; if (getrusage(RUSAGE_SELF, &ru) == 0) { stats.peakRss = static_cast(ru.ru_maxrss) * BYTES_PER_KB; // KB -> 字节 @@ -127,9 +129,13 @@ void MemoryTracker::Reset() MemoryStats MemoryTracker::GetDelta() { MemoryStats current = GetMemoryStats(); - MemoryStats delta = { current.currentRss - baseline.currentRss, current.peakRss - baseline.peakRss, - current.currentVss - baseline.currentVss, current.pageFaultsMinor - baseline.pageFaultsMinor, - current.pageFaultsMajor - baseline.pageFaultsMajor }; + MemoryStats delta = { + current.currentRss - baseline.currentRss, + current.peakRss - baseline.peakRss, + current.currentVss - baseline.currentVss, + current.pageFaultsMinor - baseline.pageFaultsMinor, + current.pageFaultsMajor - baseline.pageFaultsMajor + }; return delta; } @@ -141,9 +147,13 @@ MemoryStats MemoryTracker::MeasureMemory(Func&& func) func(); auto postStats = GetMemoryStats(); - return { postStats.currentRss - preStats.currentRss, postStats.peakRss - preStats.peakRss, - postStats.currentVss - preStats.currentVss, postStats.pageFaultsMinor - preStats.pageFaultsMinor, - postStats.pageFaultsMajor - preStats.pageFaultsMajor }; + return { + postStats.currentRss - preStats.currentRss, + postStats.peakRss - preStats.peakRss, + postStats.currentVss - preStats.currentVss, + postStats.pageFaultsMinor - preStats.pageFaultsMinor, + postStats.pageFaultsMajor - preStats.pageFaultsMajor + }; } void MemoryTracker::Report(MemoryStats stats) @@ -153,12 +163,9 @@ void MemoryTracker::Report(MemoryStats stats) const double mb = kb * BYTES_PER_KB; const double gb = mb * BYTES_PER_KB; - if (bytes > gb) - return std::to_string(bytes / gb) + " GB"; - if (bytes > mb) - return std::to_string(bytes / mb) + " MB"; - if (bytes > kb) - return std::to_string(bytes / kb) + " KB"; + if (bytes > gb) return std::to_string(bytes / gb) + " GB"; + if (bytes > mb) return std::to_string(bytes / mb) + " MB"; + if (bytes > kb) return std::to_string(bytes / kb) + " KB"; return std::to_string(bytes) + " B"; }; diff --git a/ets1.2/libarkts/native/src/memoryTracker.h b/ets1.2/libarkts/native/src/memoryTracker.h index 3747160f5..3f0dc71eb 100644 --- a/ets1.2/libarkts/native/src/memoryTracker.h +++ b/ets1.2/libarkts/native/src/memoryTracker.h @@ -21,11 +21,11 @@ // 内存统计结构体 struct MemoryStats { - size_t currentRss = 0; // 当前驻留集大小 (字节) - size_t peakRss = 0; // 峰值驻留集大小 (字节) - size_t currentVss = 0; // 当前虚拟内存大小 (字节) - size_t pageFaultsMinor = 0; // 小页错误次数 - size_t pageFaultsMajor = 0; // 大页错误次数 + size_t currentRss = 0; // 当前驻留集大小 (字节) + size_t peakRss = 0; // 峰值驻留集大小 (字节) + size_t currentVss = 0; // 当前虚拟内存大小 (字节) + size_t pageFaultsMinor = 0; // 小页错误次数 + size_t pageFaultsMajor = 0; // 大页错误次数 }; class MemoryTracker { diff --git a/ets1.2/libarkts/package.json b/ets1.2/libarkts/package.json index f391b800c..f04866a74 100644 --- a/ets1.2/libarkts/package.json +++ b/ets1.2/libarkts/package.json @@ -12,6 +12,10 @@ ] } }, + "workspaces": [ + ".", + "../ui2abc/memo-plugin-ng" + ], "exports": { ".": "./lib/libarkts.js", "./compat": "./lib/libarkts-compat.js", @@ -23,7 +27,7 @@ "./plugins/build/src/**/*" ], "config": { - "panda_sdk_path": "../../incremental/tools/panda/node_modules/@panda/sdk", + "panda_sdk_path": "../incremental/tools/panda/node_modules/@panda/sdk", "panda_sdk_version": "next" }, "dependencies": { @@ -31,9 +35,7 @@ "@koalaui/build-common": "1.7.10+devel", "@koalaui/compat": "1.7.10+devel", "@koalaui/common": "1.7.10+devel", - "@koalaui/harness": "1.7.10+devel", "@koalaui/interop": "1.7.10+devel", - "@koalaui/fast-arktsc": "1.7.10+devel", "@idlizer/arktscgen": "2.1.10-arktscgen-4", "mocha": "^9.2.2", "node-addon-api": "8.0.0", @@ -41,17 +43,19 @@ "commander": "10.0.1" }, "devDependencies": { + "tslib": "^2.3.1", "rollup": "^4.13.0", "@rollup/plugin-commonjs": "^26.0.1", "@rollup/plugin-node-resolve": "^15.3.0", "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.6", + "tsconfig-paths": "^4.2.0", "rimraf": "^6.0.1" }, "scripts": { "clean": "rimraf generated build native/build* ./.rollup.cache tsconfig.tsbuildinfo lib", "clean:plugins": "rimraf plugins/build", - "compile:koala:interop": "npm run --prefix ../../interop compile", + "compile:koala:interop": "npm run --prefix ../interop compile", "compile:meson": "cd native && meson setup build && meson compile -C build", "compile:meson:mingw": "cd native && meson setup --cross-file ./mingw.cross mingw_build && meson compile -C mingw_build", "crosscompile:meson": "cd native && CXX=clang++ meson setup -D cross_compile=true build && CXX=clang++ meson compile -C build", @@ -62,8 +66,8 @@ "compile:release": "npm run crosscompile:native && npm run compile:js", "compile:js": "rm -rf lib/ && rollup -c rollup.lib.mjs && rollup -c rollup.es2panda.mjs", "compile:plugins": "rollup -c ./rollup.printer-plugin.mjs", - "direct": "fast-arktsc --config arktsconfig.json --compiler ../../incremental/tools/panda/arkts/ui2abc --link-name ./build/abc/main.abc && ninja -f build/abc/build.ninja", - "simultaneous": "mkdir -p build/abc && bash ../../incremental/tools/panda/arkts/ui2abc --simultaneous --arktsconfig arktsconfig.json --output ./build/abc/main.abc:./build/abc/library.abc plugins/input/main.ets:plugins/input/library.ets", + "direct": "fast-arktsc --config arktsconfig.json --compiler ../incremental/tools/panda/arkts/ui2abc --link-name ./build/abc/main.abc && ninja -f build/abc/build.ninja", + "simultaneous": "mkdir -p build/abc && bash ../incremental/tools/panda/arkts/ui2abc --simultaneous --arktsconfig arktsconfig.json --output ./build/abc/main.abc:./build/abc/library.abc plugins/input/main.ets:plugins/input/library.ets", "run": "npm run compile && npm run compile:plugins && npm run simultaneous", "run:memo": "npm run compile && npm run compile:plugins && npm run compile --prefix ../memo-plugin-ng && npm run memo", "run:abc": "$npm_package_config_panda_sdk_path/linux_host_tools/bin/ark --load-runtimes=ets --boot-panda-files=$npm_package_config_panda_sdk_path/ets/etsstdlib.abc ./main.abc main.ETSGLOBAL::main", @@ -72,9 +76,9 @@ "test": "npm run compile:native && npm run test:light", "test:golden": "npm run compile:native && TEST_GOLDEN=1 npm run test:light", "compile:playground": "cd playground && meson setup build && meson compile -C build", - "run:playground": "npm run compile:playground && mkdir -p build && ./playground/build/playground _ --extension ets --stdlib ../../incremental/tools/panda/node_modules/@panda/sdk/ets/stdlib --output build/playground.abc ./playground/src/main.ets", - "panda:sdk:clean": "cd ../../incremental/tools/panda && rimraf node_modules", - "panda:sdk:install": "cd ../../incremental/tools/panda && echo \"Installing panda sdk $npm_package_config_panda_sdk_version\" && PANDA_SDK_VERSION=$npm_package_config_panda_sdk_version npm run panda:sdk:install", + "run:playground": "npm run compile:playground && mkdir -p build && ./playground/build/playground _ --extension ets --stdlib ../incremental/tools/panda/node_modules/@panda/sdk/ets/stdlib --output build/playground.abc ./playground/src/main.ets", + "panda:sdk:clean": "cd ../incremental/tools/panda && rimraf node_modules", + "panda:sdk:install": "cd ../incremental/tools/panda && echo \"Installing panda sdk $npm_package_config_panda_sdk_version\" && PANDA_SDK_VERSION=$npm_package_config_panda_sdk_version npm run panda:sdk:install", "panda:sdk:reinstall": "npm run panda:sdk:clean && npm run panda:sdk:install", "regenerate:current": "rimraf -rf ./generated && npm run compile -C ../../../arktscgen && node ../../../arktscgen --panda-sdk-path $npm_package_config_panda_sdk_path --output-dir ../ --options-file ./generator/options.json5 --no-initialize --debug", "regenerate": "rimraf -rf ./generated && arktscgen --panda-sdk-path ${PANDA_SDK_PATH:=$npm_package_config_panda_sdk_path} --output-dir ../ --options-file ./generator/options.json5 --no-initialize", diff --git a/ets1.2/libarkts/playground/src/playground.cc b/ets1.2/libarkts/playground/src/playground.cc deleted file mode 100644 index d142c0081..000000000 --- a/ets1.2/libarkts/playground/src/playground.cc +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "public/es2panda_lib.h" -#include "util.h" - -// NOLINTBEGIN -static std::string prefix = "returns_"; - -static std::string source = R"( -class C { -} - -interface I { - x: int -} - -class Test { - static returns_void() { - } - - static returns_int() { - return 1 - } - - static returns_arrow() { - return () => {} - } - - static returns_C() { - return new C() - } - - static returns_I() { - return { x: 1 } as I - } - - static returns_union(cond: boolean) { - if (cond) { - return 1 - } else { - return "hello" - } - } -} -)"; - -static es2panda_Impl* impl = nullptr; -static es2panda_Config* config = nullptr; -static es2panda_Context* context = nullptr; - -static int countFound = 0; -static int countApplied = 0; - -void setScriptFunctionReturnType(es2panda_AstNode* node, [[maybe_unused]] void* arg) -{ - if (impl->IsScriptFunction(node)) { - es2panda_AstNode* id = impl->ScriptFunctionId(context, node); - if (!id) { - return; - } - if (std::string(impl->IdentifierNameConst(context, id)).substr(0, prefix.length()) != prefix) { - return; - } - countFound++; - es2panda_Signature* signature = impl->ScriptFunctionSignature(context, node); - if (!signature) { - return; - } - es2panda_Type* returnType = impl->SignatureReturnType(context, signature); - if (!returnType) { - return; - } - es2panda_AstNode* returnTypeAnnotation = impl->CreateOpaqueTypeNode(context, returnType); - if (!returnTypeAnnotation) { - return; - } - impl->ScriptFunctionSetReturnTypeAnnotation(context, node, returnTypeAnnotation); - countApplied++; - } -} - -int main(int argc, char** argv) -{ - if (argc < MIN_ARGC) { - return INVALID_ARGC_ERROR_CODE; - } - - if (GetImpl() == nullptr) { - return NULLPTR_IMPL_ERROR_CODE; - } - impl = GetImpl(); - - const char** args = const_cast(&(argv[1])); - config = impl->CreateConfig(argc - 1, args); - context = impl->CreateContextFromString(config, source.data(), argv[argc - 1]); - if (context == nullptr) { - return NULLPTR_CONTEXT_ERROR_CODE; - } - - impl->ProceedToState(context, ES2PANDA_STATE_CHECKED); - CheckForErrors("CHECKED", context); - if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { - return PROCEED_ERROR_CODE; - } - - auto* program = impl->ContextProgram(context); - es2panda_AstNode* ast = impl->ProgramAst(context, program); - - impl->AstNodeForEach(ast, setScriptFunctionReturnType, nullptr); - if (countFound == 0) { - return TEST_ERROR_CODE; - } - if (countFound != countApplied) { - return TEST_ERROR_CODE; - } - - impl->AstNodeRecheck(context, ast); - CheckForErrors("RECHECKED", context); - if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { - return PROCEED_ERROR_CODE; - } - - impl->ProceedToState(context, ES2PANDA_STATE_BIN_GENERATED); - CheckForErrors("BIN", context); - if (impl->ContextState(context) == ES2PANDA_STATE_ERROR) { - return PROCEED_ERROR_CODE; - } - - impl->DestroyContext(context); - impl->DestroyConfig(config); - - return 0; -} - -// NOLINTEND \ No newline at end of file diff --git a/ets1.2/libarkts/playground/src/util.h b/ets1.2/libarkts/playground/src/util.h deleted file mode 100644 index 26f331cdc..000000000 --- a/ets1.2/libarkts/playground/src/util.h +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ES2PANDA_TEST_UNIT_PLUGIN_UTIL_H -#define ES2PANDA_TEST_UNIT_PLUGIN_UTIL_H - -#include -#include -#include -#include -#include - -#include "dynamic-loader.h" -#include "public/es2panda_lib.h" - -constexpr int MIN_ARGC = 3; - -// error code number -constexpr int NULLPTR_IMPL_ERROR_CODE = 2; -constexpr int PROCEED_ERROR_CODE = 3; -constexpr int TEST_ERROR_CODE = 4; -constexpr int INVALID_ARGC_ERROR_CODE = 5; -constexpr int NULLPTR_CONTEXT_ERROR_CODE = 6; - -extern es2panda_Impl* g_implPtr; - -es2panda_Impl* GetImplSlow(); -inline es2panda_Impl* GetImpl() -{ - if (g_implPtr) { - return g_implPtr; - } - return GetImplSlow(); -} - -struct ProccedToStatePluginTestData { - int argc; - char** argv; - es2panda_Impl** impl; - std::map>> testFunctions; - bool fromSource; - std::string source; - es2panda_ContextState exitAfterState = ES2PANDA_STATE_ERROR; -}; - -void CheckForErrors(const std::string& stateName, es2panda_Context* context); -bool IsAssertCall(es2panda_AstNode* ast); -es2panda_AstNode* CreateAssertStatement(es2panda_Context* context, es2panda_AstNode* test, es2panda_AstNode* second); -es2panda_AstNode* AssertStatementTest(es2panda_Context* context, es2panda_AstNode* classInstance); -int RunAllStagesWithTestFunction(ProccedToStatePluginTestData& data); - -es2panda_AstNode* CreateIdentifierFromString(es2panda_Context* context, const std::string_view& name); - -void AppendStatementToProgram(es2panda_Context* context, es2panda_AstNode* program, es2panda_AstNode* newStatement); - -void PrependStatementToProgram(es2panda_Context* context, es2panda_AstNode* program, es2panda_AstNode* newStatement); - -int Test(es2panda_Context* context, es2panda_Impl* impl, int stage, - const std::function& handle); - -#endif diff --git a/ets1.2/libarkts/rollup-lib.mjs b/ets1.2/libarkts/rollup.lib.mjs similarity index 100% rename from ets1.2/libarkts/rollup-lib.mjs rename to ets1.2/libarkts/rollup.lib.mjs diff --git a/ets1.2/package.json b/ets1.2/package.json new file mode 100644 index 000000000..dec57c318 --- /dev/null +++ b/ets1.2/package.json @@ -0,0 +1,11 @@ +{ + "name": "root", + "private": true, + "workspaces": [ + "interop", + "build-common", + "common", + "compat", + "libarkts" + ] +} diff --git a/ets1.2/koala_integration.gni b/koala_integration.gni similarity index 86% rename from ets1.2/koala_integration.gni rename to koala_integration.gni index 5295f7960..c530783d4 100644 --- a/ets1.2/koala_integration.gni +++ b/koala_integration.gni @@ -16,10 +16,12 @@ koala_mr = { scripts_path = "$root_path/gn/script" imports_prefix = "$root_path/gn/import" libarkts_path = "$root_path/libarkts" + panda_sdk_path = "$libarkts_path/sdk" + es2panda_path = "$panda_sdk_path/ohos_arm64/include/tools/es2panda" interop_path = "$root_path/interop" is_rri = false } node_version = "v16.20.2" host_arch = "${host_os}-${host_cpu}" -koala_node_path = rebase_path("//prebuilts/build-tools/common/nodejs/node-${node_version}-${host_arch}/bin") +koala_node_path = rebase_path("//prebuilts/build-tools/common/nodejs/node-${node_version}-${host_arch}/bin") \ No newline at end of file -- Gitee From 8f089440bd278f73c696be724eb7d96d3dbe1d35 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Fri, 12 Sep 2025 18:16:11 +0300 Subject: [PATCH 02/14] fix copy Signed-off-by: Korobeinikov Evgeny Change-Id: Id9586667c7668d17c9bda1b291d1fe17f678c660 --- ets1.2/libarkts/gn/command/copy_libs.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ets1.2/libarkts/gn/command/copy_libs.py b/ets1.2/libarkts/gn/command/copy_libs.py index d9940ea79..46bc1d72d 100755 --- a/ets1.2/libarkts/gn/command/copy_libs.py +++ b/ets1.2/libarkts/gn/command/copy_libs.py @@ -72,7 +72,9 @@ def copy_output(options): if (tail_dir == compiler): from_path = head_dir - shutil.rmtree(to_path) + if os.path.exists(to_path): + shutil.rmtree(to_path) + copy_files(os.path.join(options.source_path, 'lib'), os.path.join(to_path, 'lib')) -- Gitee From 4e8e7e5e2c414433b62d9b23c424dffaff7ce0b8 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Fri, 12 Sep 2025 20:26:58 +0300 Subject: [PATCH 03/14] codecheck1 Signed-off-by: Korobeinikov Evgeny Change-Id: I09257fc774148ad1212397aa2e5306a99336d8b7 --- ets1.2/gn/command/npm_util.py | 10 +++++----- ets1.2/gn/script/npm.py | 11 +++++------ ets1.2/interop/src/cpp/DeserializerBase.h | 3 ++- ets1.2/interop/src/cpp/SerializerBase.h | 10 ++++++---- ets1.2/interop/src/cpp/ani/convertors-ani.cc | 2 +- ets1.2/interop/src/cpp/common-interop.cc | 6 ++---- ets1.2/interop/src/cpp/interop-logging.cc | 5 +++-- ets1.2/interop/src/cpp/jni/convertors-jni.cc | 10 +++++++--- ets1.2/interop/src/cpp/jsc/convertors-jsc.cc | 3 ++- ets1.2/interop/src/cpp/napi/convertors-napi.h | 16 ++++++++++------ ets1.2/interop/src/cpp/ohos/hilog/log.h | 3 +-- ets1.2/interop/src/cpp/ohos/oh_sk_log.cc | 5 +++-- ets1.2/interop/src/cpp/profiler.h | 3 ++- ets1.2/interop/src/cpp/types/koala-types.h | 8 +++++--- ets1.2/interop/src/cpp/vmloader.cc | 3 ++- ets1.2/libarkts/gn/command/copy.py | 4 ++-- ets1.2/libarkts/gn/command/copy_libs.py | 8 ++++---- ets1.2/libarkts/gn/command/gen_sdk.py | 4 ++-- ets1.2/libarkts/package.json | 2 +- .../libarkts/{rollup.lib.mjs => rollup-lib.mjs} | 0 20 files changed, 65 insertions(+), 51 deletions(-) rename ets1.2/libarkts/{rollup.lib.mjs => rollup-lib.mjs} (100%) diff --git a/ets1.2/gn/command/npm_util.py b/ets1.2/gn/command/npm_util.py index ae7d0537c..d4edce42b 100755 --- a/ets1.2/gn/command/npm_util.py +++ b/ets1.2/gn/command/npm_util.py @@ -54,17 +54,17 @@ if args.stdlib_path: os.environ["LIBARKTS_PATH"] = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../libarkts") os.environ["PANDA_SDK_PATH"] = os.path.join(os.environ.get("LIBARKTS_PATH"), "sdk") -def run(args, dir = None): +def run(npm_args, dir = None): os.chdir(dir or project_path) if os.environ.get("KOALA_LOG_STDOUT"): - subprocess.run(["npm"] + args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) + subprocess.run(["npm"] + npm_args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) return - result = subprocess.run(["npm"] + args, capture_output=True, env=os.environ, text=True) + result = subprocess.run(["npm"] + npm_args, capture_output=True, env=os.environ, text=True) with open(koala_log, "w+") as f: - f.write(f"npm args: {args}; project: {project_path}:\n" + result.stdout) + f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stdout) if result.returncode != 0: - f.write(f"npm args: {args}; project: {project_path}:\n" + result.stderr) + f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stderr) f.close() print(open(koala_log, "r").read()) raise Exception("npm failed") diff --git a/ets1.2/gn/script/npm.py b/ets1.2/gn/script/npm.py index 3d10297b7..d9f6b5c6f 100755 --- a/ets1.2/gn/script/npm.py +++ b/ets1.2/gn/script/npm.py @@ -54,19 +54,18 @@ if args.stdlib_path: os.environ["ETS_STDLIB_PATH"] = args.stdlib_path if args.panda_sdk_path: os.environ["PANDA_SDK_PATH"] = args.panda_sdk_path -# os.environ["PANDA_SDK_PATH"] = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../ui2abc/build/sdk") -def run(args, dir = None): +def run(npm_args, dir = None): os.chdir(dir or project_path) if os.environ.get("KOALA_LOG_STDOUT"): - subprocess.run(["npm"] + args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) + subprocess.run(["npm"] + npm_args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) return - result = subprocess.run(["npm"] + args, capture_output=True, env=os.environ, text=True) + result = subprocess.run(["npm"] + npm_args, capture_output=True, env=os.environ, text=True) with open(koala_log, "w+") as f: - f.write(f"npm args: {args}; project: {project_path}:\n" + result.stdout) + f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stdout) if result.returncode != 0: - f.write(f"npm args: {args}; project: {project_path}:\n" + result.stderr) + f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stderr) f.close() print(open(koala_log, "r").read()) raise Exception("npm failed") diff --git a/ets1.2/interop/src/cpp/DeserializerBase.h b/ets1.2/interop/src/cpp/DeserializerBase.h index 360ccaea6..408dfd336 100644 --- a/ets1.2/interop/src/cpp/DeserializerBase.h +++ b/ets1.2/interop/src/cpp/DeserializerBase.h @@ -558,7 +558,8 @@ inline void WriteToString(std::string* result, InteropFloat64 value) result->append(buf); #else std::string storage; - storage.resize(20); + constexpr auto BUF_SIZE{20}; + storage.resize(BUF_SIZE); // We use to_chars() to avoid locale issues. auto rc = std::to_chars(storage.data(), storage.data() + storage.size(), value); storage.resize(rc.ptr - storage.data()); diff --git a/ets1.2/interop/src/cpp/SerializerBase.h b/ets1.2/interop/src/cpp/SerializerBase.h index 2b9e484e1..bc21182b3 100644 --- a/ets1.2/interop/src/cpp/SerializerBase.h +++ b/ets1.2/interop/src/cpp/SerializerBase.h @@ -79,7 +79,8 @@ public: SerializerBase(CallbackResourceHolder* resourceHolder = nullptr) : position(0), ownData(true), resourceHolder(resourceHolder) { - this->dataLength = 256; + constexpr uint16_t LENGTH = 256; + this->dataLength = LENGTH; this->data = reinterpret_cast(malloc(this->dataLength)); if (!this->data) { INTEROP_FATAL("Cannot allocate memory"); @@ -115,11 +116,12 @@ public: return position; } - inline void check(int more) - { + inline void check(int more) { if (position + more > dataLength) { if (ownData) { - resize((position + more) * 3 / 2 + 2); + constexpr auto NUM_2{2}; + constexpr auto NUM_3{3}; + resize((position + more) * NUM_3 / NUM_2 + NUM_2); } else { INTEROP_FATAL("Buffer overrun: %d > %d\n", position + more, dataLength); } diff --git a/ets1.2/interop/src/cpp/ani/convertors-ani.cc b/ets1.2/interop/src/cpp/ani/convertors-ani.cc index c9ece6e17..e84694d98 100644 --- a/ets1.2/interop/src/cpp/ani/convertors-ani.cc +++ b/ets1.2/interop/src/cpp/ani/convertors-ani.cc @@ -15,7 +15,7 @@ #include "convertors-ani.h" #include -#include +#include #include "interop-types.h" #include "signatures.h" diff --git a/ets1.2/interop/src/cpp/common-interop.cc b/ets1.2/interop/src/cpp/common-interop.cc index b367d4f6d..e3a7e25a7 100644 --- a/ets1.2/interop/src/cpp/common-interop.cc +++ b/ets1.2/interop/src/cpp/common-interop.cc @@ -514,11 +514,9 @@ void impl_SetForeignVMContext(KNativePointer foreignVMContextRaw) } KOALA_INTEROP_V1(SetForeignVMContext, KNativePointer) -#ifndef __QUOTE -#define __QUOTE(x) #x -#endif +#define QUOTE2(x) #x -#define QUOTE(x) __QUOTE(x) +#define QUOTE(x) QUOTE2(x) void impl_NativeLog(const KStringPtr& str) { diff --git a/ets1.2/interop/src/cpp/interop-logging.cc b/ets1.2/interop/src/cpp/interop-logging.cc index 4fb30b938..e4b471c27 100644 --- a/ets1.2/interop/src/cpp/interop-logging.cc +++ b/ets1.2/interop/src/cpp/interop-logging.cc @@ -14,7 +14,7 @@ */ #include "interop-logging.h" -#include +#include #include #include @@ -59,7 +59,8 @@ void appendGroupedLog(int index, const char* str) const char* getGroupedLog(int index) { if (index < static_cast(groupedLogs.size())) { - return groupedLogs[index]->log.c_str(); + // G.STD.04-CPP: Do not hold pointer returned from std::string c_str() method. + return std::move(groupedLogs[index]->log.c_str()); } return ""; } diff --git a/ets1.2/interop/src/cpp/jni/convertors-jni.cc b/ets1.2/interop/src/cpp/jni/convertors-jni.cc index 7918b9721..f91f81273 100644 --- a/ets1.2/interop/src/cpp/jni/convertors-jni.cc +++ b/ets1.2/interop/src/cpp/jni/convertors-jni.cc @@ -30,13 +30,17 @@ const bool registerByOne = true; static bool registerNatives( JNIEnv* env, jclass clazz, const std::vector> impls) { + constexpr auto NUM_0{0}; + constexpr auto NUM_1{1}; + constexpr auto NUM_2{2}; + size_t numMethods = impls.size(); JNINativeMethod* methods = new JNINativeMethod[numMethods]; bool result = true; for (size_t i = 0; i < numMethods; i++) { - methods[i].name = (char*)std::get<0>(impls[i]).c_str(); - methods[i].signature = (char*)std::get<1>(impls[i]).c_str(); - methods[i].fnPtr = std::get<2>(impls[i]); + methods[i].name = (char*)std::get(impls[i]).c_str(); + methods[i].signature = (char*)std::get(impls[i]).c_str(); + methods[i].fnPtr = std::get(impls[i]); if (registerByOne) { result &= (env->RegisterNatives(clazz, methods + i, 1) >= 0); if (env->ExceptionCheck()) { diff --git a/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc b/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc index 98d3a994e..69040b64b 100644 --- a/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc +++ b/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc @@ -156,7 +156,8 @@ static JSValueRef u64ToBigInt(JSContextRef context, uint64_t value) JSValueMakeNumber(context, (double)(value >> 32)), JSValueMakeNumber(context, (double)(value & 0xFFFFFFFF)), }; - bigint = JSObjectCallAsFunction(context, bigIntFromParts, nullptr, 2, parts, nullptr); + const uint8_t COUNT = 2; + bigint = JSObjectCallAsFunction(context, bigIntFromParts, nullptr, COUNT, parts, nullptr); #else char buffer[128] = { 0 }; interop_snprintf(buffer, sizeof(buffer) - 1, "%zun", static_cast(value)); diff --git a/ets1.2/interop/src/cpp/napi/convertors-napi.h b/ets1.2/interop/src/cpp/napi/convertors-napi.h index 1bbd236c9..e1d5d43bf 100644 --- a/ets1.2/interop/src/cpp/napi/convertors-napi.h +++ b/ets1.2/interop/src/cpp/napi/convertors-napi.h @@ -204,14 +204,18 @@ struct InteropTypeConverter { inline napi_typedarray_type getNapiType(KInt size) { + constexpr auto NUM_1{1}; + constexpr auto NUM_2{2}; + constexpr auto NUM_4{4}; + constexpr auto NUM_8{8}; switch (size) { - case 1: + case NUM_1: return napi_uint8_array; - case 2: + case NUM_2: return napi_uint16_array; - case 4: + case NUM_4: return napi_uint32_array; - case 8: + case NUM_8: return napi_biguint64_array; default: break; @@ -760,8 +764,8 @@ public: const std::vector>& getMethods(const std::string& module); }; -#define __QUOTE(x) #x -#define QUOTE(x) __QUOTE(x) +#define QUOTE2(x) #x +#define QUOTE(x) QUOTE2(x) #ifdef _MSC_VER #define MAKE_NODE_EXPORT(module, name) \ diff --git a/ets1.2/interop/src/cpp/ohos/hilog/log.h b/ets1.2/interop/src/cpp/ohos/hilog/log.h index 058d09e26..385385521 100644 --- a/ets1.2/interop/src/cpp/ohos/hilog/log.h +++ b/ets1.2/interop/src/cpp/ohos/hilog/log.h @@ -58,8 +58,7 @@ * * @since 8 */ -#include -#include +#include #ifdef __cplusplus extern "C" { diff --git a/ets1.2/interop/src/cpp/ohos/oh_sk_log.cc b/ets1.2/interop/src/cpp/ohos/oh_sk_log.cc index c17e605f7..254feea6b 100644 --- a/ets1.2/interop/src/cpp/ohos/oh_sk_log.cc +++ b/ets1.2/interop/src/cpp/ohos/oh_sk_log.cc @@ -59,15 +59,16 @@ void oh_sk_file_log(oh_sk_log_type type, const char* msg, ...) size_t len = interop_strlen(KOALAUI_OHOS_LOG_ROOT) + 100; path = new char[len]; APPLY_LOG_FILE_PATTERN(path, len, lt, ms, getpid()); - mkdir(KOALAUI_OHOS_LOG_ROOT, 0777); + mkdir(KOALAUI_OHOS_LOG_ROOT, ACCESSPERMS); } std::unique_ptr file(fopen(path, "a"), fclose); if (!file) return; + constexpr auto US_IN_MS{1000}; fprintf(file.get(), "%02d-%02d %02d:%02d:%02d.%03lld %s koala: ", lt.tm_mon + 1, lt.tm_mday, lt.tm_hour, lt.tm_min, - lt.tm_sec, ms.tv_usec / 1000, oh_sk_log_type_str(type)); + lt.tm_sec, static_cast(ms.tv_usec / US_IN_MS), oh_sk_log_type_str(type)); va_list args; va_start(args, msg); diff --git a/ets1.2/interop/src/cpp/profiler.h b/ets1.2/interop/src/cpp/profiler.h index 2946c5d0e..236933e97 100644 --- a/ets1.2/interop/src/cpp/profiler.h +++ b/ets1.2/interop/src/cpp/profiler.h @@ -72,8 +72,9 @@ public: auto ns = a.second.time; auto count = a.second.count; char buffer[1024]; + const double MAX = 100.0; interop_snprintf(buffer, sizeof buffer, "for %s[%lld]: %.01f%% (%lld)\n", a.first.c_str(), - (long long)count, (double)ns / total * 100.0, (long long)ns); + (long long)count, (double)ns / total * MAX, (long long)ns); result += buffer; }); return result; diff --git a/ets1.2/interop/src/cpp/types/koala-types.h b/ets1.2/interop/src/cpp/types/koala-types.h index dc9102cd2..db3b808ee 100644 --- a/ets1.2/interop/src/cpp/types/koala-types.h +++ b/ets1.2/interop/src/cpp/types/koala-types.h @@ -112,11 +112,12 @@ struct KStringPtrImpl { // Ignore old content. if (_value && _owned) free(_value); - _value = reinterpret_cast(malloc(size + 1)); + auto memSize{static_cast(std::max(0, _length + 1))}; + _value = reinterpret_cast(malloc(memSize)); if (!_value) { INTEROP_FATAL("Cannot allocate memory"); } - _value[size] = 0; + _value[_length] = 0; } void assign(const char* data) @@ -130,7 +131,8 @@ struct KStringPtrImpl { free(_value); if (data) { if (_owned) { - _value = reinterpret_cast(malloc(length + 1)); + auto memSize{static_cast(std::max(0, length + 1))}; + _value = reinterpret_cast(malloc(memSize)); if (!_value) { INTEROP_FATAL("Cannot allocate memory"); } diff --git a/ets1.2/interop/src/cpp/vmloader.cc b/ets1.2/interop/src/cpp/vmloader.cc index e9f002aa1..92e2a967c 100644 --- a/ets1.2/interop/src/cpp/vmloader.cc +++ b/ets1.2/interop/src/cpp/vmloader.cc @@ -309,7 +309,8 @@ static bool ResetErrorIfExists(ani_env* env) std::string makeLibPath(const char* sdkPath, const char* platform, const char* lib) { std::string result; - result.reserve(255); + constexpr uint16_t COUNT = 255; + result.reserve(COUNT); if (sdkPath) { result.append(sdkPath).append("/"); } diff --git a/ets1.2/libarkts/gn/command/copy.py b/ets1.2/libarkts/gn/command/copy.py index c42c37f14..ca0e1fc7a 100755 --- a/ets1.2/libarkts/gn/command/copy.py +++ b/ets1.2/libarkts/gn/command/copy.py @@ -19,8 +19,8 @@ import shutil import subprocess import sys -def library_ext(os, cpu): - if (os == 'mingw' and cpu == 'x86_64'): +def library_ext(os_name, cpu_name): + if (os_name == 'mingw' and cpu_name == 'x86_64'): return 'dll' return 'node' diff --git a/ets1.2/libarkts/gn/command/copy_libs.py b/ets1.2/libarkts/gn/command/copy_libs.py index 46bc1d72d..6c57dceec 100755 --- a/ets1.2/libarkts/gn/command/copy_libs.py +++ b/ets1.2/libarkts/gn/command/copy_libs.py @@ -19,13 +19,13 @@ import shutil import subprocess import sys -def get_compiler_name(os, cpu): - if (os == 'mingw' and cpu == 'x86_64'): +def get_compiler_name(os_name, cpu_name): + if (os_name == 'mingw' and cpu_name == 'x86_64'): return 'mingw_x86_64' return 'clang_x64' -def library_ext(os, cpu): - if (os == 'mingw' and cpu == 'x86_64'): +def library_ext(os_name, cpu_name): + if (os_name == 'mingw' and cpu_name == 'x86_64'): return 'dll' return 'node' diff --git a/ets1.2/libarkts/gn/command/gen_sdk.py b/ets1.2/libarkts/gn/command/gen_sdk.py index f9bb97ea2..f5e324a72 100755 --- a/ets1.2/libarkts/gn/command/gen_sdk.py +++ b/ets1.2/libarkts/gn/command/gen_sdk.py @@ -23,8 +23,8 @@ def load_config(config_file): config = json.load(f) return config -def get_compiler_type(os, cpu): - if (os == 'mingw' and cpu == 'x86_64'): +def get_compiler_type(os_name, cpu_name): + if (os_name == 'mingw' and cpu_name == 'x86_64'): return 'mingw_x86_64' return 'clang_x64' diff --git a/ets1.2/libarkts/package.json b/ets1.2/libarkts/package.json index f04866a74..cbb4dcf04 100644 --- a/ets1.2/libarkts/package.json +++ b/ets1.2/libarkts/package.json @@ -64,7 +64,7 @@ "crosscompile:native": "npm run compile:koala:interop && npm run crosscompile:meson && npm run copy:.node", "compile": "npm run regenerate && npm run compile:native && npm run compile:js", "compile:release": "npm run crosscompile:native && npm run compile:js", - "compile:js": "rm -rf lib/ && rollup -c rollup.lib.mjs && rollup -c rollup.es2panda.mjs", + "compile:js": "rm -rf lib/ && rollup -c rollup-lib.mjs && rollup -c rollup.es2panda.mjs", "compile:plugins": "rollup -c ./rollup.printer-plugin.mjs", "direct": "fast-arktsc --config arktsconfig.json --compiler ../incremental/tools/panda/arkts/ui2abc --link-name ./build/abc/main.abc && ninja -f build/abc/build.ninja", "simultaneous": "mkdir -p build/abc && bash ../incremental/tools/panda/arkts/ui2abc --simultaneous --arktsconfig arktsconfig.json --output ./build/abc/main.abc:./build/abc/library.abc plugins/input/main.ets:plugins/input/library.ets", diff --git a/ets1.2/libarkts/rollup.lib.mjs b/ets1.2/libarkts/rollup-lib.mjs similarity index 100% rename from ets1.2/libarkts/rollup.lib.mjs rename to ets1.2/libarkts/rollup-lib.mjs -- Gitee From f3fe978072fc5fec6ecf4457d33634545d79cb33 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Fri, 12 Sep 2025 20:55:56 +0300 Subject: [PATCH 04/14] codecheck2 Signed-off-by: Korobeinikov Evgeny Change-Id: I96ae523832c856200c4deb184b9e7fe0bc2d2a9a --- ets1.2/interop/src/cpp/DeserializerBase.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ets1.2/interop/src/cpp/DeserializerBase.h b/ets1.2/interop/src/cpp/DeserializerBase.h index 408dfd336..633a9afb3 100644 --- a/ets1.2/interop/src/cpp/DeserializerBase.h +++ b/ets1.2/interop/src/cpp/DeserializerBase.h @@ -541,7 +541,8 @@ inline void WriteToString(std::string* result, InteropFloat32 value) result->append(buf); #else std::string storage; - storage.resize(20); + constexpr auto SIZE{20}; + storage.resize(SIZE); // We use to_chars() to avoid locale issues. auto rc = std::to_chars(storage.data(), storage.data() + storage.size(), value); storage.resize(rc.ptr - storage.data()); -- Gitee From 7642ac059fa5ab22e2a46c05ec7e5126d7ea5e80 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 11:31:38 +0300 Subject: [PATCH 05/14] codecheck3 Signed-off-by: Korobeinikov Evgeny Change-Id: Ia373f513bdd601af365540da11ccb505be9c08cd --- ets1.2/interop/src/cpp/SerializerBase.h | 3 +- ets1.2/interop/src/cpp/common-interop.cc | 70 ++++++++++++--------- ets1.2/interop/src/cpp/vmloader.cc | 4 +- ets1.2/libarkts/gn/command/copy.py | 2 +- ets1.2/libarkts/gn/command/copy_file.py | 3 + ets1.2/libarkts/gn/command/copy_libs.py | 2 +- ets1.2/libarkts/gn/command/gen_sdk.py | 3 + ets1.2/libarkts/native/src/common.cc | 56 +++++++++++------ ets1.2/libarkts/native/src/common.h | 6 +- ets1.2/libarkts/native/src/memoryTracker.cc | 15 ++++- 10 files changed, 105 insertions(+), 59 deletions(-) diff --git a/ets1.2/interop/src/cpp/SerializerBase.h b/ets1.2/interop/src/cpp/SerializerBase.h index bc21182b3..b37489434 100644 --- a/ets1.2/interop/src/cpp/SerializerBase.h +++ b/ets1.2/interop/src/cpp/SerializerBase.h @@ -116,7 +116,8 @@ public: return position; } - inline void check(int more) { + inline void check(int more) + { if (position + more > dataLength) { if (ownData) { constexpr auto NUM_2{2}; diff --git a/ets1.2/interop/src/cpp/common-interop.cc b/ets1.2/interop/src/cpp/common-interop.cc index e3a7e25a7..1e8341873 100644 --- a/ets1.2/interop/src/cpp/common-interop.cc +++ b/ets1.2/interop/src/cpp/common-interop.cc @@ -266,12 +266,12 @@ struct ForeignVMContext { KVMContext vmContext; int32_t (*callSync)(KVMContext vmContext, int32_t callback, uint8_t* data, int32_t length); }; -typedef KInt (*LoadVirtualMachine_t)(KInt vmKind, const char* bootFiles, const char* userFiles, const char* libraryPath, +typedef KInt (*LoadVirtualMachineT)(KInt vmKind, const char* bootFiles, const char* userFiles, const char* libraryPath, const struct ForeignVMContext* foreignVM); -typedef KNativePointer (*StartApplication_t)(const char* appUrl, const char* appParams, int32_t loopIterationr); -typedef KBoolean (*RunApplication_t)(const KInt arg0, const KInt arg1); -typedef const char* (*EmitEvent_t)(const KInt type, const KInt target, const KInt arg0, const KInt arg1); -typedef void (*RestartWith_t)(const char* page); +typedef KNativePointer (*StartApplicationT)(const char* appUrl, const char* appParams, int32_t loopIterationr); +typedef KBoolean (*RunApplicationT)(const KInt arg0, const KInt arg1); +typedef const char* (*EmitEventT)(const KInt type, const KInt target, const KInt arg0, const KInt arg1); +typedef void (*RestartWithT)(const char* page); typedef const char* (*LoadView_t)(const char* className, const char* params); void* getImpl(const char* path, const char* name) @@ -301,11 +301,13 @@ KInt impl_LoadVirtualMachine(KVMContext vmContext, KInt vmKind, const KStringPtr const char* bootFilesPath = envClassPath ? envClassPath : bootFiles.c_str(); const char* nativeLibPath = envClassPath ? envClassPath : libraryPath.c_str(); - static LoadVirtualMachine_t impl = nullptr; - if (!impl) - impl = reinterpret_cast(getImpl(nativeLibPath, "LoadVirtualMachine")); - if (!impl) + static LoadVirtualMachineT impl = nullptr; + if (!impl) { + impl = reinterpret_cast(getImpl(nativeLibPath, "LoadVirtualMachine")); + } + if (!impl) { KOALA_INTEROP_THROW_STRING(vmContext, "Cannot load VM", -1); + } const ForeignVMContext foreignVM = { vmContext, &callCallback }; return impl(vmKind, bootFilesPath, userFiles.c_str(), nativeLibPath, &foreignVM); } @@ -313,27 +315,30 @@ KOALA_INTEROP_CTX_4(LoadVirtualMachine, KInt, KInt, KStringPtr, KStringPtr, KStr KNativePointer impl_StartApplication(const KStringPtr& appUrl, const KStringPtr& appParams, KInt loopIterations) { - static StartApplication_t impl = nullptr; - if (!impl) - impl = reinterpret_cast(getImpl(nullptr, "StartApplication")); + static StartApplicationT impl = nullptr; + if (!impl) { + impl = reinterpret_cast(getImpl(nullptr, "StartApplication")); + } return impl(appUrl.c_str(), appParams.c_str(), loopIterations); } KOALA_INTEROP_3(StartApplication, KNativePointer, KStringPtr, KStringPtr, KInt) KBoolean impl_RunApplication(const KInt arg0, const KInt arg1) { - static RunApplication_t impl = nullptr; - if (!impl) - impl = reinterpret_cast(getImpl(nullptr, "RunApplication")); + static RunApplicationT impl = nullptr; + if (!impl) { + impl = reinterpret_cast(getImpl(nullptr, "RunApplication")); + } return impl(arg0, arg1); } KOALA_INTEROP_2(RunApplication, KBoolean, KInt, KInt) KStringPtr impl_EmitEvent(KVMContext vmContext, KInt type, KInt target, KInt arg0, KInt arg1) { - static EmitEvent_t impl = nullptr; - if (!impl) - impl = reinterpret_cast(getImpl(nullptr, "EmitEvent")); + static EmitEventT impl = nullptr; + if (!impl) { + impl = reinterpret_cast(getImpl(nullptr, "EmitEvent")); + } const char* out = impl(type, target, arg0, arg1); auto size = std::string(out).size(); KStringPtr result(out, size, true); @@ -343,9 +348,10 @@ KOALA_INTEROP_CTX_4(EmitEvent, KStringPtr, KInt, KInt, KInt, KInt) void impl_RestartWith(const KStringPtr& page) { - static RestartWith_t impl = nullptr; - if (!impl) - impl = reinterpret_cast(getImpl(nullptr, "RestartWith")); + static RestartWithT impl = nullptr; + if (!impl) { + impl = reinterpret_cast(getImpl(nullptr, "RestartWith")); + } impl(page.c_str()); } KOALA_INTEROP_V1(RestartWith, KStringPtr) @@ -354,8 +360,9 @@ KOALA_INTEROP_V1(RestartWith, KStringPtr) KStringPtr impl_LoadView(const KStringPtr& className, const KStringPtr& params) { static LoadView_t impl = nullptr; - if (!impl) + if (!impl) { impl = reinterpret_cast(getImpl(nullptr, "LoadView")); + } const char* result = impl(className.c_str(), params.c_str()); return KStringPtr(result, interop_strlen(result), true); } @@ -439,7 +446,7 @@ static Callback_Caller_Sync_t g_callbackCallerSync[API_KIND_MAX] = { 0 }; #define CHECK_HAS_CALLBACK_CALLER(apiKind, callbackCallers) \ CHECK_VALID_API_KIND(apiKind); \ if ((callbackCallers)[apiKind] == nullptr) \ - INTEROP_FATAL("Callback caller for api kind %d was not set", apiKind) + INTEROP_FATAL("Callback caller for api kind %d was not set", apiKind); #define CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, callbackCallers) \ CHECK_VALID_API_KIND(apiKind); \ if ((callbackCallers)[apiKind] != nullptr) \ @@ -605,12 +612,14 @@ KVMDeferred* CreateDeferred(KVMContext vmContext, KVMObjectHandle* promiseHandle napi_value resourceName; napi_create_string_utf8(env, "Async", sizeof("Async"), &resourceName); auto status = napi_create_promise(env, (napi_deferred*)&deferred->context, &promise); - if (status != napi_ok) + if (status != napi_ok) { LOGE("cannot make a promise; status=%d", status); + } status = napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, nullptr, nullptr, deferred, (napi_threadsafe_function_call_js)resolveDeferredImpl, (napi_threadsafe_function*)&deferred->handler); - if (status != napi_ok) + if (status != napi_ok) { LOGE("cannot make threadsafe function; status=%d", status); + } *promiseHandle = (KVMObjectHandle)promise; #endif #ifdef KOALA_ANI @@ -629,7 +638,8 @@ KVMDeferred* CreateDeferred(KVMContext vmContext, KVMObjectHandle* promiseHandle return deferred; } -class KoalaWork { +class KoalaWork +{ protected: InteropVMContext vmContext; #ifdef KOALA_FOREIGN_NAPI @@ -799,8 +809,7 @@ KStringPtr impl_RawUtf8ToString(KVMContext vmContext, KNativePointer data) KOALA_INTEROP_CTX_1(RawUtf8ToString, KStringPtr, KNativePointer) #endif -#if defined(KOALA_NAPI) || defined(KOALA_JNI) || defined(KOALA_CJ) || defined(KOALA_ETS_NAPI) || defined(KOALA_ANI) || \ - defined(KOALA_KOTLIN) +#if defined(KOALA_NAPI) || defined(KOALA_JNI) || defined(KOALA_CJ) || defined(KOALA_ETS_NAPI) || defined(KOALA_ANI) KStringPtr impl_StdStringToString(KVMContext vmContext, KNativePointer stringPtr) { std::string* string = reinterpret_cast(stringPtr); @@ -820,10 +829,11 @@ KOALA_INTEROP_CTX_2(RawReturnData, KInteropReturnBuffer, KInt, KInt) KInteropNumber impl_IncrementNumber(KInteropNumber number) { - if (number.tag == 102) + if (number.tag == 102) { number.i32++; - else + } else { number.f32 += 1.f; + } return number; } KOALA_INTEROP_1(IncrementNumber, KInteropNumber, KInteropNumber) diff --git a/ets1.2/interop/src/cpp/vmloader.cc b/ets1.2/interop/src/cpp/vmloader.cc index 92e2a967c..bba92278e 100644 --- a/ets1.2/interop/src/cpp/vmloader.cc +++ b/ets1.2/interop/src/cpp/vmloader.cc @@ -309,8 +309,8 @@ static bool ResetErrorIfExists(ani_env* env) std::string makeLibPath(const char* sdkPath, const char* platform, const char* lib) { std::string result; - constexpr uint16_t COUNT = 255; - result.reserve(COUNT); + constexpr uint16_t count = 255; + result.reserve(count); if (sdkPath) { result.append(sdkPath).append("/"); } diff --git a/ets1.2/libarkts/gn/command/copy.py b/ets1.2/libarkts/gn/command/copy.py index ca0e1fc7a..b7afc2b1a 100755 --- a/ets1.2/libarkts/gn/command/copy.py +++ b/ets1.2/libarkts/gn/command/copy.py @@ -24,6 +24,7 @@ def library_ext(os_name, cpu_name): return 'dll' return 'node' + def copy_files(source_path, dest_path, is_file=False): try: if is_file: @@ -46,7 +47,6 @@ def run_cmd(cmd, execution_path=None): raise Exception(stdout.decode() + stderr.decode()) - def copy_output(options): library_extention = library_ext(options.current_os, options.current_cpu) diff --git a/ets1.2/libarkts/gn/command/copy_file.py b/ets1.2/libarkts/gn/command/copy_file.py index 2bf645cfc..aea22a5a5 100755 --- a/ets1.2/libarkts/gn/command/copy_file.py +++ b/ets1.2/libarkts/gn/command/copy_file.py @@ -17,6 +17,7 @@ import os import sys import shutil + def copy_files(source_path, dest_path): try: if not os.path.isdir(source_path): @@ -27,6 +28,7 @@ def copy_files(source_path, dest_path): except Exception as err: raise Exception("Copy files failed. Error: " + str(err)) from err + def main(): dst = sys.argv[-1] srcs = sys.argv[1:-1] @@ -34,5 +36,6 @@ def main(): for src in srcs: copy_files(src, dst) + if __name__ == '__main__': sys.exit(main()) \ No newline at end of file diff --git a/ets1.2/libarkts/gn/command/copy_libs.py b/ets1.2/libarkts/gn/command/copy_libs.py index 6c57dceec..d5a40ada4 100755 --- a/ets1.2/libarkts/gn/command/copy_libs.py +++ b/ets1.2/libarkts/gn/command/copy_libs.py @@ -24,6 +24,7 @@ def get_compiler_name(os_name, cpu_name): return 'mingw_x86_64' return 'clang_x64' + def library_ext(os_name, cpu_name): if (os_name == 'mingw' and cpu_name == 'x86_64'): return 'dll' @@ -59,7 +60,6 @@ def run_cmd(cmd, execution_path=None): raise Exception(stderr.decode()) - def copy_output(options): compiler = get_compiler_name(options.current_os, options.current_cpu) diff --git a/ets1.2/libarkts/gn/command/gen_sdk.py b/ets1.2/libarkts/gn/command/gen_sdk.py index f5e324a72..458cac385 100755 --- a/ets1.2/libarkts/gn/command/gen_sdk.py +++ b/ets1.2/libarkts/gn/command/gen_sdk.py @@ -23,15 +23,18 @@ def load_config(config_file): config = json.load(f) return config + def get_compiler_type(os_name, cpu_name): if (os_name == 'mingw' and cpu_name == 'x86_64'): return 'mingw_x86_64' return 'clang_x64' + def replace_out_root(value, out_root, compiler_type): """Replace $out_root in the string with the actual value.""" return value.replace("$out_root", out_root).replace("$compiler_type", compiler_type) + def validate_out_root(out_root, compiler_type): head_out_root, tail_out_root = os.path.split(out_root) if (tail_out_root == compiler_type): diff --git a/ets1.2/libarkts/native/src/common.cc b/ets1.2/libarkts/native/src/common.cc index ec02f466b..82654b6d6 100644 --- a/ets1.2/libarkts/native/src/common.cc +++ b/ets1.2/libarkts/native/src/common.cc @@ -136,7 +136,8 @@ void impl_SetUpSoPath(KStringPtr &soPath) KOALA_INTEROP_V1(SetUpSoPath, KStringPtr); // Improve: simplify this -void* FindLibrary() { +void* FindLibrary() +{ void *res = nullptr; std::vector pathArray; @@ -205,7 +206,8 @@ char* getStringCopy(KStringPtr& ptr) return StageArena::strdup(ptr.c_str() ? ptr.c_str() : ""); } -KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr) { +KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr) +{ const std::size_t headerLen = 4; const char** argv = StageArena::allocArray(argc); @@ -221,14 +223,16 @@ KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr) { } KOALA_INTEROP_2(CreateConfig, KNativePointer, KInt, KStringArray) -KNativePointer impl_DestroyConfig(KNativePointer configPtr) { +KNativePointer impl_DestroyConfig(KNativePointer configPtr) +{ auto config = reinterpret_cast(configPtr); GetImpl()->DestroyConfig(config); return nullptr; } KOALA_INTEROP_1(DestroyConfig, KNativePointer, KNativePointer) -void impl_DestroyContext(KNativePointer contextPtr) { +void impl_DestroyContext(KNativePointer contextPtr) +{ auto context = reinterpret_cast(contextPtr); GetImpl()->DestroyContext(context); StageArena::instance()->cleanup(); @@ -244,7 +248,8 @@ KNativePointer impl_UpdateCallExpression( KNativePointer typeParamsPtr, KBoolean optionalT, KBoolean trailingCommaT -) { +) +{ auto node = reinterpret_cast(nodePtr); auto context = reinterpret_cast(contextPtr); auto callee = reinterpret_cast(calleePtr); @@ -261,7 +266,8 @@ KNativePointer impl_UpdateCallExpression( } KOALA_INTEROP_8(UpdateCallExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KNativePointer, KBoolean, KBoolean) -KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer nodePtr) { +KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer nodePtr) +{ auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -272,7 +278,8 @@ KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer no } KOALA_INTEROP_2(IdentifierIdentifierFlags, KInt, KNativePointer, KNativePointer) -void impl_ClassDefinitionSetBody(KNativePointer context, KNativePointer receiver, KNativePointerArray body, KUInt bodyLength) { +void impl_ClassDefinitionSetBody(KNativePointer context, KNativePointer receiver, KNativePointerArray body, KUInt bodyLength) +{ const auto _context = reinterpret_cast(context); const auto _receiver = reinterpret_cast(receiver); const auto _body = reinterpret_cast(body); @@ -289,8 +296,8 @@ Improve: NOT FROM API (shouldn't be there) ----------------------------------------------------------------------------------------------------------------------------- */ -es2panda_AstNode * cachedParentNode; -es2panda_Context * cachedContext; +es2panda_AstNode* cachedParentNode; +es2panda_Context* cachedContext; static void changeParent(es2panda_AstNode *child) { @@ -306,7 +313,8 @@ static void SetRightParent(es2panda_AstNode *node, void *arg) GetImpl()->AstNodeIterateConst(ctx, node, changeParent); } -KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer programPtr) { +KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer programPtr) +{ auto context = reinterpret_cast(contextPtr); auto program = reinterpret_cast(programPtr); @@ -315,7 +323,8 @@ KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer p } KOALA_INTEROP_2(AstNodeUpdateAll, KNativePointer, KNativePointer, KNativePointer) -void impl_AstNodeSetChildrenParentPtr(KNativePointer contextPtr, KNativePointer nodePtr) { +void impl_AstNodeSetChildrenParentPtr(KNativePointer contextPtr, KNativePointer nodePtr) +{ auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); cachedParentNode = node; @@ -324,7 +333,8 @@ void impl_AstNodeSetChildrenParentPtr(KNativePointer contextPtr, KNativePointer } KOALA_INTEROP_V2(AstNodeSetChildrenParentPtr, KNativePointer, KNativePointer) -void impl_AstNodeOnUpdate(KNativePointer context, KNativePointer newNode, KNativePointer replacedNode) { +void impl_AstNodeOnUpdate(KNativePointer context, KNativePointer newNode, KNativePointer replacedNode) +{ auto _context = reinterpret_cast(context); auto _newNode = reinterpret_cast(newNode); auto _replacedNode = reinterpret_cast(replacedNode); @@ -357,7 +367,8 @@ static void visitChild(es2panda_AstNode *node) KNativePointer impl_AstNodeChildren( KNativePointer contextPtr, KNativePointer nodePtr -) { +) +{ auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); cachedContext = context; @@ -368,18 +379,22 @@ KNativePointer impl_AstNodeChildren( } KOALA_INTEROP_2(AstNodeChildren, KNativePointer, KNativePointer, KNativePointer); -struct Pattern { +struct Pattern +{ es2panda_Context* context; std::string key; std::string value; es2panda_Impl* impl; - Pattern(es2panda_Context* context, const std::string& part): context(context), impl(GetImpl()){ + Pattern(es2panda_Context* context, const std::string& part): context(context), impl(GetImpl()) + { std::istringstream stream(part); std::getline(stream, key, '='); std::getline(stream, value, '='); } - bool match(es2panda_AstNode* node) { + + bool match(es2panda_AstNode* node) + { if (key == "type") { auto type = impl->AstNodeTypeConst(context, node); switch (type) { @@ -422,19 +437,22 @@ struct Pattern { } }; -struct Matcher { +struct Matcher +{ es2panda_Context* context; const char* query; std::vector patterns; es2panda_Impl* impl; - Matcher(es2panda_Context* context, const char* query) : context(context), query(query), impl(GetImpl()) { + Matcher(es2panda_Context* context, const char* query) : context(context), query(query), impl(GetImpl()) + { std::istringstream stream(query); std::string item; while (std::getline(stream, item, ';')) { patterns.emplace_back(Pattern(context, item)); } } - bool match(es2panda_AstNode* node) { + bool match(es2panda_AstNode* node) + { bool result = true; for (auto pattern: patterns) { result &= pattern.match(node); diff --git a/ets1.2/libarkts/native/src/common.h b/ets1.2/libarkts/native/src/common.h index 0ee7cd1d7..371b349dd 100644 --- a/ets1.2/libarkts/native/src/common.h +++ b/ets1.2/libarkts/native/src/common.h @@ -45,7 +45,8 @@ using std::string, std::cout, std::endl, std::vector; extern es2panda_Impl *es2pandaImplementation; es2panda_Impl *GetImplSlow(); -inline es2panda_Impl *GetImpl() { +inline es2panda_Impl *GetImpl() +{ if (es2pandaImplementation) { return es2pandaImplementation; } @@ -76,7 +77,8 @@ inline KUInt unpackUInt(const KByte* bytes) es2panda_ContextState intToState(KInt state); -class StageArena { +class StageArena +{ std::vector allocated; size_t totalSize; public: diff --git a/ets1.2/libarkts/native/src/memoryTracker.cc b/ets1.2/libarkts/native/src/memoryTracker.cc index c12fcd248..667a95c08 100644 --- a/ets1.2/libarkts/native/src/memoryTracker.cc +++ b/ets1.2/libarkts/native/src/memoryTracker.cc @@ -163,9 +163,18 @@ void MemoryTracker::Report(MemoryStats stats) const double mb = kb * BYTES_PER_KB; const double gb = mb * BYTES_PER_KB; - if (bytes > gb) return std::to_string(bytes / gb) + " GB"; - if (bytes > mb) return std::to_string(bytes / mb) + " MB"; - if (bytes > kb) return std::to_string(bytes / kb) + " KB"; + if (bytes > gb) { + return std::to_string(bytes / gb) + " GB"; + } + + if (bytes > mb) { + return std::to_string(bytes / mb) + " MB"; + } + + if (bytes > kb) { + return std::to_string(bytes / kb) + " KB"; + } + return std::to_string(bytes) + " B"; }; -- Gitee From 501e181cc6e3d56bfb72b5f05931834433c6e9b3 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 11:55:48 +0300 Subject: [PATCH 06/14] codecheck4 Signed-off-by: Korobeinikov Evgeny Change-Id: I52a394232fd60dbfda7eb755ba86aae6d30aad49 --- ets1.2/interop/src/cpp/common-interop.cc | 39 ++++++++++++------------ ets1.2/interop/src/cpp/common-interop.h | 4 +-- ets1.2/libarkts/gn/command/copy.py | 1 + ets1.2/libarkts/gn/command/copy_libs.py | 1 + ets1.2/libarkts/gn/command/gen_sdk.py | 3 ++ ets1.2/libarkts/native/src/common.cc | 3 +- ets1.2/libarkts/native/src/common.h | 3 +- 7 files changed, 28 insertions(+), 26 deletions(-) diff --git a/ets1.2/interop/src/cpp/common-interop.cc b/ets1.2/interop/src/cpp/common-interop.cc index 1e8341873..9c41fcaa9 100644 --- a/ets1.2/interop/src/cpp/common-interop.cc +++ b/ets1.2/interop/src/cpp/common-interop.cc @@ -49,7 +49,7 @@ InteropProfiler* InteropProfiler::_instance = nullptr; using std::string; #ifndef KOALA_INTEROP_MEM_ANALYZER -static std::atomic mallocCounter { 0 }; +static std::atomic g_mallocCounter { 0 }; #endif #if defined(KOALA_NAPI) || defined(KOALA_ANI) @@ -272,9 +272,9 @@ typedef KNativePointer (*StartApplicationT)(const char* appUrl, const char* appP typedef KBoolean (*RunApplicationT)(const KInt arg0, const KInt arg1); typedef const char* (*EmitEventT)(const KInt type, const KInt target, const KInt arg0, const KInt arg1); typedef void (*RestartWithT)(const char* page); -typedef const char* (*LoadView_t)(const char* className, const char* params); +typedef const char* (*LoadViewT)(const char* className, const char* params); -void* getImpl(const char* path, const char* name) +void* GetImpl(const char* path, const char* name) { static void* lib = nullptr; if (!lib && name) { @@ -303,7 +303,7 @@ KInt impl_LoadVirtualMachine(KVMContext vmContext, KInt vmKind, const KStringPtr static LoadVirtualMachineT impl = nullptr; if (!impl) { - impl = reinterpret_cast(getImpl(nativeLibPath, "LoadVirtualMachine")); + impl = reinterpret_cast(GetImpl(nativeLibPath, "LoadVirtualMachine")); } if (!impl) { KOALA_INTEROP_THROW_STRING(vmContext, "Cannot load VM", -1); @@ -317,7 +317,7 @@ KNativePointer impl_StartApplication(const KStringPtr& appUrl, const KStringPtr& { static StartApplicationT impl = nullptr; if (!impl) { - impl = reinterpret_cast(getImpl(nullptr, "StartApplication")); + impl = reinterpret_cast(GetImpl(nullptr, "StartApplication")); } return impl(appUrl.c_str(), appParams.c_str(), loopIterations); } @@ -327,7 +327,7 @@ KBoolean impl_RunApplication(const KInt arg0, const KInt arg1) { static RunApplicationT impl = nullptr; if (!impl) { - impl = reinterpret_cast(getImpl(nullptr, "RunApplication")); + impl = reinterpret_cast(GetImpl(nullptr, "RunApplication")); } return impl(arg0, arg1); } @@ -337,7 +337,7 @@ KStringPtr impl_EmitEvent(KVMContext vmContext, KInt type, KInt target, KInt arg { static EmitEventT impl = nullptr; if (!impl) { - impl = reinterpret_cast(getImpl(nullptr, "EmitEvent")); + impl = reinterpret_cast(GetImpl(nullptr, "EmitEvent")); } const char* out = impl(type, target, arg0, arg1); auto size = std::string(out).size(); @@ -350,7 +350,7 @@ void impl_RestartWith(const KStringPtr& page) { static RestartWithT impl = nullptr; if (!impl) { - impl = reinterpret_cast(getImpl(nullptr, "RestartWith")); + impl = reinterpret_cast(GetImpl(nullptr, "RestartWith")); } impl(page.c_str()); } @@ -359,9 +359,9 @@ KOALA_INTEROP_V1(RestartWith, KStringPtr) #ifdef KOALA_ANI KStringPtr impl_LoadView(const KStringPtr& className, const KStringPtr& params) { - static LoadView_t impl = nullptr; + static LoadViewT impl = nullptr; if (!impl) { - impl = reinterpret_cast(getImpl(nullptr, "LoadView")); + impl = reinterpret_cast(GetImpl(nullptr, "LoadView")); } const char* result = impl(className.c_str(), params.c_str()); return KStringPtr(result, interop_strlen(result), true); @@ -376,7 +376,7 @@ KNativePointer impl_Malloc(KLong length) INTEROP_FATAL("Memory allocation failed!"); } #ifndef KOALA_INTEROP_MEM_ANALYZER - mallocCounter.fetch_add(1, std::memory_order_release); + g_mallocCounter.fetch_add(1, std::memory_order_release); #endif return ptr; } @@ -387,7 +387,7 @@ void malloc_finalize(KNativePointer data) if (data) { free(data); #ifndef KOALA_INTEROP_MEM_ANALYZER - if (mallocCounter.fetch_sub(1, std::memory_order_release) == 0) { + if (g_mallocCounter.fetch_sub(1, std::memory_order_release) == 0) { INTEROP_FATAL("Double-free detected!"); } #endif @@ -442,17 +442,17 @@ static Callback_Caller_Sync_t g_callbackCallerSync[API_KIND_MAX] = { 0 }; #define CHECK_VALID_API_KIND(apiKind) \ if ((apiKind) < 0 || (apiKind) > API_KIND_MAX) \ - INTEROP_FATAL("Maximum api kind is %d, received %d", API_KIND_MAX, apiKind); + INTEROP_FATAL("Maximum api kind is %d, received %d", API_KIND_MAX, apiKind) #define CHECK_HAS_CALLBACK_CALLER(apiKind, callbackCallers) \ CHECK_VALID_API_KIND(apiKind); \ if ((callbackCallers)[apiKind] == nullptr) \ - INTEROP_FATAL("Callback caller for api kind %d was not set", apiKind); + INTEROP_FATAL("Callback caller for api kind %d was not set", apiKind) #define CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, callbackCallers) \ CHECK_VALID_API_KIND(apiKind); \ if ((callbackCallers)[apiKind] != nullptr) \ - INTEROP_FATAL("Callback caller for api kind %d already was set", apiKind); + INTEROP_FATAL("Callback caller for api kind %d already was set", apiKind) -void setCallbackCaller(int apiKind, Callback_Caller_t callbackCaller) +void SetCallbackCaller(int apiKind, Callback_Caller_t callbackCaller) { CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, g_callbackCaller); g_callbackCaller[apiKind] = callbackCaller; @@ -465,7 +465,7 @@ void impl_CallCallback(KInt apiKind, KInt callbackKind, KSerializerBuffer args, } KOALA_INTEROP_V4(CallCallback, KInt, KInt, KSerializerBuffer, KInt) -void setCallbackCallerSync(int apiKind, Callback_Caller_Sync_t callbackCallerSync) +void SetCallbackCallerSync(int apiKind, Callback_Caller_Sync_t callbackCallerSync) { CHECK_HAS_NOT_CALLBACK_CALLER(apiKind, g_callbackCallerSync); g_callbackCallerSync[apiKind] = callbackCallerSync; @@ -638,8 +638,7 @@ KVMDeferred* CreateDeferred(KVMContext vmContext, KVMObjectHandle* promiseHandle return deferred; } -class KoalaWork -{ +class KoalaWork { protected: InteropVMContext vmContext; #ifdef KOALA_FOREIGN_NAPI @@ -841,7 +840,7 @@ KOALA_INTEROP_1(IncrementNumber, KInteropNumber, KInteropNumber) void impl_ReportMemLeaks() { #ifndef KOALA_INTEROP_MEM_ANALYZER - const auto count = mallocCounter.load(std::memory_order_acquire); + const auto count = g_mallocCounter.load(std::memory_order_acquire); if (count > 0) { fprintf(stderr, "Memory leaks detected: %d blocks\n", count); } else { diff --git a/ets1.2/interop/src/cpp/common-interop.h b/ets1.2/interop/src/cpp/common-interop.h index 3a5fa5cfc..8ee05f416 100644 --- a/ets1.2/interop/src/cpp/common-interop.h +++ b/ets1.2/interop/src/cpp/common-interop.h @@ -48,8 +48,8 @@ typedef void (*Callback_Caller_t)(KInt callbackKind, KSerializerBuffer argsData, KInt argsLength); typedef void (*Callback_Caller_Sync_t)( KVMContext vmContext, KInt callbackKind, KSerializerBuffer argsData, KInt argsLength); -extern "C" DLL_EXPORT void setCallbackCaller(int apiKind, Callback_Caller_t caller); -extern "C" DLL_EXPORT void setCallbackCallerSync(int apiKind, Callback_Caller_Sync_t callerSync); +extern "C" DLL_EXPORT void SetCallbackCaller(int apiKind, Callback_Caller_t caller); +extern "C" DLL_EXPORT void SetCallbackCallerSync(int apiKind, Callback_Caller_Sync_t callerSync); extern "C" DLL_EXPORT KVMDeferred* CreateDeferred(KVMContext context, KVMObjectHandle* promise); extern "C" DLL_EXPORT const InteropAsyncWorker* GetAsyncWorker(); diff --git a/ets1.2/libarkts/gn/command/copy.py b/ets1.2/libarkts/gn/command/copy.py index b7afc2b1a..8c8a87408 100755 --- a/ets1.2/libarkts/gn/command/copy.py +++ b/ets1.2/libarkts/gn/command/copy.py @@ -19,6 +19,7 @@ import shutil import subprocess import sys + def library_ext(os_name, cpu_name): if (os_name == 'mingw' and cpu_name == 'x86_64'): return 'dll' diff --git a/ets1.2/libarkts/gn/command/copy_libs.py b/ets1.2/libarkts/gn/command/copy_libs.py index d5a40ada4..47ab27d30 100755 --- a/ets1.2/libarkts/gn/command/copy_libs.py +++ b/ets1.2/libarkts/gn/command/copy_libs.py @@ -19,6 +19,7 @@ import shutil import subprocess import sys + def get_compiler_name(os_name, cpu_name): if (os_name == 'mingw' and cpu_name == 'x86_64'): return 'mingw_x86_64' diff --git a/ets1.2/libarkts/gn/command/gen_sdk.py b/ets1.2/libarkts/gn/command/gen_sdk.py index 458cac385..b91ef0a0f 100755 --- a/ets1.2/libarkts/gn/command/gen_sdk.py +++ b/ets1.2/libarkts/gn/command/gen_sdk.py @@ -17,6 +17,7 @@ import shutil import json import argparse + def load_config(config_file): """Load the configuration file.""" with open(config_file, 'r') as f: @@ -81,6 +82,7 @@ def copy_files(config, src_base, dist_base, out_root, compiler_type, substitutio except Exception as e: print(f"Failed to copy directory: {source} -> {destination}, error: {e}") + def main(): # Parse command-line arguments parser = argparse.ArgumentParser(description="Copy files or directories.") @@ -119,5 +121,6 @@ def main(): with open(os.path.join(args.dist, "package.json"), "w") as file: file.write(content) + if __name__ == '__main__': main() \ No newline at end of file diff --git a/ets1.2/libarkts/native/src/common.cc b/ets1.2/libarkts/native/src/common.cc index 82654b6d6..f6467ad5d 100644 --- a/ets1.2/libarkts/native/src/common.cc +++ b/ets1.2/libarkts/native/src/common.cc @@ -437,8 +437,7 @@ struct Pattern } }; -struct Matcher -{ +struct Matcher { es2panda_Context* context; const char* query; std::vector patterns; diff --git a/ets1.2/libarkts/native/src/common.h b/ets1.2/libarkts/native/src/common.h index 371b349dd..11b17a454 100644 --- a/ets1.2/libarkts/native/src/common.h +++ b/ets1.2/libarkts/native/src/common.h @@ -77,8 +77,7 @@ inline KUInt unpackUInt(const KByte* bytes) es2panda_ContextState intToState(KInt state); -class StageArena -{ +class StageArena { std::vector allocated; size_t totalSize; public: -- Gitee From a44db969128d767123f123ca4a701dc893d17de1 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 12:07:47 +0300 Subject: [PATCH 07/14] codecheck5 Signed-off-by: Korobeinikov Evgeny Change-Id: If83adafaa8411f3c746bb71d9200cadf419c1a80 --- ets1.2/libarkts/native/src/common.cc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ets1.2/libarkts/native/src/common.cc b/ets1.2/libarkts/native/src/common.cc index f6467ad5d..a652e3277 100644 --- a/ets1.2/libarkts/native/src/common.cc +++ b/ets1.2/libarkts/native/src/common.cc @@ -379,8 +379,7 @@ KNativePointer impl_AstNodeChildren( } KOALA_INTEROP_2(AstNodeChildren, KNativePointer, KNativePointer, KNativePointer); -struct Pattern -{ +struct Pattern { es2panda_Context* context; std::string key; std::string value; -- Gitee From 988f5e312b09405b9135eedaf230147f58ca85d1 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 13:08:59 +0300 Subject: [PATCH 08/14] codecheck6 Signed-off-by: Korobeinikov Evgeny Change-Id: I695bb8ae8b6e80629155559e7bb4b0d88aa512b4 --- ets1.2/libarkts/native/src/bridges.cc | 55 ++++++++++++++++++++------- ets1.2/libarkts/native/src/common.cc | 3 +- ets1.2/libarkts/native/src/common.h | 2 +- 3 files changed, 44 insertions(+), 16 deletions(-) diff --git a/ets1.2/libarkts/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index 63989bb45..64e0f0162 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -32,7 +32,9 @@ KNativePointer impl_AstNodeRebind(KNativePointer contextPtr, KNativePointer node } KOALA_INTEROP_2(AstNodeRebind, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_AnnotationAllowedAnnotations(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer returnLen) +KNativePointer impl_AnnotationAllowedAnnotations(KNativePointer contextPtr, KNativePointer nodePtr, + KNativePointer returnLen +) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -42,7 +44,9 @@ KNativePointer impl_AnnotationAllowedAnnotations(KNativePointer contextPtr, KNat } KOALA_INTEROP_3(AnnotationAllowedAnnotations, KNativePointer, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_AnnotationAllowedAnnotationsConst(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer returnLen) +KNativePointer impl_AnnotationAllowedAnnotationsConst(KNativePointer contextPtr, KNativePointer nodePtr, + KNativePointer returnLen +) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -158,7 +162,11 @@ static KNativePointer impl_ExternalSourcePrograms(KNativePointer instance) } KOALA_INTEROP_1(ExternalSourcePrograms, KNativePointer, KNativePointer); -KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, KInt importKinds, KNativePointerArray specifiers, KUInt specifiersSequenceLength, KNativePointer source, KNativePointer program, KInt importFlag) +KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, + KInt importKinds, KNativePointerArray specifiers, + KUInt specifiersSequenceLength, + KNativePointer source, KNativePointer program, KInt importFlag +) { const auto _context = reinterpret_cast(context); const auto _kinds = static_cast(importKinds); @@ -168,9 +176,11 @@ KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, KInt const auto _program = reinterpret_cast(program); const auto _importFlag = static_cast(importFlag); - return GetImpl()->ETSParserBuildImportDeclaration(_context, _kinds, _specifiers, _specifiersSequenceLength, _source, _program, _importFlag); + return GetImpl()->ETSParserBuildImportDeclaration(_context, _kinds, _specifiers, + _specifiersSequenceLength, _source, _program, _importFlag); } -KOALA_INTEROP_7(ETSParserBuildImportDeclaration, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt, KNativePointer, KNativePointer, KInt) +KOALA_INTEROP_7(ETSParserBuildImportDeclaration, KNativePointer, KNativePointer, KInt, + KNativePointerArray, KUInt, KNativePointer, KNativePointer, KInt) KNativePointer impl_ETSParserGetImportPathManager(KNativePointer contextPtr) { @@ -204,14 +214,22 @@ KNativePointer impl_OptionsArkTsConfig(KNativePointer context, KNativePointer op } KOALA_INTEROP_2(OptionsArkTsConfig, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_CreateCacheContextFromFile(KNativePointer configPtr, KStringPtr& source_file_namePtr, KNativePointer globalContextPtr, KBoolean isExternal) { +KNativePointer impl_CreateCacheContextFromFile(KNativePointer configPtr, KStringPtr& source_file_namePtr, + KNativePointer globalContextPtr, KBoolean isExternal +) { auto config = reinterpret_cast(configPtr); auto globalContext = reinterpret_cast(globalContextPtr); - return GetImpl()->CreateCacheContextFromFile(config, getStringCopy(source_file_namePtr), globalContext, isExternal); + return GetImpl()->CreateCacheContextFromFile(config, + getStringCopy(source_file_namePtr), + globalContext, + isExternal + ); } KOALA_INTEROP_4(CreateCacheContextFromFile, KNativePointer, KNativePointer, KStringPtr, KNativePointer, KBoolean) -KNativePointer impl_CreateGlobalContext(KNativePointer configPtr, KStringArray externalFileListPtr, KUInt fileNum, KBoolean LspUsage) { +KNativePointer impl_CreateGlobalContext(KNativePointer configPtr, KStringArray externalFileListPtr, + KUInt fileNum, KBoolean LspUsage +) { auto config = reinterpret_cast(configPtr); const int headerLen = 4; const char** files = StageArena::allocArray(fileNum); @@ -279,7 +297,9 @@ KNativePointer impl_Checker_ScriptFunctionGetPreferredReturnType(KNativePointer } KOALA_INTEROP_2(Checker_ScriptFunctionGetPreferredReturnType, KNativePointer, KNativePointer, KNativePointer) -void impl_Checker_ScriptFunctionSetPreferredReturnType(KNativePointer context, KNativePointer node, KNativePointer type) +void impl_Checker_ScriptFunctionSetPreferredReturnType(KNativePointer context, KNativePointer node, + KNativePointer type +) { auto _context = reinterpret_cast(context); auto _node = reinterpret_cast(node); @@ -437,7 +457,8 @@ KOALA_INTEROP_5(CreateDiagnosticInfo, KNativePointer, KNativePointer, KNativePoi KStringArray, KInt, KNativePointer) KNativePointer impl_CreateSuggestionInfo(KNativePointer context, KNativePointer kind, KStringArray argsPtr, - KInt argc, KStringPtr& substitutionCode, KStringPtr& title, KNativePointer range) + KInt argc, KStringPtr& substitutionCode, KStringPtr& title, KNativePointer range +) { const auto _context = reinterpret_cast(context); const auto _kind = reinterpret_cast(kind); @@ -489,13 +510,19 @@ KNativePointer impl_AnnotationUsageIrPropertiesPtrConst(KNativePointer context, } KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); -KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr &outputDeclEts, KStringPtr &outputEts, - KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations) +KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, + KStringPtr &outputDeclEts, + KStringPtr &outputEts, + KBoolean exportAll, KBoolean isolated, + KStringPtr &recordFile, KBoolean genAnnotations +) { auto context = reinterpret_cast(contextPtr); - return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), exportAll, isolated, recordFile.data(), genAnnotations); + return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), + exportAll, isolated, recordFile.data(), genAnnotations); } -KOALA_INTEROP_7(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean, KBoolean, KStringPtr, KBoolean) +KOALA_INTEROP_7(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, + KStringPtr, KBoolean, KBoolean, KStringPtr, KBoolean) // Improve: simplify KNativePointer impl_CreateContextGenerateAbcForExternalSourceFiles( diff --git a/ets1.2/libarkts/native/src/common.cc b/ets1.2/libarkts/native/src/common.cc index a652e3277..fc0bde406 100644 --- a/ets1.2/libarkts/native/src/common.cc +++ b/ets1.2/libarkts/native/src/common.cc @@ -278,7 +278,8 @@ KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer no } KOALA_INTEROP_2(IdentifierIdentifierFlags, KInt, KNativePointer, KNativePointer) -void impl_ClassDefinitionSetBody(KNativePointer context, KNativePointer receiver, KNativePointerArray body, KUInt bodyLength) +void impl_ClassDefinitionSetBody(KNativePointer context, KNativePointer receiver, KNativePointerArray body, + KUInt bodyLength) { const auto _context = reinterpret_cast(context); const auto _receiver = reinterpret_cast(receiver); diff --git a/ets1.2/libarkts/native/src/common.h b/ets1.2/libarkts/native/src/common.h index 11b17a454..df14513d2 100644 --- a/ets1.2/libarkts/native/src/common.h +++ b/ets1.2/libarkts/native/src/common.h @@ -57,7 +57,7 @@ string getString(KStringPtr ptr); char* getStringCopy(KStringPtr& ptr); -inline KUInt unpackUInt(const KByte* bytes) +KUInt unpackUInt(const KByte* bytes) { const KUInt BYTE_0 = 0; const KUInt BYTE_1 = 1; -- Gitee From 8894960bc45f7f3592d6919f03d3fefe077cf7c5 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 13:22:13 +0300 Subject: [PATCH 09/14] codecheck7 Signed-off-by: Korobeinikov Evgeny Change-Id: I02f649a7797b1466054c311988aea7aca39569e4 --- ets1.2/libarkts/native/src/bridges.cc | 24 ++++++++++-------------- ets1.2/libarkts/native/src/common.cc | 5 +++-- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/ets1.2/libarkts/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index 64e0f0162..9f7a7c82e 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -162,11 +162,9 @@ static KNativePointer impl_ExternalSourcePrograms(KNativePointer instance) } KOALA_INTEROP_1(ExternalSourcePrograms, KNativePointer, KNativePointer); -KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, - KInt importKinds, KNativePointerArray specifiers, - KUInt specifiersSequenceLength, - KNativePointer source, KNativePointer program, KInt importFlag -) +KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, KInt importKinds, + KNativePointerArray specifiers, KUInt specifiersSequenceLength, + KNativePointer source, KNativePointer program, KInt importFlag) { const auto _context = reinterpret_cast(context); const auto _kinds = static_cast(importKinds); @@ -179,7 +177,7 @@ KNativePointer impl_ETSParserBuildImportDeclaration(KNativePointer context, return GetImpl()->ETSParserBuildImportDeclaration(_context, _kinds, _specifiers, _specifiersSequenceLength, _source, _program, _importFlag); } -KOALA_INTEROP_7(ETSParserBuildImportDeclaration, KNativePointer, KNativePointer, KInt, +KOALA_INTEROP_7(ETSParserBuildImportDeclaration, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt, KNativePointer, KNativePointer, KInt) KNativePointer impl_ETSParserGetImportPathManager(KNativePointer contextPtr) @@ -219,7 +217,7 @@ KNativePointer impl_CreateCacheContextFromFile(KNativePointer configPtr, KString ) { auto config = reinterpret_cast(configPtr); auto globalContext = reinterpret_cast(globalContextPtr); - return GetImpl()->CreateCacheContextFromFile(config, + return GetImpl()->CreateCacheContextFromFile(config, getStringCopy(source_file_namePtr), globalContext, isExternal @@ -297,7 +295,7 @@ KNativePointer impl_Checker_ScriptFunctionGetPreferredReturnType(KNativePointer } KOALA_INTEROP_2(Checker_ScriptFunctionGetPreferredReturnType, KNativePointer, KNativePointer, KNativePointer) -void impl_Checker_ScriptFunctionSetPreferredReturnType(KNativePointer context, KNativePointer node, +void impl_Checker_ScriptFunctionSetPreferredReturnType(KNativePointer context, KNativePointer node, KNativePointer type ) { @@ -510,16 +508,14 @@ KNativePointer impl_AnnotationUsageIrPropertiesPtrConst(KNativePointer context, } KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); -KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, - KStringPtr &outputDeclEts, +KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr &outputDeclEts, KStringPtr &outputEts, - KBoolean exportAll, KBoolean isolated, - KStringPtr &recordFile, KBoolean genAnnotations -) + KBoolean exportAll, KBoolean isolated, + KStringPtr &recordFile, KBoolean genAnnotations) { auto context = reinterpret_cast(contextPtr); return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), - exportAll, isolated, recordFile.data(), genAnnotations); + exportAll, isolated, recordFile.data(), genAnnotations); } KOALA_INTEROP_7(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean, KBoolean, KStringPtr, KBoolean) diff --git a/ets1.2/libarkts/native/src/common.cc b/ets1.2/libarkts/native/src/common.cc index fc0bde406..bee1c1ba2 100644 --- a/ets1.2/libarkts/native/src/common.cc +++ b/ets1.2/libarkts/native/src/common.cc @@ -264,7 +264,8 @@ KNativePointer impl_UpdateCallExpression( GetImpl()->AstNodeSetOriginalNode(context, nn, node); return nn; } -KOALA_INTEROP_8(UpdateCallExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KNativePointer, KBoolean, KBoolean) +KOALA_INTEROP_8(UpdateCallExpression, KNativePointer, KNativePointer, KNativePointer, + KNativePointer, KNativePointerArray, KInt, KNativePointer, KBoolean, KBoolean) KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer nodePtr) { @@ -278,7 +279,7 @@ KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer no } KOALA_INTEROP_2(IdentifierIdentifierFlags, KInt, KNativePointer, KNativePointer) -void impl_ClassDefinitionSetBody(KNativePointer context, KNativePointer receiver, KNativePointerArray body, +void impl_ClassDefinitionSetBody(KNativePointer context, KNativePointer receiver, KNativePointerArray body, KUInt bodyLength) { const auto _context = reinterpret_cast(context); -- Gitee From 83a6f9273b22beb5e5a15b5dfea1a0ab550172be Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 13:30:33 +0300 Subject: [PATCH 10/14] codecheck8 Signed-off-by: Korobeinikov Evgeny Change-Id: I2eb31ce301a86c360662ed26b0f59a7e3552000f --- ets1.2/libarkts/native/src/bridges.cc | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ets1.2/libarkts/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index 9f7a7c82e..b6191e887 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -509,15 +509,13 @@ KNativePointer impl_AnnotationUsageIrPropertiesPtrConst(KNativePointer context, KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr &outputDeclEts, - KStringPtr &outputEts, - KBoolean exportAll, KBoolean isolated, - KStringPtr &recordFile, KBoolean genAnnotations) + KStringPtr &outputEts, KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations) { auto context = reinterpret_cast(contextPtr); return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), exportAll, isolated, recordFile.data(), genAnnotations); } -KOALA_INTEROP_7(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, +KOALA_INTEROP_7(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean, KBoolean, KStringPtr, KBoolean) // Improve: simplify -- Gitee From eb81adb5677a78082ad0ae11d8f98c3043ed5694 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 13:39:41 +0300 Subject: [PATCH 11/14] codecheck9 Signed-off-by: Korobeinikov Evgeny Change-Id: I85deb884a329d44f83d20cb3642a71f0ba2754e7 --- ets1.2/libarkts/native/src/bridges.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ets1.2/libarkts/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index b6191e887..c944da685 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -509,7 +509,8 @@ KNativePointer impl_AnnotationUsageIrPropertiesPtrConst(KNativePointer context, KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr &outputDeclEts, - KStringPtr &outputEts, KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations) + KStringPtr &outputEts, KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations +) { auto context = reinterpret_cast(contextPtr); return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), -- Gitee From 32fea08bae02378e9deabb6ff2f0a5fe242a39fe Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 13:48:17 +0300 Subject: [PATCH 12/14] codecheck10 Signed-off-by: Korobeinikov Evgeny Change-Id: I67adf9bb9e03c4da7404f645e33aec787f71549e --- ets1.2/libarkts/native/src/bridges.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ets1.2/libarkts/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index c944da685..e5f87ef4e 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -508,8 +508,9 @@ KNativePointer impl_AnnotationUsageIrPropertiesPtrConst(KNativePointer context, } KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); -KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr &outputDeclEts, - KStringPtr &outputEts, KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations +KInt impl_GenerateTsDeclarationsFromContext( + KNativePointer contextPtr, KStringPtr &outputDeclEts, KStringPtr &outputEts, + KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations ) { auto context = reinterpret_cast(contextPtr); -- Gitee From c909bb1299323fac85a37757683c074cb73f94aa Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 13:55:48 +0300 Subject: [PATCH 13/14] codecheck11 Signed-off-by: Korobeinikov Evgeny Change-Id: I71af37b6afd67161ffa3e1b2cb9c142bdef7e275 --- ets1.2/libarkts/native/src/bridges.cc | 3 +-- ets1.2/libarkts/native/src/common.h | 11 +++-------- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/ets1.2/libarkts/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index e5f87ef4e..b196fa502 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -510,8 +510,7 @@ KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePoin KInt impl_GenerateTsDeclarationsFromContext( KNativePointer contextPtr, KStringPtr &outputDeclEts, KStringPtr &outputEts, - KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations -) + KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations) { auto context = reinterpret_cast(contextPtr); return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), diff --git a/ets1.2/libarkts/native/src/common.h b/ets1.2/libarkts/native/src/common.h index df14513d2..086246dcb 100644 --- a/ets1.2/libarkts/native/src/common.h +++ b/ets1.2/libarkts/native/src/common.h @@ -57,22 +57,17 @@ string getString(KStringPtr ptr); char* getStringCopy(KStringPtr& ptr); -KUInt unpackUInt(const KByte* bytes) +inline KUInt unpackUInt(const KByte* bytes) { const KUInt BYTE_0 = 0; const KUInt BYTE_1 = 1; const KUInt BYTE_2 = 2; const KUInt BYTE_3 = 3; - const KUInt BYTE_1_SHIFT = 8; const KUInt BYTE_2_SHIFT = 16; const KUInt BYTE_3_SHIFT = 24; - return ( - bytes[BYTE_0] - | (bytes[BYTE_1] << BYTE_1_SHIFT) - | (bytes[BYTE_2] << BYTE_2_SHIFT) - | (bytes[BYTE_3] << BYTE_3_SHIFT) - ); + return ( bytes[BYTE_0] | (bytes[BYTE_1] << BYTE_1_SHIFT) | (bytes[BYTE_2] << BYTE_2_SHIFT) | + (bytes[BYTE_3] << BYTE_3_SHIFT)); } es2panda_ContextState intToState(KInt state); -- Gitee From 389242857eac9f6c73134eb1b6c47f90cbaac19c Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Sat, 13 Sep 2025 14:08:15 +0300 Subject: [PATCH 14/14] codecheck12 Signed-off-by: Korobeinikov Evgeny Change-Id: I58bd4290a0835dcf616f2d364f75d91810ac1175 --- ets1.2/libarkts/native/src/bridges.cc | 5 ++--- ets1.2/libarkts/native/src/common.h | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ets1.2/libarkts/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index b196fa502..d3acb8c40 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -508,9 +508,8 @@ KNativePointer impl_AnnotationUsageIrPropertiesPtrConst(KNativePointer context, } KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); -KInt impl_GenerateTsDeclarationsFromContext( - KNativePointer contextPtr, KStringPtr &outputDeclEts, KStringPtr &outputEts, - KBoolean exportAll, KBoolean isolated, KStringPtr &recordFile, KBoolean genAnnotations) +KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr& outputDeclEts, KStringPtr& outputEts, + KBoolean exportAll, KBoolean isolated, KStringPtr& recordFile, KBoolean genAnnotations) { auto context = reinterpret_cast(contextPtr); return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), diff --git a/ets1.2/libarkts/native/src/common.h b/ets1.2/libarkts/native/src/common.h index 086246dcb..8f0d413d5 100644 --- a/ets1.2/libarkts/native/src/common.h +++ b/ets1.2/libarkts/native/src/common.h @@ -66,8 +66,8 @@ inline KUInt unpackUInt(const KByte* bytes) const KUInt BYTE_1_SHIFT = 8; const KUInt BYTE_2_SHIFT = 16; const KUInt BYTE_3_SHIFT = 24; - return ( bytes[BYTE_0] | (bytes[BYTE_1] << BYTE_1_SHIFT) | (bytes[BYTE_2] << BYTE_2_SHIFT) | - (bytes[BYTE_3] << BYTE_3_SHIFT)); + return (bytes[BYTE_0] | (bytes[BYTE_1] << BYTE_1_SHIFT) | (bytes[BYTE_2] << BYTE_2_SHIFT) | + (bytes[BYTE_3] << BYTE_3_SHIFT)); } es2panda_ContextState intToState(KInt state); -- Gitee