diff --git a/ets1.2/common/package.json b/ets1.2/common/package.json index 1f2687d5cdd32a052ac04f2dc8d75a62f971ad87..103b6d79db093a81434b1819a0328c45f41ba2cb 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 88f6be9444ea648c67360f785c31d75959798d09..f28ece65d700d7e0b74824e5963b0a5c598100e6 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 264154f995859e0a073f69f2b327eb43572dff06..e854d0bc1ec8cbcdf767ef16821db712db288b4e 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 c6b6809cfa12b8dcbdcbe03f3bbfd69eb9a3b507..626c86ddfdc715a4c44004338282be6e069fa9a4 100755 --- a/ets1.2/gn/command/npm_util.py +++ b/ets1.2/gn/command/npm_util.py @@ -59,7 +59,6 @@ def run(npm_args, dir = None): if os.environ.get("KOALA_LOG_STDOUT"): subprocess.run(["npm"] + npm_args, env=os.environ, text=True, check=True, stderr=subprocess.STDOUT) return - result = subprocess.run(["npm"] + npm_args, capture_output=True, env=os.environ, text=True) with open(koala_log, "a+") as f: f.write(f"npm args: {npm_args}; project: {project_path}:\n" + result.stdout) diff --git a/ets1.2/interop/src/arkts/events.ts b/ets1.2/interop/src/arkts/events.ts index c6b3eddc3e292e843a149cac82467f3a1b6b7d8f..2d57f84a0279ca9b27a532c2499982aa24f38898 100644 --- a/ets1.2/interop/src/arkts/events.ts +++ b/ets1.2/interop/src/arkts/events.ts @@ -76,17 +76,17 @@ function checkSingleEvent(): boolean { return true; } case CallbackEventKind.Event_HoldManagedResource: { - const resourceId = deserializer.readInt32() - ResourceHolder.instance().hold(resourceId) + const resourceId = deserializer.readInt32(); + ResourceHolder.instance().hold(resourceId); return true; } case CallbackEventKind.Event_ReleaseManagedResource: { - const resourceId = deserializer.readInt32() - ResourceHolder.instance().release(resourceId) + const resourceId = deserializer.readInt32(); + ResourceHolder.instance().release(resourceId); return true; } default: { - throw new Error(`Unknown callback event kind ${eventKind}`) + throw new Error(`Unknown callback event kind ${eventKind}`); } } } diff --git a/ets1.2/interop/src/cpp/DeserializerBase.h b/ets1.2/interop/src/cpp/DeserializerBase.h index 3c0119355df13bb542fa3990a8c269c5b0c280b8..d15af07525319b045d4ed11eee1d6d6156a03e49 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 @@ -542,7 +543,7 @@ inline void WriteToString(std::string* result, InteropFloat32 value) #else std::string storage; constexpr auto BUF_SIZE{20}; - static_assert(BUF_SIZE >= std::numeric_limits::max_digits10, "O-ou!"); + 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); diff --git a/ets1.2/interop/src/cpp/SerializerBase.h b/ets1.2/interop/src/cpp/SerializerBase.h index 52e2c942ecd4b08f3aee2d78e5a8009b1d05abb8..5fea792ccf91dfb6597f7a7c31b34d9e38f07f30 100644 --- a/ets1.2/interop/src/cpp/SerializerBase.h +++ b/ets1.2/interop/src/cpp/SerializerBase.h @@ -34,210 +34,238 @@ #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) + { + 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)); #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(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 }; + } + } }; -#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 e0a605744c531444701e8fac4243e4412cb8251e..e84694d98e7147556c26238e44d367f64b13b4ea 100644 --- a/ets1.2/interop/src/cpp/ani/convertors-ani.cc +++ b/ets1.2/interop/src/cpp/ani/convertors-ani.cc @@ -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 79939d006896fb195805dad26eb262d3d2a08485..cc46d7998bfe4ee0e2758d5411fd97681c02a40b 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 ce615df1a32c0c8ddaff775f3713dede82475cda..03abb75bd31f29fe17ab127276307fb926489d44 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,734 @@ 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 - #define QUOTE(x) QUOTE2(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 cf8f809ba294943a457bcb111d5f7ce38d06ae25..e4b471c2736bdab63eb78d6f7f83190d71c8d949 100644 --- a/ets1.2/interop/src/cpp/interop-logging.cc +++ b/ets1.2/interop/src/cpp/interop-logging.cc @@ -97,4 +97,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 38071548f68fe469641d90c447c16b78e5a2a7c2..a3a77268b1e4d037ad61fae71850ccf271c7f9b6 100644 --- a/ets1.2/interop/src/cpp/jni/convertors-jni.cc +++ b/ets1.2/interop/src/cpp/jni/convertors-jni.cc @@ -30,13 +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++) { + 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]); diff --git a/ets1.2/interop/src/cpp/napi/convertors-napi.h b/ets1.2/interop/src/cpp/napi/convertors-napi.h index 4e75183815fff691a282bd75c6383cd81d30e58b..45f9ab142dcdb32e8cf219d946b06845db4e5178 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 @@ -206,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; @@ -248,6 +249,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 +437,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 +449,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 +461,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 +625,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) { diff --git a/ets1.2/interop/src/cpp/profiler.h b/ets1.2/interop/src/cpp/profiler.h index a99c8173d117aa44283668937e714f2a2d59cb79..e97a0fe968e0d82660c4832acf80fac0df539dd4 100644 --- a/ets1.2/interop/src/cpp/profiler.h +++ b/ets1.2/interop/src/cpp/profiler.h @@ -104,4 +104,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 6cb7f2685b9e6ec5528f00ba503f020e408433ca..16a1dbdccf9ca88be0544b397b18262f11701d3f 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 @@ -104,20 +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); - auto memSize{static_cast(std::max(0, 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"); } - _value[length] = 0; + _value[_length] = 0; } void assign(const char* data) @@ -131,6 +133,7 @@ struct KStringPtrImpl { free(_value); if (data) { if (_owned) { + // 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) { @@ -161,6 +164,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 +271,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/interop/events.ts b/ets1.2/interop/src/interop/events.ts index 3f1096066d24ced94686f9b94ec47ee602ad52f1..4cc5c448886e2af4d944b0c59d0ca2dc3dca7c5a 100644 --- a/ets1.2/interop/src/interop/events.ts +++ b/ets1.2/interop/src/interop/events.ts @@ -75,17 +75,17 @@ function checkSingleEvent(): boolean { return true; } case CallbackEventKind.Event_HoldManagedResource: { - const resourceId = deserializer.readInt32() - ResourceHolder.instance().hold(resourceId) + const resourceId = deserializer.readInt32(); + ResourceHolder.instance().hold(resourceId); return true; } case CallbackEventKind.Event_ReleaseManagedResource: { - const resourceId = deserializer.readInt32() - ResourceHolder.instance().release(resourceId) + const resourceId = deserializer.readInt32(); + ResourceHolder.instance().release(resourceId); return true; } default: { - throw new Error(`Unknown callback event kind ${eventKind}`) + throw new Error(`Unknown callback event kind ${eventKind}`); } } } diff --git a/ets1.2/libarkts/.prettierrc b/ets1.2/libarkts/.prettierrc index 0ac1c22344baf59186eae700aea827a7a367830b..e9e9c6fdb49bbeff983dca7cf4474097cf81de5d 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 54ac0975bbe1f9893d174e575cd4a8acabc641e3..ca0e1fc7a8b81ec388edc486406deebf36acc6ea 100755 --- a/ets1.2/libarkts/gn/command/copy.py +++ b/ets1.2/libarkts/gn/command/copy.py @@ -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 d19ed1a8843237c464fb7475a5d512279d2cee85..77075af1c1e7e72bce5f6ec2468806a87212bd66 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 116fb46126e3fec770a52f3c3d1db3f244bcebe5..eb73b6cedb0d4d3837be3a8eb2d29f5179913bc2 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) diff --git a/ets1.2/libarkts/native/src/common.h b/ets1.2/libarkts/native/src/common.h index f2eeeb0e786a117b34eecc2da6e72c96bc98ad90..770d2a2ad3bfb260902ace5243b300d699f20ab2 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 f391b800caa97f81a0445105bd26ae396c75eb99..a79297c80e2a250001f2d2d029c92082fd429f00 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,8 +59,8 @@ "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:js": "rm -rf lib/ && rollup -c rollup.lib.mjs && rollup -c rollup.es2panda.mjs", + "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", "simultaneous": "mkdir -p build/abc && bash ../../incremental/tools/panda/arkts/ui2abc --simultaneous --arktsconfig arktsconfig.json --output ./build/abc/main.abc:./build/abc/library.abc plugins/input/main.ets:plugins/input/library.ets", diff --git a/ets1.2/libarkts/playground/src/playground.cc b/ets1.2/libarkts/playground/src/playground.cc deleted file mode 100644 index d142c008133ad14d5d18105bb23e57d70086ae5e..0000000000000000000000000000000000000000 --- 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 26f331cdc1d34347d7a6bcbe444ea16ff8e68bf7..0000000000000000000000000000000000000000 --- 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/src-host/es2panda.ts b/ets1.2/libarkts/src-host/es2panda.ts index c7440f0d281dfea58305693ec34b80ee2ba3999c..600e8aa9238f5d099b15b90f277f485e3fd69555 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 3132fc8dee3e6c019dfb718b87a078fb4c850ead..cb407b283ff3843c5587cac01a0d13821bca4563 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 d222e07f1c73862420e76c235fecf1fe12f58649..c57973324640080ce47a389a943f17e7b71560ff 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 f6564beff7b60458e139afb6c6a39391ca1f11bf..f98d5fd1370e6a9aafb989f7429214bcd24bffc5 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 e76d7c4bbc45371129b970f9aaa36ea341b59ec8..2c4294255ce910acb1909fb524b4eba22a813f61 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 ee4890ba3bf217899a3d0114f8887c72330969f3..a5af6f0b9fafabb106040f16869b875bf0bd5c4e 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 f233a7084fd59dbe6aa05268fcc978623844499a..e169467bb81f357357c8708b4dbb0d880a023684 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 a4727774f54da7c2007c05245cd332913f2fe1ea..44d6d824555d0f3bb307947dfc6e6e4238e48f54 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 39e8569f3c8720ab00ce3ad15739cebcdb9f7218..419b97904c9d02f43506fad298e3acec95130cfa 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 2b32f9208e759d153d37519452b02ac48d1c9873..2e8b3b10dc6763dde7c64d66b506e047ef9a86a3 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 d48f5918c712d3fb6b32d0107dee051cb40f1ddb..5f06f4d6a3bec34e897c3504095957d0b6892fc2 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 73b4e6e80f2dbc1d2af6d546edf964abd549d6e9..5d46f652e952db5b59d153456653afa889f74ea5 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 0a8411de1c3e965ef51d80ddcfc59605c7635b4c..413e3f45433d63f83635710da10924e5a3cf9eef 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') }) })