From 5eada97c7f81d2704356431d109d6e54936b9aea Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Fri, 12 Sep 2025 13:36:52 +0300 Subject: [PATCH 01/15] Upd: "/ets1.2" to master of koala_projects (m1-rc2-1727-gefd9ea044) Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/common/package.json | 3 +- ets1.2/compat/src/arkts/observable.ts | 28 +- ets1.2/compat/src/typescript/strings.ts | 3 +- ets1.2/gn/command/npm_util.py | 11 +- ets1.2/gn/script/npm.py | 11 +- ets1.2/interop/src/arkts/events.ts | 25 +- 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/ani/convertors-ani.h | 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 | 79 +- 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 | 41 +- ets1.2/interop/src/cpp/vmloader.cc | 3 +- ets1.2/interop/src/interop/events.ts | 25 +- ets1.2/koala_integration.gni | 25 - ets1.2/libarkts/.prettierrc | 14 +- ets1.2/libarkts/gn/command/copy.py | 6 +- ets1.2/libarkts/native/src/bridges.cc | 75 +- ets1.2/libarkts/native/src/common.cc | 56 +- ets1.2/libarkts/native/src/common.h | 3 +- ets1.2/libarkts/package.json | 20 +- 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/libarkts/src-host/es2panda.ts | 2 +- .../expressions/call-expression.test.ts | 1 + .../test/arkts-api/functions/create.test.ts | 1 + .../arkts-api/general/annotations.test.ts | 2 +- .../test/arkts-api/general/basic.test.ts | 43 + .../test/arkts-api/general/jsdoc.test.ts | 3 +- .../test/arkts-api/general/recheck.test.ts | 1 + .../arkts-api/import-export/import.test.ts | 3 +- .../lambda/unchanged/dump-src/main.ets | 4 +- .../test/arkts-api/recheck/recheck.test.ts | 1 + .../static/typed-property/dump-src/main.ets | 2 +- ets1.2/libarkts/test/test-util.ts | 7 +- .../test/ts-api/general/abc-gen.test.ts | 11 +- 44 files changed, 1028 insertions(+), 1186 deletions(-) delete mode 100644 ets1.2/koala_integration.gni 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%) diff --git a/ets1.2/common/package.json b/ets1.2/common/package.json index 1f2687d5c..103b6d79d 100644 --- a/ets1.2/common/package.json +++ b/ets1.2/common/package.json @@ -34,7 +34,6 @@ }, "devDependencies": { "@ohos/hypium": "1.0.6", - "@types/mocha": "^9.1.0", "@typescript-eslint/eslint-plugin": "^5.20.0", "@typescript-eslint/parser": "^5.20.0", "eslint": "^8.13.0", @@ -42,4 +41,4 @@ "mocha": "^9.2.2", "source-map-support": "^0.5.21" } -} \ No newline at end of file +} diff --git a/ets1.2/compat/src/arkts/observable.ts b/ets1.2/compat/src/arkts/observable.ts index 88f6be944..f28ece65d 100644 --- a/ets1.2/compat/src/arkts/observable.ts +++ b/ets1.2/compat/src/arkts/observable.ts @@ -444,7 +444,7 @@ class ObservableArray extends Array { // === methods with uncompatible implementation === - override filter(predicate: (value: T, index: number, array: Array) => boolean): Array { + override filter(predicate: (value: T, index: int, array: Array) => boolean): Array { this.handler?.onAccess() return super.filter(predicate) } @@ -454,7 +454,7 @@ class ObservableArray extends Array { return super.flat(depth) } - override flatMap(fn: (v: T, k: number, arr: Array) => U): Array { + override flatMap(fn: (v: T, k: int, arr: Array) => U): Array { this.handler?.onAccess() return super.flatMap(fn) } @@ -466,57 +466,57 @@ class ObservableArray extends Array { return super.concat(...items) } - override find(predicate: (value: T, index: number, array: Array) => boolean): T | undefined { + override find(predicate: (value: T, index: int, array: Array) => boolean): T | undefined { this.handler?.onAccess() return super.find(predicate) } - override findIndex(predicate: (value: T, index: number, array: Array) => boolean): number { + override findIndex(predicate: (value: T, index: int, array: Array) => boolean): number { this.handler?.onAccess() return super.findIndex(predicate) } - override findLast(predicate: (elem: T, index: number, array: Array) => boolean): T | undefined { + override findLast(predicate: (elem: T, index: int, array: Array) => boolean): T | undefined { this.handler?.onAccess() return super.findLast(predicate) } - override every(predicate: (value: T, index: number, array: Array) => boolean): boolean { + override every(predicate: (value: T, index: int, array: Array) => boolean): boolean { this.handler?.onAccess() return super.every(predicate) } - override some(predicate: (value: T, index: number, array: Array) => boolean): boolean { + override some(predicate: (value: T, index: int, array: Array) => boolean): boolean { this.handler?.onAccess() return super.some(predicate) } - override findLastIndex(predicate: (element: T, index: number, array: Array) => boolean): number { + override findLastIndex(predicate: (element: T, index: int, array: Array) => boolean): number { this.handler?.onAccess() return super.findLastIndex(predicate) } - override reduce(callbackfn: (previousValue: T, currentValue: T, index: number, array: Array) => T): T { + override reduce(callbackfn: (previousValue: T, currentValue: T, index: int, array: Array) => T): T { this.handler?.onAccess() return super.reduce(callbackfn) } - override reduce(callbackfn: (previousValue: U, currentValue: T, index: number, array: Array) => U, initialValue: U): U { + override reduce(callbackfn: (previousValue: U, currentValue: T, index: int, array: Array) => U, initialValue: U): U { this.handler?.onAccess() return super.reduce(callbackfn, initialValue) } - override reduceRight(callbackfn: (previousValue: T, currentValue: T, index: number, array: Array) => T): T { + override reduceRight(callbackfn: (previousValue: T, currentValue: T, index: int, array: Array) => T): T { this.handler?.onAccess() return super.reduceRight(callbackfn) } - override reduceRight(callbackfn: (previousValue: U, currentValue: T, index: number, array: Array) => U, initialValue: U): U { + override reduceRight(callbackfn: (previousValue: U, currentValue: T, index: int, array: Array) => U, initialValue: U): U { this.handler?.onAccess() return super.reduceRight(callbackfn, initialValue) } - override forEach(callbackfn: (value: T, index: number, array: Array) => void): void { + override forEach(callbackfn: (value: T, index: int, array: Array) => void): void { this.handler?.onAccess() super.forEach(callbackfn) } @@ -586,7 +586,7 @@ class ObservableArray extends Array { return super.entries() } - override map(callbackfn: (value: T, index: number, array: Array) => U): Array { + override map(callbackfn: (value: T, index: int, array: Array) => U): Array { this.handler?.onAccess() return super.map(callbackfn) } diff --git a/ets1.2/compat/src/typescript/strings.ts b/ets1.2/compat/src/typescript/strings.ts index 264154f99..e854d0bc1 100644 --- a/ets1.2/compat/src/typescript/strings.ts +++ b/ets1.2/compat/src/typescript/strings.ts @@ -155,8 +155,9 @@ export class CustomTextEncoder { export class CustomTextDecoder { static cpArrayMaxSize = 128; constructor( - decoder: SystemTextDecoder | undefined = typeof TextDecoder != 'undefined' ? new TextDecoder() : undefined + decoder: SystemTextDecoder | undefined = undefined ) { + if (!decoder && typeof TextDecoder != 'undefined') decoder = new TextDecoder() this.decoder = decoder; } diff --git a/ets1.2/gn/command/npm_util.py b/ets1.2/gn/command/npm_util.py index c6b6809cf..2dec5865c 100755 --- a/ets1.2/gn/command/npm_util.py +++ b/ets1.2/gn/command/npm_util.py @@ -53,18 +53,17 @@ if args.stdlib_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) + result = subprocess.run(["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) + 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) print(open(koala_log, "r").read()) raise Exception("npm failed") f.close() diff --git a/ets1.2/gn/script/npm.py b/ets1.2/gn/script/npm.py index 09499e008..7bcc018a3 100755 --- a/ets1.2/gn/script/npm.py +++ b/ets1.2/gn/script/npm.py @@ -54,18 +54,19 @@ 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) + result = subprocess.run(["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) + 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) print(open(koala_log, "r").read()) raise Exception("npm failed") f.close() diff --git a/ets1.2/interop/src/arkts/events.ts b/ets1.2/interop/src/arkts/events.ts index c6b3eddc3..cc06b90c5 100644 --- a/ets1.2/interop/src/arkts/events.ts +++ b/ets1.2/interop/src/arkts/events.ts @@ -1,18 +1,3 @@ -/* - * Copyright (c) 2022-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 - * - * 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 { int32 } from '@koalaui/common'; import { DeserializerBase } from './DeserializerBase'; import { InteropNativeModule } from './InteropNativeModule'; @@ -76,17 +61,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/ani/convertors-ani.h b/ets1.2/interop/src/cpp/ani/convertors-ani.h index 79939d006..cc46d7998 100644 --- a/ets1.2/interop/src/cpp/ani/convertors-ani.h +++ b/ets1.2/interop/src/cpp/ani/convertors-ani.h @@ -479,7 +479,7 @@ public: #define KOALA_ANI_INTEROP_MODULE_CLASSPATH(module, classpath) \ static void __init_classpath_##module() \ { \ - AniExports::getInstance()->setClasspath(KOALA_QUOTE(module), "L" classpath ";"); \ + AniExports::getInstance()->setClasspath(KOALA_QUOTE(module), classpath); \ } \ namespace { \ struct __Init_classpath_##module { \ @@ -499,7 +499,7 @@ public: #define KOALA_ANI_INTEROP_MODULE_CLASSPATH(module, classpath) \ __attribute__((constructor)) static void __init_ani_classpath_##module() \ { \ - AniExports::getInstance()->setClasspath(KOALA_QUOTE(module), "L" classpath ";"); \ + AniExports::getInstance()->setClasspath(KOALA_QUOTE(module), classpath); \ } #endif 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..4b86ca1eb 100644 --- a/ets1.2/interop/src/cpp/napi/convertors-napi.h +++ b/ets1.2/interop/src/cpp/napi/convertors-napi.h @@ -18,6 +18,7 @@ #ifdef KOALA_NAPI +#include #include #include #include @@ -204,18 +205,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; @@ -248,6 +245,49 @@ struct InteropTypeConverter { static inline void release(napi_env env, InteropType value, const KInteropReturnBuffer& converted) = delete; }; +template +ElemType* getTypedElements(napi_env env, napi_value value, size_t& bytes); + +template<> +struct InteropTypeConverter { + using InteropType = napi_value; + using SelfType = InteropTypeConverter; + static constexpr auto LengthByteSize = sizeof(KUInt); + static char* strndup(const void* str, size_t n) + { + char* mem = static_cast(malloc(n + 1)); + interop_memcpy(mem, n + 1, str, n); + mem[n] = 0; + return mem; + } + static size_t decodeLength(const uint8_t* data) + { + return (data[3] << 24) | (data[2] << 16) | (data[1] << 8) | data[0]; + } + static KStringArray convertFrom(napi_env env, InteropType value) + { + size_t bytes = 0; + auto const encoded = getTypedElements(env, value, bytes); + if (!bytes) + return { { nullptr, nullptr }, 0 }; + + size_t const num = decodeLength(encoded); + KStringArray::Holder result(static_cast(malloc(sizeof(char*) * (num + 1))), &free); + + size_t count = 0; + auto const* ptr = encoded + LengthByteSize; + auto const* const end = encoded + bytes; + while (ptr < end) { + auto length = decodeLength(ptr); + result[count++] = SelfType::strndup(ptr + LengthByteSize, length); + ptr += LengthByteSize + length; + } + return { std::move(result), num }; + } + static InteropType convertTo(napi_env env, KStringArray value) = delete; + static void release(napi_env env, InteropType value, const KInteropReturnBuffer& converted) = delete; +}; + #define KOALA_INTEROP_THROW(vmContext, object, ...) \ do { \ napi_env env = (napi_env)vmContext; \ @@ -393,7 +433,7 @@ napi_valuetype getValueTypeChecked(napi_env env, napi_value value); bool isTypedArray(napi_env env, napi_value value); template -inline ElemType* getTypedElements(napi_env env, napi_value value) +inline ElemType* getTypedElements(napi_env env, napi_value value, size_t& bytesLength) { napi_valuetype valueType = getValueTypeChecked(env, value); if (valueType == napi_null) { @@ -405,10 +445,9 @@ inline ElemType* getTypedElements(napi_env env, napi_value value) } napi_value arrayBuffer; void* data = nullptr; - size_t byteLength; size_t byteOffset; napi_typedarray_type type; - napi_status status = napi_get_typedarray_info(env, value, &type, &byteLength, &data, &arrayBuffer, &byteOffset); + napi_status status = napi_get_typedarray_info(env, value, &type, &bytesLength, &data, &arrayBuffer, &byteOffset); KOALA_NAPI_THROW_IF_FAILED(env, status, nullptr); if (type != getNapiType()) { printf("Array type mismatch. Expected %d got %d\n", getNapiType(), type); @@ -418,6 +457,13 @@ inline ElemType* getTypedElements(napi_env env, napi_value value) return reinterpret_cast(data); } +template +inline ElemType* getTypedElements(napi_env env, napi_value value) +{ + size_t dummy; + return getTypedElements(env, value, dummy); +} + template inline ElemType* getTypedElements(const CallbackInfo& info, int index) { @@ -575,6 +621,13 @@ inline KInteropBuffer getArgument(const CallbackInfo& info, int return getArgument((napi_env)info.Env(), (napi_value)info[index]); } +template<> +inline KStringArray getArgument(const CallbackInfo& info, int index) +{ + NAPI_ASSERT_INDEX(info, index, {}); + return getArgument((napi_env)info.Env(), (napi_value)info[index]); +} + template<> inline KFloat getArgument(const CallbackInfo& info, int index) { @@ -764,8 +817,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..d9856c2a8 100644 --- a/ets1.2/interop/src/cpp/types/koala-types.h +++ b/ets1.2/interop/src/cpp/types/koala-types.h @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -112,12 +113,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 +131,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"); } @@ -161,6 +160,36 @@ private: bool _owned; }; +struct KStringArrayImpl { + // Null terminated, [char*, char*, ..., nullptr] + using Holder = std::unique_ptr; + + KStringArrayImpl() : KStringArrayImpl({ nullptr, nullptr }, 0) {} + KStringArrayImpl(Holder strs, size_t num) : _holder(std::move(strs)), _num(num) {} + + ~KStringArrayImpl() + { + for (size_t k = 0; k < _num; k++) { + free(_holder[k]); + } + } + + const char* const* get() const + { + return _holder.get(); + } + + char** release() + { + _num = 0; + return _holder.release(); + } + +private: + Holder _holder; + size_t _num; +}; + struct KInteropNumber { int8_t tag; union { @@ -238,7 +267,7 @@ typedef InteropNativePointer KNativePointer; typedef KStringPtrImpl KStringPtr; typedef KFloat* KFloatArray; -typedef const uint8_t* KStringArray; +typedef KStringArrayImpl KStringArray; typedef KNativePointer* KNativePointerArray; struct KSerializerBufferOpaque { 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..05b11d771 100644 --- a/ets1.2/interop/src/interop/events.ts +++ b/ets1.2/interop/src/interop/events.ts @@ -1,18 +1,3 @@ -/* - * Copyright (c) 2022-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 - * - * 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 { int32 } from '@koalaui/common'; import { DeserializerBase } from './DeserializerBase'; import { InteropNativeModule } from './InteropNativeModule'; @@ -75,17 +60,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/koala_integration.gni b/ets1.2/koala_integration.gni deleted file mode 100644 index 5295f7960..000000000 --- a/ets1.2/koala_integration.gni +++ /dev/null @@ -1,25 +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. - -koala_mr = { - root_path = "//developtools/ace_ets2bundle/ets1.2" - scripts_path = "$root_path/gn/script" - imports_prefix = "$root_path/gn/import" - libarkts_path = "$root_path/libarkts" - 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") 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/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/native/src/bridges.cc b/ets1.2/libarkts/native/src/bridges.cc index d19ed1a88..77075af1c 100644 --- a/ets1.2/libarkts/native/src/bridges.cc +++ b/ets1.2/libarkts/native/src/bridges.cc @@ -220,21 +220,10 @@ KNativePointer impl_CreateCacheContextFromFile( KOALA_INTEROP_4(CreateCacheContextFromFile, KNativePointer, KNativePointer, KStringPtr, KNativePointer, KBoolean) KNativePointer impl_CreateGlobalContext( - KNativePointer configPtr, KStringArray externalFileListPtr, KUInt fileNum, KBoolean LspUsage) + KNativePointer configPtr, KStringArray& externalFileListPtr, KUInt fileNum, KBoolean LspUsage) { auto config = reinterpret_cast(configPtr); - const int headerLen = 4; - const char** files = StageArena::allocArray(fileNum); - uint8_t* filesPtr = (uint8_t*)externalFileListPtr; - std::size_t position = headerLen; - std::size_t strLen; - for (std::size_t i = 0; i < static_cast(fileNum); ++i) { - strLen = unpackUInt(filesPtr + position); - position += headerLen; - files[i] = StageArena::strdup(std::string(reinterpret_cast(filesPtr + position), strLen).c_str()); - position += strLen; - } - return GetImpl()->CreateGlobalContext(config, files, fileNum, LspUsage); + return GetImpl()->CreateGlobalContext(config, getStringArray(externalFileListPtr), fileNum, LspUsage); } KOALA_INTEROP_4(CreateGlobalContext, KNativePointer, KNativePointer, KStringArray, KUInt, KBoolean) @@ -427,66 +416,37 @@ KNativePointer impl_CreateDiagnosticKind(KNativePointer context, KStringPtr& mes KOALA_INTEROP_3(CreateDiagnosticKind, KNativePointer, KNativePointer, KStringPtr, KInt) KNativePointer impl_CreateDiagnosticInfo( - KNativePointer context, KNativePointer kind, KStringArray argsPtr, KInt argc, KNativePointer pos) + 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 std::size_t headerLen = 4; - const char** _args = new const char*[argc]; - std::size_t position = headerLen; - std::size_t strLen; - for (std::size_t i = 0; i < static_cast(argc); ++i) { - strLen = unpackUInt(argsPtr + position); - position += headerLen; - _args[i] = strdup(std::string(reinterpret_cast(argsPtr + position), strLen).c_str()); - position += strLen; - } - return GetImpl()->CreateDiagnosticInfo(_context, _kind, _args, argc, _pos); + return GetImpl()->CreateDiagnosticInfo(_context, _kind, getStringArray(argsPtr), argc, _pos); } KOALA_INTEROP_5( CreateDiagnosticInfo, KNativePointer, KNativePointer, KNativePointer, KStringArray, KInt, KNativePointer) -KNativePointer impl_CreateSuggestionInfo(KNativePointer context, KNativePointer kind, KStringArray argsPtr, KInt argc, +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 _title = getStringCopy(title); const auto _range = reinterpret_cast(range); - const std::size_t headerLen = 4; - const char** _args = new const char*[argc]; - std::size_t position = headerLen; - std::size_t strLen; - for (std::size_t i = 0; i < static_cast(argc); ++i) { - strLen = unpackUInt(argsPtr + position); - position += headerLen; - _args[i] = strdup(std::string(reinterpret_cast(argsPtr + position), strLen).c_str()); - position += strLen; - } const auto _substitutionCode = getStringCopy(substitutionCode); - return GetImpl()->CreateSuggestionInfo(_context, _kind, _args, argc, _substitutionCode, _title, _range); + return GetImpl()->CreateSuggestionInfo( + _context, _kind, getStringArray(argsPtr), argc, _substitutionCode, _title, _range); } 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) + 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); - const std::size_t headerLen = 4; - const char** argv = new const char*[argc]; - std::size_t position = headerLen; - std::size_t strLen; - for (std::size_t i = 0; i < static_cast(argc); ++i) { - strLen = unpackUInt(argvPtr + position); - position += headerLen; - argv[i] = strdup(std::string(reinterpret_cast(argvPtr + position), strLen).c_str()); - position += strLen; - } - GetImpl()->LogDiagnostic(_context_, _kind_, argv, argc, _pos_); + GetImpl()->LogDiagnostic(_context_, _kind_, getStringArray(argvPtr), argc, _pos_); } KOALA_INTEROP_V5(LogDiagnostic, KNativePointer, KNativePointer, KStringArray, KInt, KNativePointer) @@ -510,22 +470,11 @@ KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPt KOALA_INTEROP_7(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean, KBoolean, KStringPtr, KBoolean) -// Improve: simplify KNativePointer impl_CreateContextGenerateAbcForExternalSourceFiles( - KNativePointer configPtr, KInt fileNamesCount, KStringArray fileNames) + KNativePointer configPtr, KInt fileNamesCount, KStringArray& fileNames) { auto config = reinterpret_cast(configPtr); - const std::size_t headerLen = 4; - 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()); - position += strLen; - } - return GetImpl()->CreateContextGenerateAbcForExternalSourceFiles(config, fileNamesCount, argv); + return GetImpl()->CreateContextGenerateAbcForExternalSourceFiles(config, fileNamesCount, getStringArray(fileNames)); } KOALA_INTEROP_3(CreateContextGenerateAbcForExternalSourceFiles, KNativePointer, KNativePointer, KInt, KStringArray) @@ -552,4 +501,4 @@ KNativePointer impl_CreateTypeNodeFromTsType(KNativePointer context, KNativePoin auto _typeAnnotation = GetImpl()->CreateOpaqueTypeNode(_context, _nodeTsType); return _typeAnnotation; } -KOALA_INTEROP_2(CreateTypeNodeFromTsType, KNativePointer, KNativePointer, KNativePointer) \ No newline at end of file +KOALA_INTEROP_2(CreateTypeNodeFromTsType, KNativePointer, KNativePointer, KNativePointer) diff --git a/ets1.2/libarkts/native/src/common.cc b/ets1.2/libarkts/native/src/common.cc index 116fb4612..87fa3b0b0 100644 --- a/ets1.2/libarkts/native/src/common.cc +++ b/ets1.2/libarkts/native/src/common.cc @@ -100,8 +100,8 @@ void* StageArena::alloc(size_t size) #endif 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_ALT = LIB_PREFIX "es2panda-public" LIB_SUFFIX; const char* LIB_ES2PANDA_PUBLIC = LIB_PREFIX "es2panda_public" LIB_SUFFIX; const char* IS_UI_FLAG = "IS_UI_FLAG"; const char* NOT_UI_FLAG = "NOT_UI_FLAG"; @@ -136,15 +136,14 @@ void impl_SetUpSoPath(KStringPtr& soPath) } KOALA_INTEROP_V1(SetUpSoPath, KStringPtr); -// Improve: simplify this -void* FindLibrary() +void* TryLibrary(const char* name) { 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, name}; res = loadLibrary(joinPath(pathArray)); if (res) { return res; @@ -154,7 +153,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 +161,14 @@ void* FindLibrary() } // find by set LD_LIBRARY_PATH - pathArray = { LIB_ES2PANDA_PUBLIC }; + pathArray = {name}; 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,6 +177,23 @@ void* FindLibrary() return nullptr; } +// TODO: @panda/sdk will be changed to match ohos-sdk +void* FindLibrary() { + void *res = nullptr; + + res = TryLibrary(LIB_ES2PANDA_PUBLIC); + if (res) { + return res; + } + + res = TryLibrary(LIB_ES2PANDA_PUBLIC_ALT); + if (res) { + return res; + } + + return nullptr; +} + es2panda_Impl* GetImplSlow() { if (es2pandaImplementation) { @@ -202,25 +218,19 @@ string getString(KStringPtr ptr) return ptr.data(); } +const char** getStringArray(KStringArray& ptr) +{ + return const_cast(ptr.get()); // release()? +} + 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); - std::size_t position = headerLen; - std::size_t strLen; - for (std::size_t i = 0; i < static_cast(argc); ++i) { - strLen = unpackUInt(argvPtr + position); - position += headerLen; - argv[i] = StageArena::strdup(std::string(reinterpret_cast(argvPtr + position), strLen).c_str()); - position += strLen; - } - return GetImpl()->CreateConfig(argc, argv); + return GetImpl()->CreateConfig(argc, getStringArray(argvPtr)); } KOALA_INTEROP_2(CreateConfig, KNativePointer, KInt, KStringArray) @@ -432,15 +442,15 @@ struct Pattern { return false; } - bool matchWildcard(const std::string& pattern, const char* valueArg) + bool matchWildcard(const std::string& pattern, const char* value) { if (pattern.find('*') == std::string::npos) { - return pattern == valueArg; + return pattern == value; } regex_t regex; regmatch_t match[1]; regcomp(®ex, pattern.c_str(), REG_NEWLINE); - return regexec(®ex, valueArg, 1, match, 0) != REG_NOMATCH; + return regexec(®ex, value, 1, match, 0) != REG_NOMATCH; } }; diff --git a/ets1.2/libarkts/native/src/common.h b/ets1.2/libarkts/native/src/common.h index f2eeeb0e7..770d2a2ad 100644 --- a/ets1.2/libarkts/native/src/common.h +++ b/ets1.2/libarkts/native/src/common.h @@ -55,6 +55,7 @@ inline es2panda_Impl* GetImpl() } string getString(KStringPtr ptr); +const char** getStringArray(KStringArray& ptr); char* getStringCopy(KStringPtr& ptr); @@ -129,4 +130,4 @@ public: void cleanup(); }; -#endif // COMMON_H \ No newline at end of file +#endif // COMMON_H diff --git a/ets1.2/libarkts/package.json b/ets1.2/libarkts/package.json index f391b800c..42578447a 100644 --- a/ets1.2/libarkts/package.json +++ b/ets1.2/libarkts/package.json @@ -27,17 +27,9 @@ "panda_sdk_version": "next" }, "dependencies": { - "@koalaui/ets-tsc": "4.9.5-r6", - "@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", - "node-api-headers": "0.0.5", "commander": "10.0.1" }, "devDependencies": { @@ -46,7 +38,15 @@ "@rollup/plugin-node-resolve": "^15.3.0", "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.6", - "rimraf": "^6.0.1" + "rimraf": "^6.0.1", + "@koalaui/fast-arktsc": "1.7.10+devel", + "@idlizer/arktscgen": "2.1.10-arktscgen-4", + "mocha": "^9.2.2", + "@koalaui/harness": "1.7.10+devel", + "@koalaui/ets-tsc": "4.9.5-r6", + "@koalaui/build-common": "1.7.10+devel", + "node-addon-api": "8.0.0", + "node-api-headers": "0.0.5" }, "scripts": { "clean": "rimraf generated build native/build* ./.rollup.cache tsconfig.tsbuildinfo lib", @@ -59,7 +59,7 @@ "compile:native": "npm run compile:koala:interop && npm run compile:meson && npm run copy:.node", "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:release": "npm run regenerate && 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", 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/libarkts/src-host/es2panda.ts b/ets1.2/libarkts/src-host/es2panda.ts index c7440f0d2..600e8aa92 100644 --- a/ets1.2/libarkts/src-host/es2panda.ts +++ b/ets1.2/libarkts/src-host/es2panda.ts @@ -101,7 +101,7 @@ function insertPlugin(pluginEntry: PluginEntry, state: Es2pandaContextState, dum const hooks = new DumpingHooks(state, pluginName, dumpAst); const pluginContext = new PluginContextImpl(); - if (false) { + if (true) { pluginContext.setProjectConfig({ bundleName: 'bundle', moduleName: 'module', diff --git a/ets1.2/libarkts/test/arkts-api/expressions/call-expression.test.ts b/ets1.2/libarkts/test/arkts-api/expressions/call-expression.test.ts index 3132fc8de..cb407b283 100644 --- a/ets1.2/libarkts/test/arkts-api/expressions/call-expression.test.ts +++ b/ets1.2/libarkts/test/arkts-api/expressions/call-expression.test.ts @@ -15,6 +15,7 @@ import * as util from "../../test-util" import * as arkts from "../../../src/arkts-api" +import { suite, test } from "@koalaui/harness" suite(util.basename(__filename), () => { test("sample-1", function() { diff --git a/ets1.2/libarkts/test/arkts-api/functions/create.test.ts b/ets1.2/libarkts/test/arkts-api/functions/create.test.ts index d222e07f1..c57973324 100644 --- a/ets1.2/libarkts/test/arkts-api/functions/create.test.ts +++ b/ets1.2/libarkts/test/arkts-api/functions/create.test.ts @@ -15,6 +15,7 @@ import * as util from "../../test-util" import * as arkts from "../../../src/arkts-api" +import { suite, test } from "@koalaui/harness" suite(util.basename(__filename), () => { test("sample-1", function() { diff --git a/ets1.2/libarkts/test/arkts-api/general/annotations.test.ts b/ets1.2/libarkts/test/arkts-api/general/annotations.test.ts index f6564beff..f98d5fd13 100644 --- a/ets1.2/libarkts/test/arkts-api/general/annotations.test.ts +++ b/ets1.2/libarkts/test/arkts-api/general/annotations.test.ts @@ -15,7 +15,7 @@ import * as util from "../../test-util" import * as arkts from "../../../src/arkts-api" -import { assert } from "@koalaui/harness" +import { suite, test, assert } from "@koalaui/harness" suite(util.basename(__filename), () => { test("annotated-function-1", function() { diff --git a/ets1.2/libarkts/test/arkts-api/general/basic.test.ts b/ets1.2/libarkts/test/arkts-api/general/basic.test.ts index e76d7c4bb..2c4294255 100644 --- a/ets1.2/libarkts/test/arkts-api/general/basic.test.ts +++ b/ets1.2/libarkts/test/arkts-api/general/basic.test.ts @@ -15,6 +15,9 @@ import * as util from "../../test-util" import * as arkts from "../../../src/arkts-api" +import { suite, test, assert } from "@koalaui/harness" + +const PANDA_SDK_PATH = process.env.PANDA_SDK_PATH ?? '../../incremental/tools/panda/node_modules/@panda/sdk' suite(util.basename(__filename), () => { test("sample-1", function() { @@ -46,4 +49,44 @@ suite(util.basename(__filename), () => { arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED ) }) + test("filter", function() { + arkts.arktsGlobal.compilerContext = arkts.Context.createFromString( +` +@interface memo {} + +struct Noo {} + +class Foo { + @memo + foo1() {} + + bar: int = 42 + foo2() {} + + @memo + foo3() {} +} + +interface IFoo { + @memo + ifoo1() {} + + ifoo2() {} + + @memo + ifoo3() {} +} + +struct Moo {} +` + ) + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) + const program = arkts.arktsGlobal.compilerContext!.program + const memos = arkts.filterNodes(program.ast, "type=method;annotation=memo") + assert.equal(memos.length, 4) + assert.equal((memos[0] as arkts.MethodDefinition).id!.name, "foo1") + const structs = arkts.filterNodes(program.ast, "type=struct") + assert.equal(structs.length, 2) + assert.equal((structs[0] as arkts.ETSStructDeclaration).definition.ident!.name, "Noo") + }) }) diff --git a/ets1.2/libarkts/test/arkts-api/general/jsdoc.test.ts b/ets1.2/libarkts/test/arkts-api/general/jsdoc.test.ts index ee4890ba3..a5af6f0b9 100644 --- a/ets1.2/libarkts/test/arkts-api/general/jsdoc.test.ts +++ b/ets1.2/libarkts/test/arkts-api/general/jsdoc.test.ts @@ -15,7 +15,8 @@ import * as util from "../../test-util" import * as arkts from "../../../src/arkts-api" -import { assert } from "@koalaui/harness" +import { suite, test, assert } from "@koalaui/harness" + import { isMethodDefinition, isBlockStatement, diff --git a/ets1.2/libarkts/test/arkts-api/general/recheck.test.ts b/ets1.2/libarkts/test/arkts-api/general/recheck.test.ts index f233a7084..e169467bb 100644 --- a/ets1.2/libarkts/test/arkts-api/general/recheck.test.ts +++ b/ets1.2/libarkts/test/arkts-api/general/recheck.test.ts @@ -15,6 +15,7 @@ import * as util from "../../test-util" import * as arkts from "../../../src/arkts-api" +import { suite, test } from "@koalaui/harness" const PANDA_SDK_PATH = process.env.PANDA_SDK_PATH ?? '../../incremental/tools/panda/node_modules/@panda/sdk' diff --git a/ets1.2/libarkts/test/arkts-api/import-export/import.test.ts b/ets1.2/libarkts/test/arkts-api/import-export/import.test.ts index a4727774f..44d6d8245 100644 --- a/ets1.2/libarkts/test/arkts-api/import-export/import.test.ts +++ b/ets1.2/libarkts/test/arkts-api/import-export/import.test.ts @@ -15,7 +15,8 @@ import * as util from "../../test-util" import * as arkts from "../../../src/arkts-api" -import { global } from "../../../src/arkts-api/static/global" +import { suite, test } from "@koalaui/harness" + suite(util.basename(__filename), () => { diff --git a/ets1.2/libarkts/test/arkts-api/recheck/lambda/unchanged/dump-src/main.ets b/ets1.2/libarkts/test/arkts-api/recheck/lambda/unchanged/dump-src/main.ets index 39e8569f3..419b97904 100644 --- a/ets1.2/libarkts/test/arkts-api/recheck/lambda/unchanged/dump-src/main.ets +++ b/ets1.2/libarkts/test/arkts-api/recheck/lambda/unchanged/dump-src/main.ets @@ -8,8 +8,8 @@ function foo(): void { } function hasTrailing(first?: string, trailing?: (()=> void)): void { - ({let gensym%%_865 = trailing; - (((gensym%%_865) == (null)) ? undefined : gensym%%_865())}); + ({let gensym%%_793 = trailing; + (((gensym%%_793) == (null)) ? undefined : gensym%%_793())}); } function bar(zzz: string): void { diff --git a/ets1.2/libarkts/test/arkts-api/recheck/recheck.test.ts b/ets1.2/libarkts/test/arkts-api/recheck/recheck.test.ts index 2b32f9208..2e8b3b10d 100644 --- a/ets1.2/libarkts/test/arkts-api/recheck/recheck.test.ts +++ b/ets1.2/libarkts/test/arkts-api/recheck/recheck.test.ts @@ -31,6 +31,7 @@ import { addUseImportClassSameFile } from "./exports/basic" import { addUseImportClassSameFileAndExportClass } from "./exports/add-export" import { addUseImportClassSameFileAndCreateClass } from "./exports/create-class" import { addUseImportClassSameFileAfterRewritingStructToClass, rewriteStructToClass } from "./exports/struct-to-class" +import { suite, test } from "@koalaui/harness" const DIR = './test/arkts-api/recheck' const PANDA_SDK_PATH = process.env.PANDA_SDK_PATH ?? '../../incremental/tools/panda/node_modules/@panda/sdk' diff --git a/ets1.2/libarkts/test/arkts-api/recheck/static/typed-property/dump-src/main.ets b/ets1.2/libarkts/test/arkts-api/recheck/static/typed-property/dump-src/main.ets index d48f5918c..5f06f4d6a 100644 --- a/ets1.2/libarkts/test/arkts-api/recheck/static/typed-property/dump-src/main.ets +++ b/ets1.2/libarkts/test/arkts-api/recheck/static/typed-property/dump-src/main.ets @@ -15,7 +15,7 @@ class C implements I { public get prop(): boolean { return this._$property$_prop; } - set prop(_$property$_prop: boolean) { + public set prop(_$property$_prop: boolean) { this._$property$_prop = _$property$_prop; return; } diff --git a/ets1.2/libarkts/test/test-util.ts b/ets1.2/libarkts/test/test-util.ts index 73b4e6e80..5d46f652e 100644 --- a/ets1.2/libarkts/test/test-util.ts +++ b/ets1.2/libarkts/test/test-util.ts @@ -21,7 +21,7 @@ import { assert } from "@koalaui/harness" import { exec, execSync } from "child_process" export { Es2pandaNativeModule } from "../src/Es2pandaNativeModule" -export { assert } from "@koalaui/harness" +export { test, suite, assert } from "@koalaui/harness" export function alignText(text: string): string { const lines = text.replace(/\t/gy, ' ').split('\n') @@ -116,10 +116,7 @@ export function runAbc(path: string = './generated/main.abc', modules?: readonly ) } -export function assertEqualsBinaryOutput(output: string, ctx: Mocha.Context): void { - if (process.env.TEST_BIN === undefined) { - ctx.skip() - } +export function assertEqualsBinaryOutput(output: string): void { try { contextToAbc() exec( diff --git a/ets1.2/libarkts/test/ts-api/general/abc-gen.test.ts b/ets1.2/libarkts/test/ts-api/general/abc-gen.test.ts index 0a8411de1..413e3f454 100644 --- a/ets1.2/libarkts/test/ts-api/general/abc-gen.test.ts +++ b/ets1.2/libarkts/test/ts-api/general/abc-gen.test.ts @@ -15,6 +15,7 @@ import * as util from "../../test-util" import * as ts from "../../../src/ts-api" +export { test, suite, assert } from "@koalaui/harness" // tests for abc generation (now failing on CI) suite.skip(util.basename(__filename), () => { @@ -44,7 +45,7 @@ suite.skip(util.basename(__filename), () => { ts.factory.updateSourceFile(sourceFile, newStatements) - util.assertEqualsBinaryOutput('ABC', this) + util.assertEqualsBinaryOutput('ABC') }) test("updating-function-declaration", function() { @@ -80,7 +81,7 @@ suite.skip(util.basename(__filename), () => { ts.factory.updateSourceFile(sourceFile, newStatements) - util.assertEqualsBinaryOutput('A', this) + util.assertEqualsBinaryOutput('A') }) test("updating-lambda-call", function() { @@ -125,7 +126,7 @@ suite.skip(util.basename(__filename), () => { ] ts.factory.updateSourceFile(sourceFile, newStatements) - util.assertEqualsBinaryOutput('', this) + util.assertEqualsBinaryOutput('') }) test("changing-variable-annotation", function() { @@ -174,7 +175,7 @@ suite.skip(util.basename(__filename), () => { ] ) - util.assertEqualsBinaryOutput('ok', this) + util.assertEqualsBinaryOutput('ok') }) test.skip("function-expression", function() { @@ -185,6 +186,6 @@ suite.skip(util.basename(__filename), () => { ` ts.factory.createSourceFile(sample_in) - util.assertEqualsBinaryOutput('abc', this) + util.assertEqualsBinaryOutput('abc') }) }) -- Gitee From 580a819efb22a1a0e7f96c12c2122d2d8b0d0cf8 Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Fri, 12 Sep 2025 13:45:50 +0300 Subject: [PATCH 02/15] Upd: restore/keep "koala_integration.gni" Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/koala_integration.gni | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 ets1.2/koala_integration.gni diff --git a/ets1.2/koala_integration.gni b/ets1.2/koala_integration.gni new file mode 100644 index 000000000..5295f7960 --- /dev/null +++ b/ets1.2/koala_integration.gni @@ -0,0 +1,25 @@ +# 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. + +koala_mr = { + root_path = "//developtools/ace_ets2bundle/ets1.2" + scripts_path = "$root_path/gn/script" + imports_prefix = "$root_path/gn/import" + libarkts_path = "$root_path/libarkts" + 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") -- Gitee From 31f3e02adc4a0fd0a8a8482cb84bebe1543a702b Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:04:59 +0300 Subject: [PATCH 03/15] Upd: Code-check: rename "ets1.2/libarkts/rollup{.=>-}lib.mjs" Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/libarkts/{rollup.lib.mjs => rollup-lib.mjs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ets1.2/libarkts/{rollup.lib.mjs => rollup-lib.mjs} (100%) 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 6d0e1e607fce2f37261be70c3a7489e14245c894 Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:22:18 +0300 Subject: [PATCH 04/15] Upd: Code-check: rename func args (which hide global ones) Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/libarkts/gn/command/copy.py | 4 ++-- ets1.2/libarkts/native/src/common.cc | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) 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/native/src/common.cc b/ets1.2/libarkts/native/src/common.cc index 87fa3b0b0..eb73b6ced 100644 --- a/ets1.2/libarkts/native/src/common.cc +++ b/ets1.2/libarkts/native/src/common.cc @@ -442,15 +442,15 @@ struct Pattern { return false; } - bool matchWildcard(const std::string& pattern, const char* value) + bool matchWildcard(const std::string& pattern, const char* valueArg) { if (pattern.find('*') == std::string::npos) { - return pattern == value; + return pattern == valueArg; } regex_t regex; regmatch_t match[1]; regcomp(®ex, pattern.c_str(), REG_NEWLINE); - return regexec(®ex, value, 1, match, 0) != REG_NOMATCH; + return regexec(®ex, valueArg, 1, match, 0) != REG_NOMATCH; } }; -- Gitee From 677d9b4c2343533cadafff6adbdfaf2c045c7a6c Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:41:22 +0300 Subject: [PATCH 05/15] Fix: of renamed "ets1.2/libarkts/rollup{.=>-}lib.mjs" Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/libarkts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets1.2/libarkts/package.json b/ets1.2/libarkts/package.json index 42578447a..a79297c80 100644 --- a/ets1.2/libarkts/package.json +++ b/ets1.2/libarkts/package.json @@ -60,7 +60,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 regenerate && 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", -- Gitee From a42928bf5d75430c92269450c510c12c550152ad Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 14:19:50 +0300 Subject: [PATCH 06/15] Upd: Code-check: Copyright to "interop/src/{arkts,interop}/events.ts" Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/interop/src/arkts/events.ts | 15 +++++++++++++++ ets1.2/interop/src/interop/events.ts | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/ets1.2/interop/src/arkts/events.ts b/ets1.2/interop/src/arkts/events.ts index cc06b90c5..2d57f84a0 100644 --- a/ets1.2/interop/src/arkts/events.ts +++ b/ets1.2/interop/src/arkts/events.ts @@ -1,3 +1,18 @@ +/* + * Copyright (c) 2022-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 + * + * 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 { int32 } from '@koalaui/common'; import { DeserializerBase } from './DeserializerBase'; import { InteropNativeModule } from './InteropNativeModule'; diff --git a/ets1.2/interop/src/interop/events.ts b/ets1.2/interop/src/interop/events.ts index 05b11d771..4cc5c4488 100644 --- a/ets1.2/interop/src/interop/events.ts +++ b/ets1.2/interop/src/interop/events.ts @@ -1,3 +1,18 @@ +/* + * Copyright (c) 2022-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 + * + * 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 { int32 } from '@koalaui/common'; import { DeserializerBase } from './DeserializerBase'; import { InteropNativeModule } from './InteropNativeModule'; -- Gitee From ac78f947b78e5f88b961439e6d6d0449201faf0f Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 14:29:32 +0300 Subject: [PATCH 07/15] Upd: Code-check: "args"=>"npm_args" "gn/command/npm_util.py" Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/gn/command/npm_util.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ets1.2/gn/command/npm_util.py b/ets1.2/gn/command/npm_util.py index 2dec5865c..626c86ddf 100755 --- a/ets1.2/gn/command/npm_util.py +++ b/ets1.2/gn/command/npm_util.py @@ -53,17 +53,17 @@ if args.stdlib_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, "a+") 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) print(open(koala_log, "r").read()) raise Exception("npm failed") f.close() -- Gitee From 653eb7e61cc29226402a51b619ed45f40a20dd6b Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:07:45 +0300 Subject: [PATCH 08/15] Upd: Code-check: rename argument "args=>npm_args" ("gn/script/npm.py") Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/gn/script/npm.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ets1.2/gn/script/npm.py b/ets1.2/gn/script/npm.py index 7bcc018a3..db6f176cd 100755 --- a/ets1.2/gn/script/npm.py +++ b/ets1.2/gn/script/npm.py @@ -56,17 +56,17 @@ 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, "a+") 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) print(open(koala_log, "r").read()) raise Exception("npm failed") f.close() -- Gitee From 16e4265659e292a794c7c310c6f17aa8419cc6a9 Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:09:59 +0300 Subject: [PATCH 09/15] Upd: Code-check: remove commented code ("gn/script/npm.py") Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/gn/script/npm.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ets1.2/gn/script/npm.py b/ets1.2/gn/script/npm.py index db6f176cd..09499e008 100755 --- a/ets1.2/gn/script/npm.py +++ b/ets1.2/gn/script/npm.py @@ -54,7 +54,6 @@ 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): os.chdir(dir or project_path) -- Gitee From 52eb38e57715dcc6e198038953d7454ebbf7afcf Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:14:57 +0300 Subject: [PATCH 10/15] Upd: Code-check: magic number => named Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/interop/src/cpp/DeserializerBase.h | 9 +++++++-- ets1.2/interop/src/cpp/SerializerBase.h | 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 | 12 ++++++++---- 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 | 14 +++++++++----- ets1.2/interop/src/cpp/vmloader.cc | 3 ++- 9 files changed, 46 insertions(+), 22 deletions(-) diff --git a/ets1.2/interop/src/cpp/DeserializerBase.h b/ets1.2/interop/src/cpp/DeserializerBase.h index 360ccaea6..d15af0752 100644 --- a/ets1.2/interop/src/cpp/DeserializerBase.h +++ b/ets1.2/interop/src/cpp/DeserializerBase.h @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -541,7 +542,9 @@ inline void WriteToString(std::string* result, InteropFloat32 value) result->append(buf); #else std::string storage; - storage.resize(20); + constexpr auto BUF_SIZE{20}; + static_assert(BUF_SIZE >= std::numeric_limits::max_digits10, "O-ou!"); + 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()); @@ -558,7 +561,9 @@ inline void WriteToString(std::string* result, InteropFloat64 value) result->append(buf); #else std::string storage; - storage.resize(20); + constexpr auto BUF_SIZE{20}; + static_assert(BUF_SIZE >= std::numeric_limits::max_digits10, "O-ou!"); + 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..74e03c880 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 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"); @@ -119,7 +120,9 @@ public: { 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/jni/convertors-jni.cc b/ets1.2/interop/src/cpp/jni/convertors-jni.cc index 7918b9721..a3a77268b 100644 --- a/ets1.2/interop/src/cpp/jni/convertors-jni.cc +++ b/ets1.2/interop/src/cpp/jni/convertors-jni.cc @@ -34,9 +34,12 @@ static bool registerNatives( 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]); + constexpr auto NUM_0{0}; + constexpr auto NUM_1{1}; + constexpr auto NUM_2{2}; + 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..0c0b56f14 100644 --- a/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc +++ b/ets1.2/interop/src/cpp/jsc/convertors-jsc.cc @@ -156,12 +156,14 @@ 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); + contexpr auto ARGUMENT_COUNT{sizeof(parts)/sizeof(parts[0])}; + bigint = JSObjectCallAsFunction(context, bigIntFromParts, nullptr, ARGUMENT_COUNT, parts, nullptr); #else char buffer[128] = { 0 }; interop_snprintf(buffer, sizeof(buffer) - 1, "%zun", static_cast(value)); JSStringRef script = JSStringCreateWithUTF8CString(buffer); - bigint = JSEvaluateScript(context, script, nullptr, nullptr, 0, nullptr); + contexpr auto ARGUMENT_COUNT{0}; + bigint = JSEvaluateScript(context, script, nullptr, nullptr, ARGUMENT_COUNT, 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 4b86ca1eb..1e89c6742 100644 --- a/ets1.2/interop/src/cpp/napi/convertors-napi.h +++ b/ets1.2/interop/src/cpp/napi/convertors-napi.h @@ -205,14 +205,18 @@ 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 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; 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..e97a0fe96 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]; + 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 * 100.0, (long long)ns); + (long long)count, (double)ns / total * PERCENT_100, (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 d9856c2a8..16a1dbdcc 100644 --- a/ets1.2/interop/src/cpp/types/koala-types.h +++ b/ets1.2/interop/src/cpp/types/koala-types.h @@ -105,19 +105,21 @@ struct KStringPtrImpl { return _length; } - void resize(int size) + void resize(int length) { - _length = size; + _length = length; if (!_owned) return; // Ignore old content. if (_value && _owned) free(_value); - _value = reinterpret_cast(malloc(size + 1)); + // G.MEM.01: Memory alloc size "length" should be checked. + 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) @@ -131,7 +133,9 @@ struct KStringPtrImpl { free(_value); if (data) { if (_owned) { - _value = reinterpret_cast(malloc(length + 1)); + // G.MEM.01: Memory alloc size "length" should be checked. + 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..e9693e89d 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 auto RESERVE_SIZE{255}; + result.reserve(RESERVE_SIZE); if (sdkPath) { result.append(sdkPath).append("/"); } -- Gitee From 1ebc8e4c809a01aca089415e0997f264f7411a8b Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:16:24 +0300 Subject: [PATCH 11/15] Upd: Code-check: C=>C++ headers includes Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/interop/src/cpp/ani/convertors-ani.cc | 2 +- ets1.2/interop/src/cpp/interop-logging.cc | 2 +- ets1.2/interop/src/cpp/ohos/hilog/log.h | 3 +-- 3 files changed, 3 insertions(+), 4 deletions(-) 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/interop-logging.cc b/ets1.2/interop/src/cpp/interop-logging.cc index 4fb30b938..568ffe870 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 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" { -- Gitee From 675471b800055be0ab4bf05bd7f30e4c60270228 Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:19:43 +0300 Subject: [PATCH 12/15] Upd: Code-check: rename __*** macroses (non-internal natation) Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/interop/src/cpp/common-interop.cc | 7 ++----- ets1.2/interop/src/cpp/napi/convertors-napi.h | 4 ++-- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/ets1.2/interop/src/cpp/common-interop.cc b/ets1.2/interop/src/cpp/common-interop.cc index b367d4f6d..03abb75bd 100644 --- a/ets1.2/interop/src/cpp/common-interop.cc +++ b/ets1.2/interop/src/cpp/common-interop.cc @@ -514,11 +514,8 @@ void impl_SetForeignVMContext(KNativePointer foreignVMContextRaw) } KOALA_INTEROP_V1(SetForeignVMContext, KNativePointer) -#ifndef __QUOTE -#define __QUOTE(x) #x -#endif - -#define QUOTE(x) __QUOTE(x) +#define QUOTE2(x) #x +#define QUOTE(x) QUOTE2(x) void impl_NativeLog(const KStringPtr& str) { diff --git a/ets1.2/interop/src/cpp/napi/convertors-napi.h b/ets1.2/interop/src/cpp/napi/convertors-napi.h index 1e89c6742..edfa1dcbb 100644 --- a/ets1.2/interop/src/cpp/napi/convertors-napi.h +++ b/ets1.2/interop/src/cpp/napi/convertors-napi.h @@ -821,8 +821,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) \ -- Gitee From 6bb413498f8aade8ac5e79861085265f0e7ba4c4 Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:20:36 +0300 Subject: [PATCH 13/15] Upd: Code-check: return string::c_str() Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/interop/src/cpp/interop-logging.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ets1.2/interop/src/cpp/interop-logging.cc b/ets1.2/interop/src/cpp/interop-logging.cc index 568ffe870..e4b471c27 100644 --- a/ets1.2/interop/src/cpp/interop-logging.cc +++ b/ets1.2/interop/src/cpp/interop-logging.cc @@ -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 ""; } -- Gitee From 68576a659e275e631ff7b7540b768f89d0ff52bf Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 15:23:21 +0300 Subject: [PATCH 14/15] Upd: Code-check: use static_cast(.) (for completeness only) Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/interop/src/cpp/SerializerBase.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets1.2/interop/src/cpp/SerializerBase.h b/ets1.2/interop/src/cpp/SerializerBase.h index 74e03c880..5fea792cc 100644 --- a/ets1.2/interop/src/cpp/SerializerBase.h +++ b/ets1.2/interop/src/cpp/SerializerBase.h @@ -251,7 +251,7 @@ public: void writeBuffer(InteropBuffer interopBuffer) { writeCallbackResource(interopBuffer.resource); - writePointer((void*)interopBuffer.data); + writePointer(static_cast(interopBuffer.data)); writeInt64(interopBuffer.length); } -- Gitee From 812efaf31acab496cfeda3290a8cc761e2496f82 Mon Sep 17 00:00:00 2001 From: "Alexander Ilyenko (WX1330152)" Date: Wed, 10 Sep 2025 16:25:55 +0300 Subject: [PATCH 15/15] Fix: of renamed of some magic digits Signed-off-by: Alexander Ilyenko (WX1330152) --- ets1.2/interop/src/cpp/napi/convertors-napi.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ets1.2/interop/src/cpp/napi/convertors-napi.h b/ets1.2/interop/src/cpp/napi/convertors-napi.h index edfa1dcbb..45f9ab142 100644 --- a/ets1.2/interop/src/cpp/napi/convertors-napi.h +++ b/ets1.2/interop/src/cpp/napi/convertors-napi.h @@ -207,8 +207,8 @@ 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}; + constexpr auto NUM_8{8}; switch (size) { case NUM_1: return napi_uint8_array; -- Gitee